# mare: Complete English Documentation Source: https://signalridge.github.io/mare/en/ Pages: 41 ================================================================================ Title: Installation Section: Get started URL: https://signalridge.github.io/mare/en/get-started/installation/ Markdown: https://signalridge.github.io/mare/raw/en/get-started/installation.md Source: docs/en/get-started/installation.md ================================================================================ # Installation Install mare using the method best suited to your operating system, then run `mare init` and `mare doctor` to verify the setup. ## Supported platforms Release artifacts are built for six targets (`.github/workflows/release.yaml`): | Platform | Target | Artifacts | | --- | --- | --- | | macOS, Apple silicon | `aarch64-apple-darwin` | `.tar.gz`, Homebrew cask, Nix | | macOS, Intel | `x86_64-apple-darwin` | `.tar.gz`, Homebrew cask, Nix | | Linux, x86-64 (glibc 2.39+) | `x86_64-unknown-linux-gnu` | `.tar.gz`, `.deb`, `.rpm`, Homebrew cask, AUR, Nix, GHCR container | | Linux, ARM64 (glibc 2.39+) | `aarch64-unknown-linux-gnu` | `.tar.gz`, `.deb`, `.rpm`, Homebrew cask, AUR, Nix, GHCR container | | Windows, x86-64 | `x86_64-pc-windows-msvc` | `.zip`, Scoop manifest | | Windows, ARM64 | `aarch64-pc-windows-msvc` | `.zip`, Scoop manifest | mare keeps its files in XDG-style directories on every platform, including Windows (see [Files mare uses](https://signalridge.github.io/mare/en/get-started/installation/#files-mare-uses)). ## macOS ### Quick install script Download the latest macOS archive (`aarch64-apple-darwin` or `x86_64-apple-darwin`) and verify its SHA-256 checksum against `checksums.txt`: ```sh curl -fsSL https://signalridge.github.io/mare/install.sh | sh ``` By default, the script installs `mare` into `~/.local/bin`. Override `MARE_INSTALL_DIR` to change the target directory, or set `MARE_VERSION=vX.Y.Z` to install a specific release. ### Homebrew cask ```sh brew tap signalridge/tap brew trust signalridge/tap brew install --cask mare ``` ### Nix (Flake and NUR) ```sh # Flake (run directly or install to your profile) nix run github:signalridge/mare nix profile install github:signalridge/mare#mare # NUR prebuilt binary nix profile install github:signalridge/nur-packages#mare ``` ### Manual archive (`.tar.gz`) Download `mare-$VERSION-$TARGET.tar.gz` and its `.sha256` file from [GitHub Releases](https://github.com/signalridge/mare/releases), verify the digest with `shasum -a 256`, and install: ```sh VERSION=vX.Y.Z TARGET=aarch64-apple-darwin # or x86_64-apple-darwin for Intel Macs ARCHIVE="mare-$VERSION-$TARGET.tar.gz" EXPECTED=$(awk 'NR==1 && length($1)==64 && $1 ~ /^[[:xdigit:]]+$/{print tolower($1)}' "$ARCHIVE.sha256") ACTUAL=$(shasum -a 256 "$ARCHIVE" | awk 'NR==1{print tolower($1)}') if [ -n "$EXPECTED" ] && [ "$ACTUAL" = "$EXPECTED" ]; then mkdir -p ~/.local/bin && tar xzf "$ARCHIVE" && install -m 755 "mare-$VERSION-$TARGET/mare" ~/.local/bin/mare && ~/.local/bin/mare --version else echo "Checksum mismatch: expected $EXPECTED, got $ACTUAL" >&2 false fi ``` ## Linux ### Quick install script Download the latest Linux archive (`x86_64-unknown-linux-gnu` or `aarch64-unknown-linux-gnu`, glibc 2.39+) and verify its SHA-256 checksum against `checksums.txt`: ```sh curl -fsSL https://signalridge.github.io/mare/install.sh | sh ``` By default, the script installs `mare` into `~/.local/bin`. Override `MARE_INSTALL_DIR` to change the target directory, or set `MARE_VERSION=vX.Y.Z` to install a specific release. ### Debian / Ubuntu (`.deb`) Download the `.deb` package matching your architecture (`amd64` or `arm64`) from [GitHub Releases](https://github.com/signalridge/mare/releases), verify its digest against `checksums.txt`, and install: ```sh sudo apt install ./mare__linux_amd64.deb # or for ARM64: sudo apt install ./mare__linux_arm64.deb ``` ### Fedora / RHEL (`.rpm`) Download the `.rpm` package matching your architecture (`amd64` or `arm64`) from [GitHub Releases](https://github.com/signalridge/mare/releases), verify its digest against `checksums.txt`, and install: ```sh sudo dnf install ./mare__linux_amd64.rpm # or for ARM64: sudo dnf install ./mare__linux_arm64.rpm ``` ### Arch Linux (AUR) ```sh yay -S mare-bin # or: paru -S mare-bin ``` ### Homebrew (Linuxbrew) ```sh brew tap signalridge/tap brew trust signalridge/tap brew install --cask mare ``` ### Nix (Flake and NUR) ```sh # Flake (run directly or install to your profile) nix run github:signalridge/mare nix profile install github:signalridge/mare#mare # NUR prebuilt binary nix profile install github:signalridge/nur-packages#mare ``` ### Manual archive (`.tar.gz`) Download `mare-$VERSION-$TARGET.tar.gz` and its `.sha256` file from [GitHub Releases](https://github.com/signalridge/mare/releases), verify the digest with `sha256sum`, and install: ```sh VERSION=vX.Y.Z TARGET=x86_64-unknown-linux-gnu # or aarch64-unknown-linux-gnu for ARM64 ARCHIVE="mare-$VERSION-$TARGET.tar.gz" EXPECTED=$(awk 'NR==1 && length($1)==64 && $1 ~ /^[[:xdigit:]]+$/{print tolower($1)}' "$ARCHIVE.sha256") ACTUAL=$(sha256sum "$ARCHIVE" | awk 'NR==1{print tolower($1)}') if [ -n "$EXPECTED" ] && [ "$ACTUAL" = "$EXPECTED" ]; then mkdir -p ~/.local/bin && tar xzf "$ARCHIVE" && install -m 755 "mare-$VERSION-$TARGET/mare" ~/.local/bin/mare && ~/.local/bin/mare --version else echo "Checksum mismatch: expected $EXPECTED, got $ACTUAL" >&2 false fi ``` Make sure `~/.local/bin` (or the directory you chose) is on your `PATH`. On Linux, install `bubblewrap` through your distribution package manager if you want full namespace-based OS sandboxing (Landlock is also supported where the kernel enables it). ## Windows ### Quick install script (PowerShell) Download the latest Windows release archive (`x86_64-pc-windows-msvc` or `aarch64-pc-windows-msvc`), verify its SHA-256 checksum against `checksums.txt`, install `mare.exe` into `%LOCALAPPDATA%\mare\bin` (override with `$env:MARE_INSTALL_DIR`), and add it to your User `PATH`: ```powershell irm https://signalridge.github.io/mare/install.ps1 | iex ``` Set `$env:MARE_VERSION = "vX.Y.Z"` before running the command to pin a specific version. ### Scoop ```powershell scoop bucket add signalridge https://github.com/signalridge/scoop-bucket scoop install signalridge/mare ``` ### Manual archive (`.zip`) Download `mare-$v-$t.zip` and its `.sha256` file from [GitHub Releases](https://github.com/signalridge/mare/releases), verify the SHA-256 digest before extracting, then copy `mare-$v-$t\mare.exe` to a directory on your `PATH`: ```powershell $ErrorActionPreference = "Stop" $v = "vX.Y.Z"; $t = "x86_64-pc-windows-msvc" # or aarch64-pc-windows-msvc $archive = "mare-$v-$t.zip" $expected = ([string](Get-Content "$archive.sha256" -Raw)).Trim().Split()[0].ToLower() $actual = (Get-FileHash $archive -Algorithm SHA256).Hash.ToLower() if ($expected -notmatch '^[0-9a-f]{64}$' -or $actual -ne $expected) { throw "Checksum mismatch: expected $expected, got $actual" } Expand-Archive $archive -DestinationPath . ``` Windows also provides an optional enhanced sandbox tier. `mare sandbox status` shows whether it is installed and runs a self-test; `mare sandbox setup` installs it and asks for elevation once. ## Container (Docker / GHCR) Multi-architecture (`linux/amd64`, `linux/arm64`) images based on Ubuntu 24.04 (including `git` and `bubblewrap`) are published to GitHub Container Registry and signed with Cosign: ```sh docker pull ghcr.io/signalridge/mare:latest docker run --rm -it -v "$PWD:/workspace" -w /workspace ghcr.io/signalridge/mare:latest ``` ## Release artifacts and verification Releases are published on GitHub at [`signalridge/mare`](https://github.com/signalridge/mare/releases). Each published GitHub Release (`vX.Y.Z`) attaches: - `.tar.gz` archives (macOS and Linux) and `.zip` archives (Windows) with per-archive `.sha256` files; - `.deb` and `.rpm` packages for Linux (`amd64` and `arm64`); - `checksums.txt`, its Cosign signature bundle (`checksums.txt.sigstore.json`), SPDX SBOMs (`*.sbom.spdx.json`), and SLSA provenance (`multiple.intoto.jsonl`). Each archive unpacks into a single directory of the same base name containing the `mare` binary (`mare.exe` on Windows), a `types/` directory with Lua type definitions, `LICENSE`, `THIRD_PARTY_NOTICES.md`, `licenses/cordis-LICENSE`, `licenses/RUST-THIRD-PARTY-NOTICES.txt`, and `README.md`. ## Build from source You need the Rust toolchain at version 1.100.0 or newer (`rust-version` in `Cargo.toml`; the project uses edition 2024) and a C compiler, because the Lua 5.5 runtime is compiled from vendored sources. `rust-toolchain.toml` pins the exact release that CI and the release builds use, so rustup installs and selects it automatically inside the checkout. Install directly with Cargo: ```sh cargo install --git https://github.com/signalridge/mare --locked --bin mare mare-cli mare --version ``` Or clone the repository and build locally: ```sh git clone https://github.com/signalridge/mare cd mare cargo build --release --locked -p mare-cli ./target/release/mare --version ``` The release workflow builds exactly this way, with `--locked` so `Cargo.lock` decides dependency versions. Copy `target/release/mare` somewhere on your `PATH`. The release profile enables LTO, so a release build takes noticeably longer than a debug build. The repository also has a `justfile`: | Command | What it does | | --- | --- | | `just run ` | `cargo run -- `; debug builds read the built-in plugins from `crates/mare-plugin/preset` on disk, and `/reload` picks up edits | | `just release` | `cargo build --release` | | `just test` | Run workspace tests and doctests (requires cargo-nextest 0.9.138 or newer) | | `just check` | Lint and test | `mare --version` prints the version, the commit, the Git commit date, and the target. ## First setup Create a default configuration: ```sh mare init ``` `mare init` writes `~/.config/mare/init.lua` (an existing file is kept, never overwritten) and `~/.config/mare/.luarc.json`, which points LuaLS at the type definitions in `~/.local/share/mare/runtime/types`. Each line of output says whether a file was `created`, `wrote` or `kept`. If you edited `.luarc.json` yourself, mare leaves it alone. Then check the installation: ```sh mare doctor ``` `mare doctor` prints one line per check, with a check mark, a warning mark or a cross, and exits with `1` when any check fails. On a fresh machine two failures are expected: missing directories (mare creates them on first use) and no credentials. Create the directories and tighten file permissions with: ```sh mare doctor --fix ``` `--fix` creates missing directories, sets modes (`0700` for directories, `0600` for `auth.json` and `.jsonl` files directly inside the sessions directory), and attempts to repair a corrupt package lock file. The doctor run itself still does its normal start-up work (such as preparing the session index and runtime files). Add `--json` to get the checks as one JSON document. [Troubleshooting](https://signalridge.github.io/mare/en/get-started/troubleshooting/) lists what each check covers. Next, log in to a provider as described in the [Quickstart](https://signalridge.github.io/mare/en/get-started/quickstart/). ## Shell completion `mare completion ` prints a completion script for `bash`, `zsh`, `fish`, `elvish` or `powershell`: ```sh mare completion zsh > ~/.zfunc/_mare # zsh: ~/.zfunc must be in fpath mare completion bash > ~/.local/share/bash-completion/completions/mare mare completion fish > ~/.config/fish/completions/mare.fish ``` Restart the shell, or reload its completion system, to pick it up. ## Updating mare does not replace its own binary. To update: - If you installed via a package manager (`brew upgrade --cask mare`, `scoop update mare`, `yay -Syu mare-bin`, `nix profile upgrade mare`), use that package manager. - Otherwise, re-run the quick install script (`install.sh` / `install.ps1`) or download the newer archive, verify it, and overwrite the old `mare` binary. Release builds of the TUI check GitHub releases for a newer version every 24 hours by default (`update-check.interval_hours` adjusts the interval; debug builds skip automatic checks) and print one line if there is one. The request carries no identifier beyond `mare/`. Turn the check off in `init.lua`: ```lua mare.setup { update_check = false } ``` When the version changes, mare re-extracts its built-in plugins and types into `~/.local/share/mare/runtime` the next time it starts. Packages declared in `init.lua` are updated separately with `mare plugin update`. ## Files mare uses | Directory | Default | Contents | | --- | --- | --- | | Config | `~/.config/mare` | `init.lua`, `.luarc.json`, `auth.json` (credentials), `mare-lock.json` (package lock), `plugins/` (your plugins) | | State | `~/.local/state/mare` | `state.json` (runtime choices), `trust.json`, `sessions/`, `log/`, `crashes/` | | Data | `~/.local/share/mare` | `runtime/` (built-in plugins and types), `packages/` | | Cache | `~/.cache/mare` | `luac/` (compiled Lua bytecode cache) | `XDG_CONFIG_HOME`, `XDG_STATE_HOME`, `XDG_DATA_HOME` and `XDG_CACHE_HOME` move the corresponding directory (mare appends `mare`). Setting `MARE_HOME` puts `config`, `state`, `data` and `cache` under one directory instead, which is useful for trying a clean setup without touching your real one. `mare runtime` prints the runtime directory. A project can also have a `.mare/` directory with its own `init.lua`, plugins, skills and prompts. These only load after you trust the project; see the [Quickstart](https://signalridge.github.io/mare/en/get-started/quickstart/#trust-a-project). ## Uninstall 1. Optional: remove stored credentials with `mare logout`, which revokes tokens where the provider supports it. Without a provider name it works when exactly one provider is logged in; otherwise name one, as in `mare logout openai`. 2. Uninstall via your package manager (for example `brew uninstall --cask mare` or `scoop uninstall mare`), or delete the `mare` binary directly. 3. Delete the directories above if you want no trace left. Deleting the state directory removes all saved sessions. ```sh rm -rf ~/.config/mare ~/.local/state/mare ~/.local/share/mare ~/.cache/mare ``` Environment variables and keys you wrote into `init.lua` are not touched by `mare logout`; remove them yourself. ================================================================================ Title: Overview Section: Get started URL: https://signalridge.github.io/mare/en/get-started/overview/ Markdown: https://signalridge.github.io/mare/raw/en/get-started/overview.md Source: docs/en/get-started/overview.md ================================================================================ # Overview mare is an agent harness built as a small Rust core plus Lua 5.5 plugins that you can read, wrap, or replace. ## What mare is The Rust core provides OS confinement, durable storage, the Lua runtime, and the terminal renderer (`mare-tui` and `mare-cli`). The agent loop, tools, model providers, compaction, permission rules, and UI components, themes, and statusline ship as built-in Lua plugins inside the binary. ![mare layered architecture](https://signalridge.github.io/mare/assets/diagrams/architecture.svg) | Layer | Written in | What it does | | --- | --- | --- | | Core | Rust | Plugin kernel (events, services, lifecycle, watchdog), Lua runtime, OS sandbox, session storage, file snapshots, project trust, terminal renderer (`mare-tui`), mare RPC 3.0 (JSON-RPC 2.0) | | Built-in plugins | Lua 5.5 | Agent loop, tools, providers, compaction, permissions, approvals, sessions, slash commands, UI components, themes, statusline, review, background jobs, MCP client | | Your plugins | Lua 5.5 | Additions or overrides from `init.lua`, `~/.config/mare/plugins/`, `.mare/plugins/`, or installed packages | Run `mare runtime` to print the read-only directory containing the built-in plugin sources (`agent.lua`, `tools.lua`, ...) and Lua type definitions. ## Replace, not patch - Configure a plugin: `mare.plugin("tools", { bash_timeout_ms = 120000 })` - Add a tool, slash command, key binding, or style in `init.lua`. - Replace any built-in with a same-name plugin setting `override = true` (`/plugins` shows it as overriding the built-in). Core boundaries: - Core safety: Sandboxing, file/process permission checks, crash-safe JSONL writes, project trust, and the Lua watchdog (`watchdog_ms`) live in Rust. Replacing the agent loop preserves them for calls routed through the permissions plugin and guarded tool pipeline. - Trusted plugins: Plugins run as trusted code. A plugin that disables or replaces `permissions`, or calls primitives directly outside a tool call, is not confined by those checks. - Fault isolation: Failures in optional plugins or packages report a warning and are skipped; failures in essential services, plugins with `required = true`, or required packages block requests until fixed and `/reload`ed. `/plugins` shows tracebacks. ## One set of capabilities, five front ends | Front end | Command | Purpose | | --- | --- | --- | | Terminal UI | `mare` | Interactive terminal sessions (`mare-tui` + `mare-cli`) | | Headless | `mare -p "prompt"` or `mare --json "prompt"` | One-shot prompts and JSON streams for scripts and CI | | stdio RPC | `mare --rpc` | Drive sessions over mare RPC 3.0 (JSON-RPC 2.0; `mare rpc schema`) | | HTTP / WebSocket | `mare --web` | Authenticated HTTP routes and WebSocket RPC (web UI provided by plugins) | | ACP | `mare acp` | Editor integration (Agent Client Protocol) | In-process Lua (`init.lua` and plugins) runs in the extension layer shared by every front end. ## Scope and roadmap Deferred to later releases: `ralph`, `lsp`, `model-router`, and `worktree` plugins, `/import`, and HTML/JSONL session export (implementable as third-party plugins in the meantime). ## Next steps - [Installation](https://signalridge.github.io/mare/en/get-started/installation/) - [Quickstart](https://signalridge.github.io/mare/en/get-started/quickstart/) - [Workflows](https://signalridge.github.io/mare/en/get-started/workflows/) - [Plugins](https://signalridge.github.io/mare/en/extend/plugins/) and [Writing a plugin](https://signalridge.github.io/mare/en/extend/writing-a-plugin/) - [RPC](https://signalridge.github.io/mare/en/integrate/rpc/) and [ACP](https://signalridge.github.io/mare/en/integrate/acp/) ================================================================================ Title: Quickstart Section: Get started URL: https://signalridge.github.io/mare/en/get-started/quickstart/ Markdown: https://signalridge.github.io/mare/raw/en/get-started/quickstart.md Source: docs/en/get-started/quickstart.md ================================================================================ # Quickstart Log in to a provider, start `mare` in a repository, approve a tool call, and create `~/.config/mare/init.lua`. On first launch, you can pick optional plugins or skip and install them later via `/plugins` → Discover. ## Log in to a provider mare needs one model provider. The built-in providers are: | Provider name | Credential | Environment variable | | --- | --- | --- | | `openai` | ChatGPT login (browser or device code), or an API key | `OPENAI_API_KEY` | | `anthropic` | API key | `ANTHROPIC_API_KEY` | | `google` | API key | `GEMINI_API_KEY` or `GOOGLE_API_KEY` | | `opencode-go` | API key | `OPENCODE_API_KEY` | | `deepseek` | API key | `DEEPSEEK_API_KEY` | | `kimi` | API key | `MOONSHOT_API_KEY` | | `kimi-code` | API key | `KIMI_API_KEY` | | `openrouter` | API key | `OPENROUTER_API_KEY` | | `ollama` | Local server (`http://localhost:11434/v1`); no key required by default | — | | `lmstudio` | Local server (`http://localhost:1234/v1`); no key required by default | — | An API key in the environment variable works without logging in. `mare login` stores a credential in `~/.config/mare/auth.json` (mode `0600`); a stored login wins over the environment variable. Log in to OpenAI with a ChatGPT account: ```sh mare login openai ``` > Bare `mare login` tries the configured model's provider first. With no usable default, it opens a provider picker on a TTY and exits with code `2` without a TTY. mare opens a browser. On a machine without one, for example over SSH, use a device code instead: ```sh mare login openai --device-auth ``` For any provider that uses an API key, pipe the key in on stdin. mare never prompts for a key on the terminal: ```sh printenv ANTHROPIC_API_KEY | mare login anthropic --with-api-key ``` See which providers are logged in and where each credential comes from: ```sh mare login status ``` Remove credentials with `mare logout [provider]`. You can also skip this step. When no provider has a credential, the interactive UI starts a guided first-run flow: pick a provider, log in and choose a default model. `/login [provider]` does the same from inside a session. ## Start in a project ```sh cd ~/src/my-project mare ``` Pass an initial prompt as arguments to start with a question already asked: ```sh mare "what does this project do?" ``` ### Trust a project Some project files change what mare runs: `.mare/init.lua`, `.mare/plugins`, `.mare/skills`, `.mare/prompts`, `.mare/SYSTEM.md`, `.mare/APPEND_SYSTEM.md` and `.agents/skills`. mare loads them only in a trusted project. When you start in a directory that has any of them, or that is inside a git repository, and nothing is saved yet, a prompt appears: | Choice | Effect | | --- | --- | | Trust and load | Remember this folder as trusted and load the project's files now | | Trust this session only | Load the project's files for this session only; do not save to `trust.json` | | Don't trust | Remember the decision; never load them | | Not now (or Esc) | Load nothing this time and ask again next time | The prompt groups discovered resources (project config with a full-API warning for `.mare/init.lua`, plugins, skills, prompt templates, system prompt files, and sanitized MCP server summaries). When any group has more than six items, press `e` to expand or collapse the full list. Trusting a directory permanently also trusts later changes to those files, so trust only code you would run. Decisions are stored in `~/.local/state/mare/trust.json` and apply to subdirectories. You can also decide from the shell: ```sh mare trust # trust the current project (or pass a directory: mare trust ) mare trust --revoke # revoke it mare --trust # trust for this run only, save nothing mare --no-trust # distrust for this run only ``` ## Ask a question Type a question and press Enter. A good first one asks for a reading of the code: ```text How is the configuration loaded? Point me at the files. ``` The agent reads files with its tools and answers. The tool calls appear in the transcript. Press Ctrl+O to expand or collapse tool output and thinking, and Ctrl+T for the full transcript. Press Esc to interrupt a running turn. Press Enter while the agent is working to queue a message for when the turn finishes; see [Workflows](https://signalridge.github.io/mare/en/get-started/workflows/#steer-or-queue-while-the-agent-works). ## Approve a tool call The default permission preset is `auto`: the agent can write inside the workspace and temp directories without asking, and mare asks when a call would leave the sandbox. To see approvals right away, start with the `read-only` preset, where writing files needs your approval: ```sh mare --permission read-only "add a one-line comment to the top of README.md" ``` > Outbound network access is blocked where the OS sandbox supports it. On the default Windows tier, which cannot block network access, mare asks before shell and other command tools unless that unrestricted access is already approved. The approval box names the tool and offers these answers: | Key | Answer | | --- | --- | | `y` | Allow once | | `a` | Allow for this session | | `A` | Allow and remember the proposed rule (shown when mare can propose one) | | `n` | Deny, then tell the model why | | Esc | Deny this call; the turn goes on | | Ctrl+C | Deny and stop the turn | Switch presets inside a session with `/permission` (or `/permission auto`). The three presets are `read-only`, `auto` and `full-access`; `--yolo` is shorthand for `--permission full-access`. See [Permissions](https://signalridge.github.io/mare/en/use/permissions/). ## Mention files and run commands Type `@` and a path to attach a file to your message. Tab completes paths, and `@"a path with spaces"` quotes one: ```text Explain the retry logic in @src/client.rs ``` Text files are attached up to 100 KiB each (256 KiB per message). A file that cannot be attached gets a one-line note saying why, and the agent can still read it with its read tool. Start a line with `!` to run a shell command yourself. The command and its output go into the context, so the model sees them on its next turn. Use `!!` to run a command without adding anything to the context: ```text !git status --short !!ls -la ``` ## Choose a model `/model` opens a picker. Providers without credentials are grouped as needing login. Give a model reference directly to switch: ```text /model openai/gpt-6.1-terra ``` `/effort` sets the reasoning effort for the active model. You can also pass `-m/--model` and `-e/--effort` at start-up (or set `MARE_EFFORT`). `effort` is invocation-only as a global override: global `effort` in `init.lua` is ignored, whereas `model` in `init.lua` overrides the choice saved in `~/.local/state/mare/state.json`. `/status` shows the version, model, session, token use and each provider's login. `/help` lists every command. ## Resume a session Every conversation is saved under `~/.local/state/mare/sessions`. Leave with Ctrl+D on an empty input, or press Ctrl+C twice. Then come back: ```sh mare -c # continue the most recent session in this directory mare -r # pick a session from a list mare -r -2 # the second most recent session in this directory mare -r my-name # by name, id or unambiguous id prefix mare -c --fork-session # continue in a copy and leave the original alone ``` Add `--all` to `-c` or `-r` to look at sessions from every directory. Inside the UI, `/resume`, `/new`, `/name ` and `/fork` do the corresponding things. More in [Workflows](https://signalridge.github.io/mare/en/get-started/workflows/#continue-and-fork-sessions). ## Write your first init.lua Run `mare init` to create `~/.config/mare/init.lua` with commented examples (an existing file is preserved), then edit it: ```lua -- ~/.config/mare/init.lua mare.setup { model = "openai/gpt-6.1-terra", } -- give long shell commands more time mare.plugin("tools", { bash_timeout_ms = 300000 }) -- /m is a shortcut for /model mare.command.alias("m", "model") -- a grep tool backed by ripgrep (grep and find are not built in) mare.tool.command { name = "grep", description = "Search file contents with ripgrep.", command = { "rg", "--line-number", "--no-heading", "--max-columns=500", "--regexp={pattern}", "--", "{path}" }, params = { pattern = { type = "string", required = true }, path = { type = "string", default = "." }, }, } ``` Restart mare, or run `/reload config` inside a session. `mare.setup` warns about unknown option names and wrong types, with a "did you mean" hint; `/config` shows every option, its value and where it was set. A project's trusted `.mare/init.lua` runs after this file. Next: - [Workflows](https://signalridge.github.io/mare/en/get-started/workflows/) for recipes. - [Models](https://signalridge.github.io/mare/en/use/models/) and [Permissions](https://signalridge.github.io/mare/en/use/permissions/) for the choices you just made. - [Options](https://signalridge.github.io/mare/en/configure/options/) and [Key maps](https://signalridge.github.io/mare/en/configure/keymaps/) for what else `init.lua` can set. ================================================================================ Title: Troubleshooting Section: Get started URL: https://signalridge.github.io/mare/en/get-started/troubleshooting/ Markdown: https://signalridge.github.io/mare/raw/en/get-started/troubleshooting.md Source: docs/en/get-started/troubleshooting.md ================================================================================ # Troubleshooting How to find out why mare does not start, cannot reach a model, behaves differently than you configured, or draws wrongly in your terminal. ## Start with mare doctor ```sh mare doctor ``` `mare doctor` runs without calling a model. It prints one line per check and exits `1` if any check fails (`0` otherwise). A check mark means pass, `!` is a warning that does not fail the run and a cross is a failure. `mare doctor --json` prints the same checks as one JSON document, and `mare doctor --fix` creates missing directories, tightens permissions, and attempts to repair a corrupt package lock file (the run itself still does its normal start-up work, such as preparing the session index and runtime files). Inside a session, `/doctor` shows the checks the running session knows about, as an overlay. | Check | What it tells you | | --- | --- | | `directories`, `permissions` | The config, state, data, sessions and log directories exist; `auth.json`, the state directory and the sessions directory are private (`0600` / `0700`), as are `.jsonl` files directly inside it. Per-project session files in subdirectories are not checked. `--fix` repairs both | | `terminal capabilities` | Which terminal mare detected and whether it has truecolor, wide emoji, the kitty keyboard protocol and bracketed paste, plus known quirks of that terminal | | `config`, `model`, `config options` | Whether `init.lua` loads, which model is set, and any unknown option names or type errors in `mare.setup`, `mare.o` and `mare.plugin` | | `auth.json`, `auth.json mode` | A credentials file that does not parse is reported, never treated as "no credentials"; mare keeps a copy as `auth.json.bak` | | `sandbox` and `sandbox ...` | The sandbox backend on this machine (for example `bwrap` or `landlock` on Linux, Seatbelt on macOS) and which capabilities it can enforce | | `tmux clipboard`, `tmux keys` | Only inside tmux: whether `set-clipboard` and `extended-keys` are on | | `session files`, `session index` | Every saved session parses; a half-written last entry is reported as a warning; the session index is consistent | | `runtime`, `plugins` | The runtime directory is extracted; how many plugins are active and each plugin's problem, including which plugins override a built-in | | `permission policy`, `key conflicts` | The permissions service in use and the session sandbox level; key bindings that your terminal or OS probably intercepts | | `credential sources` | For each provider, where its credential comes from (a stored login, an environment variable, or none). Secrets are never printed | | connectivity | Reachability of the providers you have configured, never a fixed list | | `mcp ...`, `packages`, `skills`, `git` | Checks contributed by plugins: MCP servers, installed packages and the lock file, loaded skills, `git` on `PATH` | On Windows, `mare doctor` also reports legacy console hosts and whether Windows Terminal forwards `Shift+Enter` and `Alt+Enter`. Plugins add their own checks by listening to the `kernel/doctor` event; see [Services and events](https://signalridge.github.io/mare/en/extend/services-and-events/). ## Isolate the cause These flags narrow a problem down. Combine them with a normal start. | Flag | Effect | | --- | --- | | `--clean` | Skip `init.lua`, packages, user plugins and project plugins. Only the built-in plugins load, and the project is not trusted | | `--strict-config` | Refuse to start (exit `2`) when the configuration has warnings, instead of printing them. Applies to headless and RPC runs | | `--no-trust` | Do not trust this project for this run, whatever was saved | | `--no-session` | Do not read or write a session | | `--set KEY=VALUE` | Override one config value for this run, for example `--set plugins.tools.edit_mode=replace` | If `mare --clean` works and `mare` does not, the problem is in `init.lua`, a package, or a plugin. Bisect by commenting out parts of `init.lua`. If the problem is in a project, `mare --no-trust` tells you whether its `.mare/` files are the cause. To try mare with entirely fresh directories without touching your real ones, point `MARE_HOME` at an empty directory: `MARE_HOME=$(mktemp -d) mare doctor`. ## Slow start ```sh mare --profile-startup # start the UI, quit when ready, print the time of each stage mare --startuptime /tmp/start.txt # normal start, write the timing to a file (like nvim --startuptime) ``` Inside a session, `/profile` shows the startup timeline and each plugin's load time, plus changes to the tool list between model requests (a changed tool list invalidates the provider's prompt cache from that point). ## Configuration errors mare distinguishes warnings from errors. - Warnings are unknown option names, wrong types, and unparseable `MARE_*` environment values. The option name comes with a "did you mean" hint when one is close. Headless and RPC runs print warnings to stderr; add `--strict-config` to make them refuse to start (exit `2`). `/config` lists every option, its value and where it was set. - An error is an `init.lua` (or a trusted project's `.mare/init.lua`) that fails to run. The interactive UI shows a dialog with the file, the line and the first line of the error, and three choices: open the file in your editor at that line (the config runs again afterwards), exit, or continue. If you continue, the UI starts but every model request stays blocked until the file is fixed and `/reload` succeeds. Headless and RPC runs have no dialog and exit with `2`. - An optional plugin or package that fails to load reports a warning and is skipped. `/plugins` lists every plugin with its origin and, below them, each failure with a traceback; the traceback stays until a full `/reload` clears it. Startup notices say "fix it and /reload (or start clean: mare --clean)". - Failures in essential services, plugins marked `required = true`, or required packages (`required = true`) block model requests until fixed and `/reload`ed (or disabled). `mare plugin sync` installs the packages `init.lua` declares, `mare plugin list` shows them, and disabling a required package in `init.lua` stops it from blocking requests. Reload after editing: `/reload` reloads plugins, `/reload <plugin>` one plugin and `/reload config` the configuration. ## Credentials and models | Symptom | What to check | | --- | --- | | "X is not configured: run /login X or set ..." | `mare login status` shows each provider. Log in, or export the provider's variable (see the [Quickstart](https://signalridge.github.io/mare/en/get-started/quickstart/#log-in-to-a-provider)) | | A key in the environment is ignored | A stored login in `auth.json` wins over environment variables. `mare doctor` names a source that is set but not used. `mare logout <provider>` removes the stored one | | `mare login anthropic` says to pass the key on stdin | API-key providers read the key from stdin only: `printenv ANTHROPIC_API_KEY \| mare login anthropic --with-api-key` | | The ChatGPT browser login cannot open a browser | Over SSH, or on Linux without `DISPLAY` or `WAYLAND_DISPLAY`, use `mare login openai --device-auth` | | `/model` shows a provider as "needs login" | That provider has no credential yet; `/login <provider>` | | The model list is old or a model is missing | `mare model refresh` re-reads the model list of every logged-in provider | | `auth.json` is corrupt | Saved credentials cannot be read or changed until it is fixed. Fix the file, or delete it and log in again; `auth.json.bak` holds the copy mare made | | `mare logout` removed the login but the provider still works | The credential also comes from an environment variable or `init.lua`; `logout` tells you which one to remove | The first-run flow starts by itself in the interactive UI whenever no provider has a credential. ## Terminal problems - Run `/terminal-setup` to check whether `Shift+Enter` and `Alt+Enter` reach mare and to see how to fix them. Without `Shift+Enter`, type `\` and press Enter for a newline. - Inside tmux, `Shift+Enter` arrives as Enter unless `set -g extended-keys on` is in `tmux.conf`, and copying only reaches the system clipboard with `set -g set-clipboard on`. `mare doctor` checks both. - `TERM=dumb` selects a plain line-by-line mode with no cursor movement. - `mare doctor` lists key bindings that terminals or the OS commonly intercept (`key conflicts`) with a fix. Rebind with `mare.keymap.set`; see [Key maps](https://signalridge.github.io/mare/en/configure/keymaps/). - The screen is garbled after a program wrote to the terminal directly: press `Ctrl+L` to redraw. Output written to mare's stdout and stderr, including by child processes, is captured above the input box; only programs that open the terminal device themselves can disturb the screen. - Images show as `[image]`: the terminal supports none of the Kitty, iTerm2 or sixel protocols. `mare doctor` shows the detected capabilities. - On Windows, `Ctrl+V` is the terminal's text paste, so paste images with `Alt+V`, and `Ctrl+Z` cannot suspend mare. ## Sessions - `session files ... damaged` in `mare doctor`: the named file cannot be parsed. Open it read-only or fork it instead of continuing it. - `session torn writes`: the last entry was half written (usually after a crash). It is ignored and cut at the next resume. - `session index ... degraded`: `/resume` falls back to scanning the session files. - After a crash or kill in the middle of a turn, run `/continue` in the resumed session to continue the interrupted turn. ## Logs, crash reports and state | What | Where | | --- | --- | | Log | `~/.local/state/mare/log/mare.log`, rotated at 10 MB with 5 old files kept, redacted, mode `0600` | | Crash reports | `~/.local/state/mare/crashes/<time>/report.txt`, written only when a panic ends mare | | Sessions | `~/.local/state/mare/sessions/` | | Runtime choices (model, effort) | `~/.local/state/mare/state.json` | | Trust decisions | `~/.local/state/mare/trust.json` | | Credentials | `~/.config/mare/auth.json` | The default log level is `info`. Raise it for one run with the `MARE_LOG` environment variable, which takes a `tracing` filter: ```sh MARE_LOG=debug mare MARE_LOG=info,mare_binding=trace mare ``` Inside a session, `/debug` shows the most recent log lines and the latest crash report. Directories move with `XDG_STATE_HOME`, `XDG_CONFIG_HOME`, `XDG_DATA_HOME` and `MARE_HOME`. ## Sandbox and permissions `mare doctor` prints the sandbox backend and what it can and cannot enforce. A `!` on `sandbox deny-read` means that restricting reads is not available on this machine, so approved escalations leave the sandbox as approved. Inside a session, `/permission caps` shows the same capability summary, `/permission log` the permission decisions of the session, and `/permission` changes the preset. `--permission full-access` (`--yolo`) removes the sandbox and does not ask, except for dangerous commands, which still ask in every preset (and are denied in a headless run). If a headless run exits with `3`, an approval was answered with "deny and stop" (`abort`) and that stopped the turn. An approval nobody could answer is only denied: the model gets a denial and the run can still exit `0`, with the denied calls listed on stderr. To avoid denials, choose a preset that does not need the approval (`--permission`) or set `--approval-policy never` so requests are rejected without prompting. ================================================================================ Title: Workflows Section: Get started URL: https://signalridge.github.io/mare/en/get-started/workflows/ Markdown: https://signalridge.github.io/mare/raw/en/get-started/workflows.md Source: docs/en/get-started/workflows.md ================================================================================ # Workflows ## Explore a codebase read-only ```sh mare --permission read-only "Give me a map of this repository: the main modules, the entry points and how they connect." ``` `read-only` blocks writes and network access. On the default Windows tier (no network blocking), `mare` asks before each shell or command tool unless `all` / `danger-full-access` was approved or allowed by rule. Follow up with narrower questions and attach files with `@`: ```text Where is the retry policy decided? Compare @src/client.rs with @src/config.rs. ``` To limit what the model can call at all, name the tools. `read` and `bash` are two of the built-in tools (the others include `write` and `edit`): ```sh mare --tools read,bash --permission read-only ``` Run `/init` once in a project to have the agent write an `AGENTS.md` with build commands, architecture notes and conventions. Later sessions read it as context. ## Fix a bug with approvals Describe the symptom and ask for a failing test first: ```sh mare "The CSV export drops the last row when the file has no trailing newline. Reproduce it with a failing test, then fix it." ``` In the default `auto` preset, edits inside the workspace go through and mare asks when a call would leave the sandbox. Answer the approval box with `y` (once), `a` (this session) or `n` (deny, then say why). To approve every write yourself, run `/permission read-only`. See [Permissions](https://signalridge.github.io/mare/en/use/permissions/) for the rules behind each answer. Check what happened before you commit: - `/diff` shows the files changed in each turn, newest first. - `Ctrl+R` opens the change viewer: mare's own edits per turn, or git's unstaged, staged and last-commit diffs. - Type `!git diff --stat` to run a command yourself and put the result in the context. ## Review changes `/review` starts a separate read-only session that reviews code and shows its findings in the transcript. They never enter your conversation's context. ```text /review pick a target from a list /review uncommitted staged, unstaged and untracked changes /review <sha> one commit /review base main the changes against a base branch /review focus on error handling and concurrency ``` Any text that is not a target is taken as custom review instructions. `/review changes [path]` opens the change viewer instead of running a review. ## Run headless in a script or CI `-p` runs one prompt, prints the final answer to stdout and exits: ```sh mare -p "Summarize the changes in @CHANGELOG.md in three bullets" ``` mare also goes headless by itself when stdin or stdout is not a terminal. Piped input is appended to the prompt, or becomes the prompt when you pass `-` or no prompt: ```sh git diff main... | mare -p "Review this diff for bugs" echo "list the TODO comments in src/" | mare -p - ``` A headless run cannot ask you anything. Set the permission level up front, and bound the run: ```sh mare -p --permission read-only --max-turns 20 --timeout 10m "Find unused exported functions" ``` | Exit code | Meaning | | --- | --- | | `0` | Completed | | `1` | Error | | `2` | Bad arguments or configuration | | `3` | An approval was answered with "deny and stop" and the turn was stopped | | `4` | `--max-turns` or `--timeout` reached | | `130` | Interrupted | For machine-readable output use `--json`, which prints one JSON object per line. Each line is `{"type": ..., "data": ...}`, a `session` record comes first and a `settled` record comes last with the final text, usage, `exit_code` and `reason`: ```sh mare --json "Run the tests and report failures" | tail -n 1 | jq '.data | {exit_code, reason}' ``` Add `--stream-deltas` for token-level events. Headless runs never ask about project trust: a saved decision applies, and otherwise a project's `.mare/` files stay unloaded unless you pass `--trust`. MCP servers declared by the project need `--approve-mcps`. In CI, make runs reproducible with `--no-session` (the session is not saved or resumable; runtime files and tool writes still happen) and `--strict-config` (refuse to start on configuration warnings). See [Headless mode](https://signalridge.github.io/mare/en/use/headless/) and [JSON stream](https://signalridge.github.io/mare/en/integrate/json-stream/). To run several prompts in one session from a script, create the session first: ```sh id=$(mare session new --name nightly) mare -p --resume "$id" "Step 1: list failing tests" mare -p --resume "$id" "Step 2: fix the first one" ``` ## Continue and fork sessions ```sh mare -c # continue the most recent session in this directory mare -r # open the session picker mare -r -2 # the second most recent session in this directory mare -r nightly # by name, id or unambiguous id prefix mare -c --fork-session # continue in a copy and leave the original unchanged mare -c --all # most recent session in any directory ``` Inside a session: | Command | What it does | | --- | --- | | `/new` (alias `/clear`) | Start a new session | | `/resume` (alias `/sessions`) | Pick a session; `/resume all` lists every directory, `/resume search <text>` searches | | `/name <title>` (aliases `/rename`, `/title`) | Name the session so `-r <name>` finds it | | `/fork` | Fork into a new session from your latest message; `/fork pick` lets you choose the message | | `/tree` | Navigate the session tree and branch from any earlier point | | `/retry` | Regenerate the last answer; the old one stays on its branch | | `/btw <question>` | Ask a side question; the answer is not added to the conversation | | `/export [path]` | Export the conversation as Markdown | Sessions are JSONL files in `~/.local/state/mare/sessions`. See [Sessions](https://signalridge.github.io/mare/en/use/sessions/). ## Undo and rewind There are two levels of undo, and they do different things. - `/undo` rewinds the conversation to before a prompt. `/undo` alone picks one, `/undo N` takes the Nth-last. The files stay as they are. Pressing Esc twice while the agent is idle opens the same picker. - `/rewind [turn]` puts files back the way they were before a turn. It can also rewind the conversation to that point (as a `/tree` branch, so the old one is kept) or fold the conversation from that turn into a summary. mare saves the original of a file before any tool writes, removes or renames it, whichever tool does it. A file that changed outside mare since is listed and restored only after you confirm. Changes made by shell commands cannot be snapshotted, and the turn says so. ## Background jobs For commands that take a while, the agent starts them in the background and keeps working. You are notified when they finish, with a short piece of the output. - Ask for it: "Start the dev server in the background and check that it answers on port 8080." - Press `Ctrl+B` while a command is running to move it to the background. - `/jobs` lists jobs and opens a job's output or stops it. A line above the input box shows running jobs. ## Steer or queue while the agent works You do not have to wait for a turn to end. | Key | Effect while the agent works | | --- | --- | | Enter | Queue the message; it is sent when the turn finishes | | `Ctrl+S` | Steer: send the input into the running turn | | `Alt+Enter` | Queue it explicitly as a follow-up (`Ctrl+Q` on Windows) | | Esc | Interrupt the turn | | `Ctrl+C` | Interrupt, or clear the input; twice to exit | Press Enter on an empty input while messages are queued to get a menu with three choices: steer now, interrupt and send, or keep them queued. Queued messages are shown above the input; press Up to select one and Enter to edit it in place. ## Work with images - Press `Ctrl+V` in the input to paste an image from the clipboard (`Alt+V` on Windows, where the terminal owns `Ctrl+V`). - Ask the agent to look at an image file: "Look at docs/mockup.png and list the UI elements." The read tool returns PNG, JPEG, GIF and WebP files as images. On a terminal that supports the Kitty, iTerm2 or sixel image protocols, mare draws images inline in the transcript. Elsewhere the transcript shows `[image]`. The `images` plugin controls which images are drawn; see [UI](https://signalridge.github.io/mare/en/configure/ui/). ================================================================================ Title: Checkpoints and code review Section: Use mare URL: https://signalridge.github.io/mare/en/use/checkpoints-and-review/ Markdown: https://signalridge.github.io/mare/raw/en/use/checkpoints-and-review.md Source: docs/en/use/checkpoints-and-review.md ================================================================================ # Checkpoints and code review Before mare's file tools (`write`, `edit`, `apply_patch`) modify, delete, or rename a file, mare records the previous file bytes in a per-session snapshot journal. File changes made by shell subprocesses (`bash`, `powershell`, `shell`) are not snapshotted and cannot be guaranteed to be restored by `/rewind`; mare flags those turns as having potential unrecorded edits. You can inspect per-turn edits with `/diff`, restore snapshotted files with `/rewind` (or rewind prompts with `/undo`), and run an isolated read-only review with `/review`. ## Snapshots, `/diff`, and `/rewind` The `changes` plugin stores snapshots beside the session log at `<session-path>.snapshots/` (or under `<state>/snapshots/run-<pid>-<uuid>/` when running with `--no-session`). Storage is capped by `cap_bytes` (64 MiB by default) and an index limit of 20,000 records (oldest turns are trimmed first); individual files larger than 16 MiB can still be written, but their snapshot is recorded as missing. ### Inspecting changes with `/diff` and `Ctrl+R` - `/diff` opens an overlay listing every turn that modified files through mare tools, newest first, with `+adds / -dels` counts and unified diffs. - `Ctrl+R` (or `/review changes`) opens the multi-scope change viewer: mare's per-turn edits (`turns`), plus git `unstaged`, `staged`, and `committed` (last commit) diffs. Diffs longer than `collapse_lines` (default 400) start collapsed. If a turn ran shell commands (`bash`, `powershell`, or `shell`), mare flags it because shell side effects cannot be snapshotted by the file guard. ### Restoring files with `/rewind` Run `/rewind` (or `/rewind <turn-id>`) to pick a turn. When the session supports conversation rewind and has a recorded history point before that turn, mare offers three actions (otherwise it restores files only): | Option | Effect | |---|---| | Restore files | Puts files modified in that turn and later back to their state before the turn. Conversation history stays unchanged. | | Restore files and the conversation | Restores the files, branches the session tree back to before the turn, and puts that turn's prompt back into your input box. | | Summarize from here | Leaves files on disk untouched and folds the conversation from that turn onward into a summary. | Safety checks during restore: - **External conflict check**: If a file changed outside mare since the turn recorded it, `/rewind` lists the conflicting paths and asks before overwriting them. - **Link refusal**: Restores never write through symlinks or hard links. Any path that became a link is refused and reported. - **Trimmed or oversized backups**: If a backup was trimmed under `cap_bytes` or the 20,000-record index limit, or skipped because the original file exceeded 16 MiB, `/rewind` reports it as missing rather than guessing. Configure snapshot retention in `init.lua`: ```lua mare.plugin("changes", { cap_bytes = 128 * 1024 * 1024, }) ``` ### Conversation-only `/undo` `/undo` (or pressing `Esc` twice on an empty idle input) rewinds only the conversation to before a chosen prompt and places that prompt back in the editor, without modifying files on disk. Undone turns remain on their original branch in the session JSONL file (`/tree`). ## Read-only code review (`/review`) The `review` plugin runs a one-shot read-only subagent session using the `read-only` permission preset and read-only tools (`read`, `ls`, `bash` inside the read-only sandbox). Review findings render directly in the transcript and never enter your main conversation's context window. ```text /review # pick a target interactively /review uncommitted # staged, unstaged, and untracked files /review <sha> # review a single commit (also /review commit <sha>) /review base main # diff against base branch /review focus on race conditions and locks # custom review instructions /review changes [path] # open the diff viewer instead of running an agent review ``` Configure the reviewer in `init.lua`: ```lua mare.plugin("review", { collapse_lines = 400, scopes = { "turns", "unstaged", "staged", "committed" }, prompt_diff_bytes = 120 * 1024, tools = { "read", "ls", "bash" }, }) ``` To mask `Ctrl+R` in the editor, call `mare.keymap.set("editor", "<C-r>", false)`. To use it for history search instead, bind it explicitly to `"history-search"`: `mare.keymap.set("editor", "<C-r>", "history-search")`. ## Related - [Sessions](https://signalridge.github.io/mare/en/use/sessions/) for `/tree`, `/fork`, and session JSONL durability - [Permissions and sandbox](https://signalridge.github.io/mare/en/use/permissions/) for the `read-only` sandbox used by `/review` - [Appearance](https://signalridge.github.io/mare/en/configure/ui/) for diff highlight groups (`MareDiffAdd`, `MareDiffDelete`) ================================================================================ Title: Context and instructions Section: Use mare URL: https://signalridge.github.io/mare/en/use/context/ Markdown: https://signalridge.github.io/mare/raw/en/use/context.md Source: docs/en/use/context.md ================================================================================ # Context and instructions ## What the model sees Each request sends the system prompt, tool definitions, and conversation history. The system prompt combines named sections: identity line, general guidance, tool list, active sandbox and approval policy, instruction files, skills index, and working directory. mare builds the system prompt once per session and model to preserve provider prompt caching, rebuilding only when inputs change. Run `/context` for section token counts, or `/context all` for per-item sizes (instruction files, skills, tool definitions, largest messages). ## Instruction files mare reads these files, in this order: 1. A user file in the config directory: `~/.config/mare/AGENTS.md` (or `AGENTS.override.md`, `CLAUDE.md` there). 2. For the project, every directory from the project root down to the working directory. The project root is the nearest ancestor that contains `.git`; without one, only the working directory counts. In each directory the first existing name wins: `AGENTS.override.md` (a local override you do not commit), then `AGENTS.md`, then `CLAUDE.md`. A symlink to a file already loaded, or a copy of it, counts once. Blank files are ignored. ```text ~/.config/mare/AGENTS.md user instructions, loaded everywhere /repo/AGENTS.md project root /repo/services/api/AGENTS.md loaded when you start in services/api ``` Files are separated in the prompt as `<project_instructions path="...">` blocks, with the user file first and then root to working directory. The total is capped at 32 KiB (`project_doc_max_bytes`). When the cap is reached the files farthest from the working directory are dropped first, the file that crosses the cap is cut with a `[truncated]` note, and a note names any omitted files. When the model reads a file below the working directory, the `AGENTS.md` of each directory between the working directory and that file is appended to the read result once, within the same size budget. A monorepo can therefore keep rules next to the code they cover. An `AGENTS.md` from a project you have not trusted is still loaded, because it only instructs the model, but it is labelled as coming from an untrusted project. Project instruction files that resolve outside the project root, or follow symlinks inside an untrusted workspace, are skipped instead of loaded. See [Permissions](https://signalridge.github.io/mare/en/use/permissions/). Options of the `context` plugin: ```lua mare.plugin("context", { files = { "AGENTS.override.md", "AGENTS.md", "CLAUDE.md", "GEMINI.md" }, -- names, in priority order project_root_markers = { ".git" }, -- {} = only the working directory project_doc_max_bytes = 64 * 1024, }) ``` ### Creating and editing them - `/init` asks the model to analyze the repository and create or improve `AGENTS.md` at the root: build and test commands, architecture, and conventions actually used. - `/memory` lists the instruction files in effect, with sizes; Enter shows one. `/memory add <text>` appends a bullet to the project's `AGENTS.md`, `/memory add --user <text>` to the user file, creating it when needed. - You can edit the files in any editor. Before each prompt mare compares the modification time and size of the instruction files, `SYSTEM.md`, `APPEND_SYSTEM.md` and every `SKILL.md`, and rebuilds the system prompt if anything changed. `/memory add` tells you its note applies from the next session; `/new` starts one. ## System prompt files | File | Effect | | --- | --- | | `SYSTEM.md` | Replaces the whole default system prompt. | | `APPEND_SYSTEM.md` | Adds text at the end of the default prompt. | mare looks in `.mare/` of the project resource root (the nearest directory up to the git root containing `.mare/` or `.mcp.json`; only if the project is trusted), then in `~/.config/mare/`. Replacing the prompt removes every default section, including the sandbox and tool descriptions, so the model no longer sees them. mare says so at startup and in `mare doctor`; use `APPEND_SYSTEM.md` unless you mean it. The same can be set in `init.lua` or on the command line: ```lua mare.plugin("context", { append = "Always answer in French.", -- like APPEND_SYSTEM.md persona = "You are a careful Rust reviewer.", -- replaces only the identity line -- system = "...", -- like SYSTEM.md: replaces everything }) ``` ```sh mare --append-system-prompt "Prefer small commits." "tidy up the tests" ``` Add or remove individual sections with `mare.prompt.section { name = ..., order = ..., text = ... }` and `mare.prompt.remove(name)`. ## Skills A skill is a directory with a `SKILL.md` file: YAML frontmatter with a `name` and a `description`, then instructions. mare follows the Agent Skills layout, so skills written for other agents work unchanged. ```text ~/.config/mare/skills/release-notes/SKILL.md ``` ```markdown --- name: release-notes description: Draft release notes from the commits since the last tag. Use when asked to prepare a release. --- 1. Run `git describe --tags --abbrev=0` to find the last tag. 2. List the commits since then and group them by area. 3. Write the notes in `RELEASE_NOTES.md`. ``` Skills are discovered in these directories; when two skills share a name the first found wins: | Directory | Scope | | --- | --- | | `~/.config/mare/skills` | User. | | `~/.agents/skills` | User, shared with other agents. | | `.mare/skills` | Project, in the project resource root (nearest `.mare/` or `.mcp.json`, up to the git root). Trusted projects only. | | `.agents/skills` | Project, resolved against the same project resource root (`mare.project.root`). Trusted projects only. | | `skills/` in installed [packages](https://signalridge.github.io/mare/en/configure/packages/) | Package. | Change the list with the `skill_dirs` option. Relative entries count as project directories and need trust. Only the name, description and location of each skill go into the system prompt. When a task matches a description, the model reads the full `SKILL.md` with the `read` tool. This keeps the prompt small however many skills you install. A skill whose frontmatter sets `disable-model-invocation: true` is left out of the list and used only when you ask for it. To load a skill yourself, run `/skill:<name>` with optional text after it: ```text /skill:release-notes for v2.4 ``` The skill's instructions are sent as a message, followed by your text. `/skills` opens a browsable list of skills and shows any warnings from the scan. A skill without a `description` is skipped; other problems (a name that is not lowercase letters, digits and hyphens, a description over 1,024 characters) are warnings and the skill still loads. `mare doctor` reports them too. `allowed-tools` is read but not enforced. ## Prompt templates A Markdown file in `~/.config/mare/prompts/` or `.mare/prompts/` (project ones need a trusted project) becomes a slash command named after the file. Packages can ship templates in their `prompts/` directory. A template never replaces an existing command. ```markdown --- description: Review the staged changes argument-hint: "[focus]" --- Review the output of `git diff --staged`. Focus on: ${@:-correctness and tests}. ``` Saved as `~/.config/mare/prompts/review-staged.md`, this runs as `/review-staged security`. (A name that is already a command, such as the built-in `/review`, is skipped.) Arguments: `$1`, `$2` and so on, `$@` or `$ARGUMENTS` for all of them, `${1:-default}` and `${@:-default}` for defaults, and `${@:N}` or `${@:N:L}` for a slice. Quoted words stay together. Set `prompt_dirs` to change where templates are read from. ## File mentions `@path` in your message attaches the file's contents to that message, `@"path with spaces"` quotes a path, and a directory attaches its listing. Limits are 100 KiB per file and 256 KiB per message. See [Interactive interface](https://signalridge.github.io/mare/en/use/tui/). On the command line, a separate argument that starts with `@` attaches a text file to the first prompt: `mare "review" @src/lib.rs`. The command line reads the whole file with none of those limits, and an image or an unreadable path stays as written. ## How compaction treats context When the conversation approaches the context window, mare compacts conversation messages while keeping the original history in the session file. The system prompt, tool definitions, skill headers, and instruction files are not part of the conversation: they are sent again with every request, are never summarized, and keep counting against the window. A very large `AGENTS.md` therefore costs tokens on every request. Anything the model must keep across a compaction belongs in `AGENTS.md`, not only in the conversation. Use `/compact <focus>` to tell a manual summary what to preserve. For the four compaction stages, retention budgets, thresholds, and options, see [Usage and compaction](https://signalridge.github.io/mare/en/use/usage-and-compaction/). ================================================================================ Title: Headless mode Section: Use mare URL: https://signalridge.github.io/mare/en/use/headless/ Markdown: https://signalridge.github.io/mare/raw/en/use/headless.md Source: docs/en/use/headless.md ================================================================================ # Headless mode Run mare without the interactive UI, for scripts and CI: print the final answer, or stream machine-readable events, then exit with a status code. ```sh mare -p "list the public functions in src/lib.rs" ``` `-p` (`--print`) runs the prompt and prints the final answer to stdout. mare also switches to this mode by itself when stdin or stdout is not a terminal. Nothing is asked of you while it runs: approvals that would need an answer are denied (see below). ## Giving the prompt ```sh mare -p "explain this error" # prompt as arguments git diff | mare -p "review this diff" # piped stdin is appended as <stdin>...</stdin> cat prompt.md | mare -p # no prompt argument: stdin is the prompt mare -p - < prompt.md # "-" reads the prompt from stdin explicitly mare -p explain @src/main.rs # a separate @path argument attaches that text file ``` - With a prompt argument and piped stdin, the stdin text is added after the prompt inside `<stdin>` tags. If nothing arrives on stdin within one second, mare ignores it so an inherited pipe cannot hang the run. - Stdin must be UTF-8 and at most 64 MiB. Empty stdin with no prompt is a usage error (exit code 2). - An `@path` argument is a whole shell word that starts with `@`. A text file is attached inline; images and unreadable paths stay as written. Continue earlier work with the session options from [Sessions](https://signalridge.github.io/mare/en/use/sessions/): ```sh mare -p -c "now add tests" # continue the last session here mare -p --resume 3f9a1c2e "and update the docs" # by id; see `mare session new` mare -p --no-session "one-off question" # do not save this session ``` ## Machine-readable output ```sh mare -p --json "fix the failing test" > run.jsonl mare -p --json --stream-deltas "write a haiku" ``` `--json` (shorthand for `--mode json`) prints one JSON object per line. The first line is a `session` record, then the public agent events (turn starts, messages, tool calls, usage), `turn.failed` if the run failed, and `settled` last. Without `--stream-deltas` the stream is item level; with it, text and tool-output deltas are included too. The record formats are in [JSON stream](https://signalridge.github.io/mare/en/integrate/json-stream/). ```sh mare -p --json "summarize CHANGELOG.md" | jq -r 'select(.type == "settled") | .data.text' mare -p --json "..." | jq -r 'select(.type == "settled") | "\(.data.reason) \(.data.exit_code)"' ``` If the reader of stdout goes away (`... | head`), mare stops the run instead of spending tokens for nobody and exits with 141. For a long-lived two-way connection use `--rpc` instead; see [RPC](https://signalridge.github.io/mare/en/integrate/rpc/). ### Structured output (`--output-schema`) Pass `--output-schema FILE` in headless mode (`-p` or `--json`) to constrain the final answer to a JSON Schema and validate it before exiting. Minimal schema (`summary.schema.json`): ```json { "type": "object", "required": ["risk", "findings"], "additionalProperties": false, "properties": { "risk": { "type": "string", "enum": ["low", "medium", "high"] }, "findings": { "type": "array", "items": { "type": "string" } } } } ``` Run and read the validated JSON object: ```sh # JSON stream: save the stream first so mare's exit code is not masked by jq, then extract `.data.structured` mare -p --json --no-session --output-schema summary.schema.json \ "Inspect src/auth.rs and summarize risk." > run.jsonl || exit $? jq -ce 'select(.type == "settled") | .data.structured' run.jsonl > summary.json # Print mode: stdout receives the validated JSON text directly mare -p --no-session --output-schema summary.schema.json \ "Inspect src/auth.rs and summarize risk." > summary.json ``` Validation and error semantics: - `--output-schema` is accepted only in headless runs (`-p` / `--json`). Using it outside headless mode, or passing a missing file, invalid JSON, or an unsupported/invalid schema exits with code `2` before starting a turn. - If the model's final text does not satisfy the schema, mare fails the run (`error_kind = "invalid_output"`) and exits with code `1`. In `-p` mode stdout stays empty and the validation error is printed to stderr; in `--json` mode mare emits `turn.failed` and `settled` with `error` populated and `structured` omitted. ## Limits and tools | Option | Effect | | --- | --- | | `--max-turns N` | Stop after `N` model turns in one prompt. Exit code 4. | | `--timeout DURATION` | Stop the run after this long. Accepts `90`, `90s`, `1500ms`, `5m`, `1h`. Exit code 4. Headless only. | | `--output-schema FILE` | Validate the final response against a JSON Schema file (`structured` field in `--json`). Headless only. | | `--tools a,b` | Offer the model only these tools, for example `--tools read,ls`. | | `--exclude-tools TOOLS` | Exclude matching tools (repeatable or comma-separated; supports `*` globs), for example `--exclude-tools bash,write`. Excluded tools are hidden from requests and refused at execution. | | `--add-dir DIR` | Add an existing physical directory to the session workspace (repeatable; absolute paths without symlinks, outside protected paths; not accepted by `mare acp`). | | `--append-system-prompt TEXT` | Add text to the end of the system prompt for this run. | | `-m`, `-e` | Model and reasoning effort; see [Models](https://signalridge.github.io/mare/en/use/models/). | | `--permission`, `--yolo`, `--approval-policy` | Permission preset and approval policy; see below. | | `--no-session` | Do not persist the run. | | `--set KEY=VALUE` | Override one option, for example `--set plugins.tools.edit_mode=replace`. | | `--strict-config` | Refuse to start if the configuration has warnings. | | `--clean` | Ignore user and project config, user plugins, packages and `state.json`. | ```sh mare -p --tools read,ls --max-turns 8 --timeout 5m \ --append-system-prompt "Answer in one paragraph." \ "what does this repository do?" ``` ## Permissions and approvals Ordinary main sessions default to `auto` in trusted projects and use `untrusted_preset` (default `read-only`) in untrusted projects; an explicit `--permission` flag takes precedence. In headless runs, approvals with no responder are denied and the tool returns the denial to the model so it can continue with other work: - mare prints `mare: N approval(s) were needed and nobody could answer (denied)` to stderr, followed by one line per denied call. - The exit code stays 0 if the run otherwise completes. Exit code 3 means the run stopped because of an approval that was answered with "deny and stop". Choose the preset that matches the job: ```sh mare -p --permission read-only "audit this repo for hard-coded secrets" # no writes at all mare -p "fix the typo in README.md" # trusted project: auto writes in the workspace mare -p --yolo "run the full migration" # full-access: no sandbox; still asks for prompt rules and dangerous commands mare -p --approval-policy never "..." # reject anything that would ask ``` Explicit `prompt` rules and dangerous commands such as `rm -f` ask in every preset, including `--yolo`, and are therefore denied in a headless run unless a rule allows that exact command. An unanalyzable command is not automatically denied by parse failure alone: in `full-access` with no restrictive rule (`prompt` or `forbidden`) applying in that directory, it can still be allowed; it falls back to `ask` (and thus denial in headless runs) only when an applicable restrictive rule might match it. See [Permissions](https://signalridge.github.io/mare/en/use/permissions/). Project resources (`.mare/plugins`, `.mare/init.lua`, skills, prompts, `.mare/SYSTEM.md`) load only in trusted projects, and headless runs never ask. If the project is not trusted, mare prints a note on stderr and carries on without them. Pass `--trust` to trust the project for this run, or run `mare trust` once. Project MCP servers need `--approve-mcps`; see [MCP](https://signalridge.github.io/mare/en/use/mcp/). Run `--yolo` only in a throwaway container or VM. ## Exit codes | Code | Meaning | | --- | --- | | 0 | Completed. | | 1 | The run failed (provider error, no usable model, session not found, and so on). | | 2 | Bad arguments or configuration; the run never started. | | 3 | The run stopped because an approval was answered with "deny and stop" (`abort`). An approval nobody could answer is only denied and does not set this code. | | 4 | `--max-turns` or `--timeout` was reached. | | 5 | Session persistence failed (final answer still printed, unsaved records quarantined under `<state>/quarantine/`). | | 130 | Interrupted (SIGINT). | | 141 | stdout was closed by the reader. | With `--json`, the `settled` record carries the same code as `exit_code` and a `reason` (`completed`, `error`, `usage`, `approval_unavailable`, `max_turns`, `timeout`, `save_failed`, `interrupted`). The full list is in [Exit codes](https://signalridge.github.io/mare/en/reference/exit-codes/). ## CI examples A shell step that fails the job when the run fails, and keeps the stream as an artifact: ```sh export ANTHROPIC_API_KEY="$SECRET" mare -p --json --no-session --permission read-only --timeout 10m \ -m anthropic/claude-sonnet-5-5 \ "Review the changes in this pull request and list concrete bugs." > review.jsonl code=$? jq -r 'select(.type == "settled") | .data.text' review.jsonl > review.md exit $code ``` A GitHub Actions step that lets the agent edit files in a disposable runner: ```yaml - name: Fix lint errors env: OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} run: | mare -p --max-turns 20 --timeout 15m \ "Run the linter, fix every error it reports, and re-run it until it passes." git diff --stat ``` Checking the result and handling the exit code: ```sh mare -p --json "..." > out.jsonl case $? in 0) echo "ok" ;; 3) echo "needs a permission the CI preset does not grant" ;; 4) echo "hit --max-turns or --timeout" ;; *) echo "failed" ;; esac ``` Authenticate with an API key environment variable (see [Models](https://signalridge.github.io/mare/en/use/models/)); `mare login` stores credentials on disk and is better kept for your own machine. ================================================================================ Title: MCP servers Section: Use mare URL: https://signalridge.github.io/mare/en/use/mcp/ Markdown: https://signalridge.github.io/mare/raw/en/use/mcp.md Source: docs/en/use/mcp.md ================================================================================ # MCP servers Connect Model Context Protocol servers to mare: where to configure them, how tools reach the model, how project servers are approved and OAuth login. The `mcp` plugin is built in and on by default. It does nothing until you configure a server. It supports stdio servers (a command mare starts) and streamable HTTP servers (a URL). The legacy SSE transport is not supported; use the server's streamable HTTP endpoint, commonly `/mcp` instead of `/sse`. ## Configuring servers Servers can come from five places. Later sources override earlier ones for a server of the same name. | Order | Source | Notes | | --- | --- | --- | | 1 | `servers` in `mare.plugin("mcp", { ... })` in `init.lua` | | | 2 | `~/.config/mare/mcp.json` | User file. | | 3 | The file named by `$MARE_MCP_CONFIG` | Needs approval (below). | | 4 | `.mcp.json` in the project resource root | Project file (nearest `.mare/` or `.mcp.json`, up to the git root; may be in an ancestor of the working directory); needs approval. | | 5 | `.mare/mcp.json` in the project resource root | Project file in the same project resource root; needs approval. | JSON files use the common layout, `{ "mcpServers": { ... } }` (`mcp_servers` and `servers` are also read), and accept the camelCase spellings used by other clients (`enabledTools`, `bearerTokenEnvVar`, `startupTimeoutMs` and so on). ```json { "mcpServers": { "github": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-github"], "env": { "GITHUB_TOKEN": "${GITHUB_TOKEN}" } }, "docs": { "url": "https://example.com/mcp", "headers": { "x-team": "platform" } } } } ``` The same in `init.lua`: ```lua mare.plugin("mcp", { servers = { github = { command = "npx", args = { "-y", "@modelcontextprotocol/server-github" }, env = { GITHUB_TOKEN = "${GITHUB_TOKEN}" }, tier = "direct", }, linear = { url = "https://mcp.linear.app/mcp", oauth = true, tools = { delete_issue = "hidden" }, }, }, }) ``` Server names may contain letters, digits, `_` and `-`. Strings expand `${VAR}`, `${env:VAR}` and `${VAR:-default}`; a variable that is not set is reported by `/mcp` and `mare doctor`. A project entry that has no `command`, `url` or `type` is an override of the user's server with the same name: it can change only `enabled`, `tier`, `tools`, `enabled_tools`, `disabled_tools`, `description` and `required`. ### Server keys | Key | Meaning | | --- | --- | | `command`, `args`, `env`, `env_file`, `cwd`, `env_include`, `env_exclude` | A stdio server. `env_file` is a dotenv file; `env` overrides it. | | `url`, `headers`, `env_http_headers`, `bearer_token`, `bearer_token_env_var` | A streamable HTTP server. `env_http_headers` maps a header name to an environment variable. | | `oauth` | `true`, or a table with `scopes`, `client_id`, `client_secret`, `client_name`, `callback_port`, `auth_server_metadata_url`. | | `tls` | `{ ca_bundle = "..." }` for a private certificate authority. | | `enabled` | `false` turns the server off. | | `required` | `true`: a request waits for this server to connect, with no time limit; a failure denies the request with the reason. | | `tier` | Exposure level; see below. | | `tools` | Per-tool tier, for example `{ delete_issue = "hidden", ["search_*"] = "direct" }`. | | `enabled_tools`, `disabled_tools` | Allow or deny lists, with `*` patterns. | | `description` | Shown to the model to help it find the server's tools. | | `startup_timeout_ms`, `call_timeout_ms` | Defaults 60,000 (at most 300,000) and 120,000. Progress notifications reset the call timeout. | MCP plugin options are `tier` (default `deferred`), `startup_timeout_ms`, `call_timeout_ms` and `text_limit`. Set `plugins.tools.search_results` to change the default number of `tool_search` results (5). Results longer than `text_limit` (20 KiB) are cut in the middle, and the full text is saved to a private file named in the result. ## Approving project servers A server from `$MARE_MCP_CONFIG`, `.mcp.json` or `.mare/mcp.json` does not start until you approve it, because opening a repository must not run its commands. The approval is remembered by server name plus a hash in `~/.local/state/mare/mcp-approvals.json`. The hash covers the server's execution, auth, transport, and exposure fields: `command`, `args`, `env`, `env_file`, `env_include`, `env_exclude`, `cwd`, `url`, `headers`, `env_http_headers`, `bearer_token`, `bearer_token_env_var`, `oauth`, `tls`, `type`, `tier`, `tools`, `enabled_tools`, `disabled_tools`, `enabled`, `required`, `description`, and any partial project overlays. Changing any of these fields invalidates the hash and asks for approval again. Stdio servers from a project also require the project to be [trusted](https://signalridge.github.io/mare/en/use/permissions/). - Interactive: `/mcp enable <server>`, or choose the server in `/mcp` and pick Enable. - Headless: pass `--approve-mcps` to approve all of them. This writes the same remembered approvals to `mcp-approvals.json`, so later runs, headless or interactive, start those servers without asking again until the hash changes: ```sh mare -p --trust --approve-mcps "list my open issues" ``` Without it, an unapproved server shows as `needs_approval` and its tools are not available. ## How tools reach the model Each tool is registered as `mcp__<server>__<tool>`. A short hash is appended if the name is longer than 64 characters or collides with another tool. How many tools the model sees up front depends on the server's tier, which keeps the prompt small when you have many servers. | Tier | Behavior | | --- | --- | | `deferred` (default) | The server is not connected at startup. The model discovers tools and their schemas with `tool_search`. On the first search, an uncached server connects to discover its tools; a cached list under `~/.local/state/mare/mcp-tools` avoids a connection until first use. Models with `tool_update = "addition_only"` (Anthropic Claude, OpenAI Responses `gpt-5.4` and newer, and Kimi K3) activate deferred tools mid-conversation and invoke them directly; all other models invoke discovered tools through the fixed `call_tool` proxy so the top-level `tools` array and prompt prefix cache stay byte-stable across turns. | | `direct` | Connected in the background at startup, and tools are declared like built-in ones. A request never waits for it (unless `required`): tools that are still connecting join from the next turn. | | `hidden` | Not available. | | `codemode` | Callable only from a code-mode script. Needs a codemode plugin; otherwise treated as `deferred`. | `tool_search` takes keywords (`github issues`) or exact names (`select:mcp__github__create_issue`, up to 32 tools per query), and returns matching tool schemas within a fixed result budget. The system prompt gets one line per server. > **Prompt caching across all providers:** Deferred tool discovery keeps the system prompt and top-level `tools` array fixed across turns on every provider. Models with `tool_update = "addition_only"` (Anthropic Claude, OpenAI Responses `gpt-5.4`+, Kimi K3) activate deferred tools natively; other endpoints (such as DeepSeek, GLM, Google Gemini, older OpenAI models, and Kimi K2) use the fixed `call_tool` proxy instead of mutating `tools[]`, preserving the prompt prefix cache. Set `tier = "direct"` (or mark individual tools `direct` in `tools`) if you prefer a small toolset to be declared directly up front. If a server offers resources, the model also gets tools to list and read them, and server prompts appear as slash commands named `/mcp__<server>__<prompt>` (pass `name=value` arguments or positional words). Server elicitation requests show as a form in the TUI; headless runs always decline them. ### Approvals for MCP tools MCP tools run in the server's process, outside mare's OS sandbox. In the `auto` preset every MCP tool call therefore asks first, including read-only ones. To skip the question for a tool you trust, add a rule: ```lua mare.plugin("permissions", { rules = { { tool = "mcp__github__list_issues", decision = "allow" } }, }) ``` Or choose "Allow and remember" in the dialog. See [Permissions](https://signalridge.github.io/mare/en/use/permissions/). ## Managing servers ```sh mare mcp list # connect to every enabled server; print state, tools and errors (exit 1 on required server problems) mare mcp list-tools github # a server's tools with their input schemas mare mcp disable github # turn a server off in this project mare mcp enable github mare mcp login linear # OAuth login in the browser ``` `enable` and `disable` are remembered per project in `~/.local/state/mare/mcp-disabled.json`; they never edit your config files. Inside a session, `/mcp` opens a panel of servers with their state (`connected`, `needs_login`, `needs_approval`, `disabled`, and others) and the actions that fit each one: show tools and schemas, reconnect, log in or out, enable or disable. The same actions work as subcommands: `/mcp login <server>`, `/mcp logout <server>`, `/mcp reconnect <server>`, `/mcp enable <server>`, `/mcp disable <server>` and `/mcp tools <server>`. `mare doctor` also checks MCP servers. ## OAuth Set `oauth = true` (or a table of options) on an HTTP server, then log in once: ```sh mare mcp login linear ``` mare opens a browser, completes the OAuth flow, stores the tokens, and reconnects the server with them. A server that needs a login shows `needs_login` until you do. `/mcp logout <server>` forgets the stored tokens. `login` applies only to HTTP servers configured with `oauth`. mare finds the authorization server from the server's protected resource metadata, or from authorization server metadata at the server's origin. It refuses a login when that metadata is on another origin, when the server publishes none (set `auth_server_metadata_url` then), when the authorization server does not advertise PKCE `S256`, or when an authorization, token, registration or revocation endpoint is plain `http` on a host other than loopback. For a server that takes a static token instead, use `bearer_token_env_var` so the token stays out of the file: ```json { "mcpServers": { "internal": { "url": "https://mcp.example.com/mcp", "bearer_token_env_var": "INTERNAL_MCP_TOKEN" } } } ``` ================================================================================ Title: Models and providers Section: Use mare URL: https://signalridge.github.io/mare/en/use/models/ Markdown: https://signalridge.github.io/mare/raw/en/use/models.md Source: docs/en/use/models.md ================================================================================ # Models and providers How to sign in to a provider, pick a model and a reasoning effort, override model metadata, and add an OpenAI-compatible endpoint. A model is named `provider/id`, for example `openai/gpt-6.1-terra`. The providers are built-in plugins; each registers its models, and some also fetch a live model list once you are signed in. ## Providers | Provider | Plugin | Authentication | Environment variable | | --- | --- | --- | --- | | `openai` | `provider-openai` | ChatGPT subscription (browser or device code), or an API key | `OPENAI_API_KEY` | | `anthropic` | `provider-anthropic` | API key | `ANTHROPIC_API_KEY` | | `google` | `provider-google` | Gemini API key | `GEMINI_API_KEY`, `GOOGLE_API_KEY` | | `opencode-go` | `provider-opencode-go` | opencode Go API key | `OPENCODE_API_KEY` | | `deepseek` | `provider-openai-compat` | API key | `DEEPSEEK_API_KEY` | | `kimi` | `provider-openai-compat` | Moonshot API key | `MOONSHOT_API_KEY` | | `kimi-code` | `provider-openai-compat` | Kimi Code API key | `KIMI_API_KEY` | | `openrouter` | `provider-openai-compat` | API key | `OPENROUTER_API_KEY` | | `ollama` | `provider-openai-compat` | none (`http://localhost:11434/v1`) | | | `lmstudio` | `provider-openai-compat` | none (`http://localhost:1234/v1`) | | `provider-faux` is a scripted provider for tests and offline demos; it is not meant for real work. mare looks for a key in this order: the `api_key` set with `mare.provider` in `init.lua`, then the credential stored by `mare login` (`~/.config/mare/auth.json`, mode 0600), then the provider's environment variables. ## Signing in ```sh mare login # configured model's provider; picker on TTY (exits 2 without TTY) mare login openai # ChatGPT subscription (openai) explicitly mare login openai --oauth # force browser OAuth explicitly mare login openai --device-auth # ChatGPT with a device code, for SSH or no browser printenv ANTHROPIC_API_KEY | mare login anthropic --with-api-key printenv OPENAI_API_KEY | mare login openai --with-api-key mare login status # every provider and whether it has credentials mare logout openai # remove local stored credentials (best-effort OAuth revocation for openai-codex only) ``` - Bare `mare login` tries the configured model's provider first. With no usable default, it opens a provider picker on a TTY and exits `2` without one (pass `mare login openai` explicitly for ChatGPT). - `--with-api-key` reads from stdin only and refuses to run when stdin is a TTY, keeping keys out of shell history. - Inside a session, `/login [provider]` passes the provider name to `llm` and refreshes that provider's model catalog in the background on success. - Over `--rpc`, interactive login requires a connected UI; pass an API key explicitly via the `key` parameter of `llm.login`. - Without a display (SSH, or Linux without `DISPLAY` / `WAYLAND_DISPLAY`), ChatGPT login offers device-code flow first. ### Provider login contract and `auth_keys` Custom provider plugins registered with `ctx.llm:register_provider` participate in `/login`, `mare login`, `mare login status`, and `mare logout` by declaring: - `login = { methods = { "oauth", "device", "api_key" }, run = function(io) ... end }`: advertises the supported login methods so mare validates `--oauth` / `--device-auth` / `--with-api-key` before calling `run(io)` (where `io` provides `say`, `ask`, `choose`, `method`, and optional `key`). When a caller omits `method` (such as `/login <provider>`), `run(io)` receives `io.method == nil`; passing `method = "auto"` resolves a concrete method before invoking `run(io)`. - `auth_keys = { ... }`: lists every key in `auth.json` owned by the provider (defaulting to `{ provider }`). For example, `openai` declares `auth_keys = { "openai-codex", "openai" }`, so `mare logout openai` removes both local entries from `auth.json`. Its server-side revocation runs best-effort only for the `openai-codex` OAuth token; a separately pasted OpenAI API key is removed locally and is not revoked at OpenAI. Lua plugins can inspect stored credential key names without reading secret values or running key commands via `ctx.llm:auth_keys(prefix?)` (returns sorted key names from `auth.json`, optionally filtered by literal prefix) or `ctx.llm:list_auth_keys(prefix?)` (returns `{ data = string[] }`). Over RPC, `llm.list_auth_keys` (`{ prefix? } -> { data: string[] }`), `llm.login`, and `llm.logout` are primary admin methods (restricted to owner/admin connections; `llm.list_auth_keys` returns key names only and never exposes secret values), while `llm.list_providers` can also be granted to peer clients. For non-interactive use, set the environment variable instead; nothing is written to disk: ```sh export ANTHROPIC_API_KEY=... mare -p -m anthropic/claude-sonnet-5-5 "summarize the diff" ``` To read a key from a password manager, give `api_key` a command. The command runs on demand, and its output is cached until the helper reports `expires_at` or a request returns 401: ```lua mare.provider("anthropic", { api_key = { cmd = { "pass", "show", "anthropic/api-key" } } }) ``` ## Choosing a model ```sh mare -m openai/gpt-6.1-terra # this run mare -m sonnet # an alias ``` In a session, `/model` opens the picker. Providers without credentials are grouped at the end as needing login. `/model <provider/id>` or `/model <alias>` switches directly, and `/model <text>` opens the picker filtered by that text. Opening the picker refreshes model lists older than ten minutes in the background. `Alt+P` opens the picker without losing your draft; `Alt+M` cycles through your favorite models, or the recently used ones if you have no favorites. To set a default, use `init.lua`: ```lua mare.setup { model = "openai/gpt-6.1-terra", favorite_models = { "openai/gpt-6.1-terra", "anthropic/claude-sonnet-5-5" }, fallback_models = { "google/gemini-2.5-pro" }, -- tried when the current model is overloaded or out of quota } ``` You can also set `MARE_MODEL`. An explicit `model` in `init.lua` (or the flag or variable) wins over the model you last picked with `/model`, which mare remembers in `state.json` (see below). The built-in aliases `sonnet`, `opus` and `haiku` select the newest Anthropic model of that family. Define your own with `mare.model`: ```lua mare.model { provider = "openai", id = "gpt-6.1-terra", alias = "main" } ``` After that `-m main`, `/model main` and `fallback_models` accept `main`. ## Reasoning effort Effort controls how much the model reasons before it answers. The levels are `off`, `minimal`, `low`, `medium`, `high`, `xhigh` and `max`; each model offers only some of them. ```sh mare -e high "refactor this module" ``` In a session, `/effort` lists the levels the current model supports. `/effort high` sets one for this model and remembers it. `/effort high --session` changes only the current session. `Alt+,` lowers and `Alt+.` raises the level. If you ask for a level the model does not support, mare uses the nearest supported one and says so; it never clamps silently. `/show-reasoning` toggles showing full reasoning text instead of a one-line summary. A model without an effort parameter reports that and lists the parameters it does have. ## Refreshing the model list Providers that can list their models cache the list in `~/.local/state/mare/models-cache/<provider>.json` and refresh it in the background after startup when it is older than a day. Metadata such as price, input types and limits is merged in from models.dev. To refresh now: ```sh mare model refresh ``` This fetches the model lists of every provider that has credentials, plus the models.dev metadata. Set the `llm` plugin option `models_dev = false` to stop using models.dev: ```lua mare.plugin("llm", { models_dev = false, catalog_refresh_ms = 7 * 24 * 3600 * 1000 }) ``` ## Per-model overrides `models` in `mare.setup` overrides fields of a model, or defines one the provider does not list. The key is the `provider/id` ref. ```lua mare.setup { models = { ["openai/gpt-6.1-terra"] = { context_window = 921000, max_output = 64000 }, ["openrouter/qwen/qwen3-coder"] = { name = "Qwen3 Coder", context_window = 262144, reasoning = true }, }, } ``` Common fields are `name`, `context_window`, `max_output`, `reasoning`, `efforts`, `input` (a list such as `{ "text", "image" }`) and `cost` (`input`, `output`, `cache_read`, per million tokens). A model that is not otherwise known gets a 128,000-token context window and 16,384 maximum output until you set them. The context window matters: [automatic compaction](https://signalridge.github.io/mare/en/use/sessions/) triggers from it. ## Adding an OpenAI-compatible provider Any server that speaks the Chat Completions API can be added with `mare.provider`. A name that is not a built-in provider, plus a `base_url`, defines a new provider. Two accounts of one service are two names. ```lua mare.provider("lab", { base_url = "http://10.0.0.5:8080/v1", api_key = "LAB_API_KEY", -- an environment variable name, a { cmd = {...} } helper, or a literal default_model = "qwen3", default_context = 131072, models = { { model_id = "qwen3", context_window = 131072, max_output = 8192, reasoning = true, efforts = { "low", "medium", "high" } }, }, }) ``` ```sh mare -m lab/qwen3 ``` Useful fields: `no_key = true` for a server without authentication, `list_models` to read the server's model list, `dialect` (`"deepseek"`, `"openrouter"`, `"kimi"`, `"cerebras"`, `"zai"`, `"together"`, `"qwen"`, …) to select protocol quirks without tying behaviour to the provider name, `effort_param` (`"reasoning_effort"` or `"openrouter"`), `reasoning_format`, `needs_reasoning_placeholder`, `key_prefixes`, `models_dev` (a models.dev provider id, or `false` to disable enrichment), `headers`, `query_params`, `retries`, `stream_idle_timeout_ms`, `connect_timeout_ms`, `drop_fields`, `transport` and `proxy`. Narrower fields (`reasoning_format`, `effort_param`, `cache_control_format`, `needs_reasoning_placeholder`) take precedence over `dialect`, which in turn takes precedence over host and model-id detection. `wire_api = "responses"` (or `wire = "openai-responses"`) moves a data-entry provider to the OpenAI Responses wire. ### Overlays and regional endpoints Calling `mare.provider` with an existing built-in name overlays that preset field by field (`models`, when given, replaces the preset's seed list; changing `wire` or `wire_api` moves a data entry to the new wire, while code-backed providers ignore `wire`/`wire_api` and report a `mare doctor` warning). Built-in presets default to international endpoints; override `base_url` to point a preset at a regional or mainland endpoint or an internal gateway while keeping its dialect and credential variable: ```lua mare.provider("kimi", { base_url = "https://api.moonshot.cn/v1" }) mare.provider("anthropic", { base_url = "https://gateway.example.com", headers = { ["x-team"] = "infra" } }) ``` ### Custom endpoints and provider plugins Services compatible with an existing wire can be configured directly with `mare.provider`. When a service requires custom authentication, signing, or request framing, write a provider plugin. ## Runtime choices in `state.json` When you pick a model or an effort inside a session, mare saves it to `~/.local/state/mare/state.json` instead of editing `init.lua`. The file holds `model`, `recent_models` and `model_params` (the effort remembered for each model), plus other choices such as the status line segments. The next run starts from them, unless `init.lua`, an environment variable or a flag sets the same thing. Delete the key, or run with `--clean`, to ignore it. `/config` shows each option's value and where it came from. ================================================================================ Title: Permissions and sandbox Section: Use mare URL: https://signalridge.github.io/mare/en/use/permissions/ Markdown: https://signalridge.github.io/mare/raw/en/use/permissions.md Source: docs/en/use/permissions.md ================================================================================ # Permissions and sandbox How mare decides what the agent may do: permission presets, approvals, rules, project trust and the operating-system sandbox, including what is not protected. Two mechanisms work together. The sandbox is enforced by the operating system and limits what a spawned process can write, read and reach over the network. Approvals decide when mare asks you before a tool call that goes beyond the sandbox. Both are provided by the built-in `permissions` plugin; if you disable that plugin, mare runs with full access. ## Presets A preset sets the sandbox level and the approval behaviour together. Choose one per session. | Preset | Status bar | Sandbox | Asks | | --- | --- | --- | --- | | `read-only` | `READ` | Read everywhere. No writes. Network blocked (not on the default Windows tier, which cannot block it; see the sandbox section below). | Before a file write, and before anything that needs more than the sandbox gives. | | `auto` (default) | `AUTO` | Write in the workspace and temporary directories. Network open unless you turn it off. | When the model asks to leave the sandbox, and for tools that are not confined by it. | | `full-access` | `FULL` | None. | Explicit `prompt` rules, unanalyzable commands when a restrictive rule applies in scope, and dangerous commands (below). | ```sh mare --permission read-only # for this run mare --yolo # same as --permission full-access ``` ```lua -- ~/.config/mare/init.lua mare.plugin("permissions", { preset = "auto" }) ``` Inside a session, `/permission` opens a picker, `/permission read-only` (or `auto`, `full-access`) switches directly, and `Shift+Tab` cycles through `read-only` → `auto` → `full-access` → `read-only`. `/yolo` switches to `full-access`; mare asks you to confirm. `/permission log` shows what was decided and why, and `/permission caps` shows what the sandbox backend on this machine can enforce. The session records its preset, so resuming restores it. In an untrusted project (see below), an explicit CLI flag preset (`--permission` or `--yolo`) still wins first; otherwise mare starts in `untrusted_preset`, whose default is `read-only`, instead of the configured `preset` (including values set via `--set plugins.permissions.preset=...`), and downgrades to that ceiling if project trust is revoked. Pressing `Shift+Tab` in an untrusted directory still steps down directly to `read-only` (for example from `full-access`), and when the next preset in the cycle is `auto` or `full-access`, it opens the same picker as `/permission` with the current preset selected instead of raising permissions on a single keypress. Pressing `Esc` leaves the current preset unchanged, choosing `auto` applies to the session, choosing `full-access` still asks for confirmation, and switching presets never changes project trust. In `auto` and `read-only`, shell commands run inside the sandbox without asking. If a command fails because the sandbox denied something, the model can retry it with a request for the narrowest extra right that the denial names: network access (to a host), write access to a path, or everything. That retry asks you. An approval applies to that one call and is never retried automatically. The default Windows tier cannot control the network, and mare accepts that gap without refusing. To keep the `read-only` promise as far as it can, mare asks before every shell or command tool (`info.command_tool == true`, covering `bash`, `powershell`, and `mare.tool.command` tools) unless that exact unrestricted access (`all` / `danger-full-access`) was already approved or allowed by rule. For strict refusal instead, set `accept_partial` explicitly (see below). ### Customizing `auto` ```lua mare.plugin("permissions", { preset = "auto", writable = { "~/.cache/pip", "/data/scratch" }, -- extra writable directories (must exist; use physical paths, not symlinks) deny_read = { "/home/alice/.ssh" }, -- literal absolute paths the sandbox hides from reads network = { default = "deny", allow = { "github.com", "*.npmjs.org" } }, }) ``` Relative extra writable directories are resolved against the working directory. A directory that does not exist, or is not a directory, is skipped with a notice and flagged by `mare doctor`. A directory that exists but is a symlink, or lies behind one, is refused by the sandbox policy instead of being skipped; use its physical path. `network` is `true` (open), `false` (blocked) or a table with `allow`, `deny`, `default` and `allow_local`. A table is enforced through a local filtering proxy; see network policy below. ## Approvals When a tool call needs your decision, mare shows a dialog titled `Allow <tool>?` with the reason, the working directory and, for edits, a preview of the change. | Choice | Key | Meaning | | --- | --- | --- | | Allow once | `y` | Run this call. | | Allow for this session | `a` | Run this call, and the same call again without asking, for the rest of the session. For shell commands "the same" means the same command, directory and requested scope: approving `git push` does not approve `git push --force`. | | Allow and remember | `A` | Save a rule and allow. For shell commands the rule is an argv prefix such as `git push`, saved in the rules file and used by every session. For other tools it allows all calls to that tool for this session. | | Deny | `n` | Refuse this call. You are asked for an optional reason, which the model reads in the tool result. | | Deny and stop | `Ctrl+C` | Refuse and end the turn. | `Esc` denies the call and lets the turn continue. For a request for extra sandbox rights the choices are for this turn or for this session. Only one approval is shown at a time. If the call comes from a sub-agent, the dialog names it. ### Requesting additional permissions The `permissions` plugin also registers the built-in `request_permissions` tool (see [Tools and shell mode](https://signalridge.github.io/mare/en/use/tools/)). Instead of failing on a sandbox denial and retrying, the model can call `request_permissions` up front with `additional_permissions` (`read` paths, existing physical `write` directories, or `network` boolean / host allowlist), a required `justification`, and `scope` (`"turn"` by default, or `"session"`). You can grant all or only part of the request. The tool returns JSON (`{ permissions, scope }`) listing only newly approved or reused additional rights; access already present in the baseline preset is omitted, and a denied request grants nothing. Subsequent calls within that turn or session reuse the approved scope without prompting again. If the host sandbox baseline changes (`sandbox/changed`, for example after switching presets or updating the host policy), mare clears all transient turn and session grants and session approval caches so stale grants never carry over. ### Approval policy The approval policy is separate from the preset. It decides what happens to a request that would ask: ```sh mare --approval-policy never # reject every request without prompting ``` - `ask` (default): prompt you. - `never`: reject requests without prompting. The sandbox still applies. - `untrusted`: ask before every tool call except those that only read, even where the sandbox would allow it. - A table `{ mode = "granular", categories = { tool = true, network = true } }` allows asking only for the listed categories and rejects the rest. Set it with `mare.plugin("approvals", { policy = "never" })` (RPC `options.set {session_id: "...", values: {"plugins.approvals.policy": "never"}}`, `--set plugins.approvals.policy=never`) or `/approval never`. A sub-agent can only tighten the policy it inherits. ### Dangerous commands Some commands ask in every preset, including `full-access`: `rm -f` / `--force` and `find -delete` (found anywhere in the script, through wrappers), and on Windows `Remove-Item -Force`, `del /f` and `rd /s /q`. In headless runs nobody can answer, so they are denied. Only a rule that allows that exact command lets one pass without asking. ```lua mare.plugin("permissions", { dangerous = { rules = { { "git", "push", "--force" } } }, -- add your own argv prefixes }) ``` ## Rules Rules fix a decision for matching commands. They are checked against the parsed command: plain words joined by `&&`, `||`, `;` or `|` are split into segments, and every segment must match an allow rule. A command with `$(...)`, backticks, expansions, subshells, redirections (except fixed sinks like `/dev/null`), `eval` or a nested shell cannot be analyzed, so no allow rule applies to it. ```lua mare.plugin("permissions", { rules = { { argv = { "git", "status" }, decision = "allow" }, { argv = { "git", "push" }, decision = "prompt" }, { argv = { "rm", "-rf" }, decision = "forbidden", justification = "never delete recursively" }, { tool = "my_unconfined_tool", decision = "allow" }, }, }) ``` `decision` is `allow`, `prompt` (always ask) or `forbidden` (always deny). When several rules match, the strictest wins: `forbidden`, then `prompt`, then `allow`. Optional fields are `cwd` (a glob such as `~/src/**`), `scope` (`network`, `write:<path>`, `all`), `deny_args` and `expires`. Rules saved with "Allow and remember" live in `~/.local/state/mare/permissions.json`, which several sessions share safely; edit it or set `rules_file` to move it. ## Project trust A project can ship code and prompts that mare would load: `.mare/plugins`, `.mare/init.lua`, `.mare/skills`, `.mare/prompts`, `.mare/SYSTEM.md`, and `.mare/APPEND_SYSTEM.md` from the project resource root (nearest directory with `.mare/` or `.mcp.json`, up to the git root). Trust probing checks upward to the git root for `.agents/skills`; when loading skills, default relative skill directories are resolved once against `mare.project.root`. Project resources load only if you trusted the resource root (with no deny along the path to it). Decisions are stored in `~/.local/state/mare/trust.json`. ```sh mare trust # trust the current project; pass a directory with mare trust <dir> mare trust --revoke # stop trusting it mare --trust # trust it for this run only; saves nothing mare --no-trust # distrust it for this run, whatever was saved ``` The first time you open mare in a directory with such resources (or inside a git repository), the interactive TUI shows a trust overlay listing discovered resources by group (project config with a full-API warning for `.mare/init.lua`, plugins, skills, prompt templates, system prompt files, and sanitized MCP server names with executable basename or URL host only; press `e` to expand or collapse groups with more than six items). The overlay offers four choices: **Trust and load** (saved to `trust.json`), **Trust this session only** (loads project resources for the current session without saving), **Don't trust** (saved), and **Not now** (`Esc`, ask again next time). Headless and RPC runs never ask: untrusted resources stay unloaded and mare prints a note to stderr unless you pass `--trust` (trust for this run without saving) or saved trust already exists. The `trust_default` option (`ask`, `trust` or `distrust`) sets the default for directories with no saved decision. Trust only covers loading project files. MCP servers from the project have their own approval; see [MCP](https://signalridge.github.io/mare/en/use/mcp/). ## The operating-system sandbox The sandbox confines the processes mare starts for tools (the `bash` tool, other command tools) and file access made by mare's own file primitives, using the session's current preset. There are three levels: `read-only`, `workspace-write` and `danger-full-access`. Inside `workspace-write` the writable roots are the working directory, extra workspace directories added with `--add-dir` or `/add-dir` (existing absolute physical directories that do not overlap host-protected or project-protected paths), the platform temp areas and `writable`. Inside the workspace, `.git` and `.mare` stay read-only for confined processes when the backend reports `fs_protect`; Landlock and the Windows tiers do not. ![Three-platform OS sandbox backends and probed capabilities](https://signalridge.github.io/mare/assets/diagrams/sandbox-backends.svg) When a command escalates with `write:.git` inside a git linked worktree or submodule where `.git` is an existing pointer file (`gitdir: ...`), mare resolves the target `gitdir` strictly without symlinks instead of widening the surrounding workspace. For a valid linked worktree (verified `commondir`, `worktrees/` ancestry, `objects`/`refs`/`HEAD` layout, and matching `gitdir` backlink), `write:.git` grants write access to both the worktree's `gitdir` and the shared repository `commondir`; existing symlinked or malformed `.git` pointers and backlinks are rejected. If `.git` itself does not exist, `write:.git` follows the ordinary missing-file branch and requests write scope for its existing parent directory (which still requires the applicable approval). | Platform | Backend | Notes | | --- | --- | --- | | Linux | bubblewrap (`bwrap`), then Landlock | `bwrap` must be installed and able to create namespaces. It mounts the host root read-only, with a private `/proc`, `/dev` and PID namespace, and binds the writable roots. Network is blocked with a network namespace; filtered networking uses a loopback-only namespace bridged to the proxy. If `bwrap` is unusable, Landlock is used: file writes and reads are restricted, and sockets are blocked with seccomp, but it cannot protect `.git` and `.mare` or provide domain filtering. | | macOS | Seatbelt (`/usr/bin/sandbox-exec`) | A profile that denies file writes except the writable roots and can restrict reads, outbound network and Unix sockets. | | Windows, default tier | Restricted token, Low integrity, ACL grants | Writes are confined. Reads and the network are not controlled, and mare reports this as partial. mare accepts the missing network control by default (see the paragraph on approvals above). | | Windows, enhanced tier | Dedicated sandbox accounts, setup-time deny-read ACLs, firewall filters | Install once with `mare sandbox setup` (asks for elevation). Setup applies deny-read ACLs to credential and browser paths for the sandbox account, but `windows-user` does not declare per-call `fs_deny_read` (nor allowlist `fs_read`), so strict calls requesting explicit `deny_read` are refused unless partial protection is accepted. Network is filtered, but the filter's proxy ports are shared by all sandboxed calls, so per-call network isolation is not enforced and the sandbox does not report `net_block` or `net_proxy`. `mare sandbox status` runs a self-test; `--require-full` exits non-zero unless everything is enforced; because per-call network isolation is not, it currently exits non-zero even when the self-test passes. `mare sandbox setup --remove` undoes the setup. If the self-test fails, mare falls back to the default tier and reports why. | mare probes each backend on demand and caches which capabilities actually work (`fs_read`, `fs_deny_read`, `fs_write`, `fs_protect`, `fs_host_protect`, `net_block`, `net_proxy`, `unix_socket`). A preset that needs a capability the backend lacks is refused with `SANDBOX_INSUFFICIENT`, naming it, instead of running weaker. If no backend works, commands are refused with `SANDBOX_UNAVAILABLE`; mare never runs them unconfined silently. The default exceptions are a missing `fs_protect`, which is accepted and reported as partial on every platform, and a missing network control on the default Windows tier. To accept other gaps explicitly: ```lua mare.plugin("permissions", { accept_partial = { "network" } }) ``` An explicit `accept_partial = {}` means strict refusal. Run `mare doctor` to see the backend and capabilities for your machine, or `/permission caps` in a session. ### Network policy In `auto`, `network = true` leaves the network open for sandboxed commands (the built-in `web_fetch` HTTP client still blocks private, loopback, link-local, and metadata IPs by default). `false` blocks it. A table with `allow` / `deny` hosts and `default` sends traffic through a local proxy that filters by host; the sandbox lets the command connect only to that proxy. Unix sockets are blocked while the network is restricted; per-socket exceptions (`unix_sockets`) apply only on backends that support them (Linux's seccomp `AF_UNIX` path does not support per-socket allowlists). Setting proxy environment variables alone never counts as enforcement. ## What is not protected - Reads are open by default: under `auto` and `read-only`, a confined command can read any file your user can (including `~/.ssh`) unless listed in `deny_read` or hidden by the Windows enhanced tier's defaults. Anything read can be sent to the model provider. - `auto` allows outbound network unless you change `network`. - `full-access` and approved unconfined tool calls run without a sandbox. Under `auto`, tools outside the local sandbox (such as MCP tools) ask before running. - Landlock and the Windows default tier do not protect `.git` or `.mare`; the Windows default tier does not control reads or network. - The sandbox is not a VM: it shares your kernel, user, and home directory. Approving `write:.git` lets a command edit git hooks that execute outside the sandbox. - Direct `!cmd` shell commands bypass approval prompts. - Prompt injection is not solved by sandboxing: read approval prompts before pressing `y`. - Shell side effects cannot be reverted with `/rewind`; see [Sessions](https://signalridge.github.io/mare/en/use/sessions/). ================================================================================ Title: Sessions Section: Use mare URL: https://signalridge.github.io/mare/en/use/sessions/ Markdown: https://signalridge.github.io/mare/raw/en/use/sessions.md Source: docs/en/use/sessions.md ================================================================================ # Sessions Each session is an append-only JSONL file scoped to a working directory. Every entry stores an `id` and `parent`, so rewinding or retrying creates a branch while keeping prior branches in the same file. ## Where sessions live ```text ~/.local/state/mare/sessions/<directory-slug>/<timestamp>_<id-suffix>.jsonl ``` The state directory follows `$XDG_STATE_HOME` (or `$MARE_HOME/state` if `MARE_HOME` is set). `<directory-slug>` is the working directory path with every character other than Unicode alphanumeric characters, `.`, and `_` replaced by `-`, wrapped in `--`. A session file is created when the first message is written, not at startup. For a session file `abc.jsonl`, its attachments sit beside it in `abc.attachments/` (images moved out of the log) and its `/rewind` backups in `abc.jsonl.snapshots/`. When there is no session file, snapshots use `<state>/snapshots/run-<pid>-<uuid>/`, and compacted images fall back to `<state>/attachments/<session-id or unsaved>/`. See [Files](https://signalridge.github.io/mare/en/reference/files/) for the full file layout. ### Durability and crash recovery - Appends are whole lines. A trailing line without a newline is a torn write: readers ignore it and the next write truncates it. - At semantic boundaries (for example when a message is complete) the file is flushed to disk with `fsync`. A batch that fails to write or sync is rolled back to its previous length. - A line that ends in a newline but does not parse is treated as corruption. mare never opens such a file for writing or rewrites it; you can view it read-only or fork from a stable snapshot. - One process writes a session at a time, enforced with a lock file next to the session. If another process has it open, mare offers a read-only view or a fork instead. - mare records a `running` marker when it opens a session and a `closed` marker on a clean exit. A session whose last marker is `running` was interrupted. It shows as crashed in the `/resume` picker, and `/continue` resumes an interrupted turn. ## Resume and continue ```sh mare -c # most recent session in this directory mare -c --all # most recent session in any directory mare -r # open the picker mare -r 3f9a1c2e # by id, or an unambiguous id prefix (headless) mare -r "fix login bug" # by name, case-insensitive (headless) mare -r -2 # the second most recent session here mare -r ./some/session.jsonl # by file path ``` | Option | Meaning | | --- | --- | | `-c`, `--continue` | Continue the most recent session in this directory. | | `-r`, `--resume [VALUE]` | Resume by id, name, `-N` or path. Without a value, open the picker. | | `--all` | With `-c` or `-r`, look at sessions of every directory. | | `--fork-session` | With `-c` or `-r`, continue in a copy and leave the original untouched. | | `--session-id ID` | Use this id for a new session: 8 to 64 letters, digits, `-` or `_`. Fails if the id exists. | | `--name NAME` | Name the new or resumed session. | | `--no-session` | Do not save the session. mare may still write runtime files and per-run snapshots, and tools can write files. The session cannot be resumed, and `-c` or `-r` together with it is an error. | In the interactive UI, `-r <text>` that is not a full id, a `-N` or a file path opens the picker with the text as the search. In headless runs a name or prefix that matches several sessions is an error that lists the candidates; mare never picks "the newest" for you. A session that cannot be found is an error (exit code 1), never a silent new session. If you resume a session that was recorded in another directory, the TUI asks which directory to use. The `session` plugin option `resume_cwd` takes `"ask"` (default), `"current"` or `"session"`. ```lua mare.plugin("session", { resume_cwd = "current" }) ``` ### Scripts `mare session new` creates an empty session in the current directory and prints its id, so a script can create the session first and run prompts into it: ```sh id=$(mare session new --name nightly-review) mare -p --resume "$id" "list the TODO comments in src/" mare -p --resume "$id" "now rank them by risk" ``` `mare session` provides `new`, `list`, `fork`, `archive`, `unarchive`, and `delete` subcommands (see [CLI reference](https://signalridge.github.io/mare/en/reference/cli/#mare-session)). It runs a lightweight session host without loading user/project configs or plugins, using `--cwd` and (for `new` and `fork`) `--name`; pass run options such as `--model`, `--trust`, or `--permission` to the subsequent `mare -p --resume "$id"` calls. See [Headless](https://signalridge.github.io/mare/en/use/headless/). ## In the session | Command | Effect | | --- | --- | | `/new` (`/clear`) | Start a new session. The old one stays on disk. | | `/resume` (`/sessions`) | Open the picker. `/resume all` lists every directory; `/resume search <text>` filters; `/resume <id or name>` loads one. Not available while a turn runs. | | `/name <title>` (`/title`, `/rename`) | Name the session. Without a title it shows the current name. | | `/fork` | Fork into a new session from your latest message. `/fork pick` lets you choose the message. | | `/clone` | Duplicate the whole session into a new one. | | `/tree` | Browse the session tree and branch from any earlier point. | | `/label <text>` | Label the current point in the tree. | | `/retry` | Regenerate the last answer on a new branch. The old answer stays at its branch. | | `/continue` | Continue an interrupted turn after a crash or kill. | | `/archive` | Mark the session archived and start a new one. The file stays. | | `/delete` | Delete this session after a confirmation. | Picker keys: `Ctrl+D` delete, `Ctrl+R` rename, `Ctrl+S` sort by created or updated, `Ctrl+N` named only, `Ctrl+A` show archived, `Ctrl+X` archive, `Ctrl+E` expand, `Ctrl+T` transcript, `Ctrl+L` change layout. The `session` plugin option `picker_style` selects `"comfortable"` (default), `"dense"` or `"cards"`. ### Undo and rewind `/undo` and `/rewind` are different. - `/undo` rewinds the conversation to before a prompt and puts the prompt text back in the input. Files on disk stay as they are. `/undo` opens a picker; `/undo 2` goes back two prompts. Only prompts since the last compaction can be undone. Pressing `Esc` twice on an empty idle input opens the same picker. The undone messages stay in the file on their own branch (see `/tree`). - `/rewind` restores files. mare saves the original of a file before any tool writes, removes or renames it, and `/rewind [turn]` puts those files back to how they were before a turn. You choose between restoring files only, restoring files and the conversation, or summarizing the conversation from that turn on. `/rewind` cannot undo changes made by shell commands, and the turn says so. If a file changed outside mare after the turn, it is listed and restored only after you confirm. Backups are capped (`changes` plugin option `cap_bytes`, 64 MiB by default); when the oldest are trimmed they are reported as missing. `/diff` shows the files changed in each turn. ### Compaction Long sessions are compacted so they fit in the model's context window. Compaction writes summary or projection records into the session JSONL file while leaving all original messages intact on disk (reachable via `/tree` or inspecting the file). ```text /compact compact now /compact keep the migration plan compact with a focus instruction ``` For the four compaction stages (`prune`, `offload`, `remote`, `local`), threshold precedence, backoff and `stalled` handling, and `compact` plugin options, see [Usage and compaction](https://signalridge.github.io/mare/en/use/usage-and-compaction/). For what stays outside compaction on every request, see [Context](https://signalridge.github.io/mare/en/use/context/). ### Export and copy - `/export [path]` writes the conversation as redacted Markdown with private file permissions (`0600` on Unix). Without a path the file is `mare-session-<date>-<time>.md` in the working directory. `/export-md` is an alias. - `/copy` copies the last response to the clipboard as Markdown source. If it has code blocks, a picker offers each block or the full response; `w` in the picker writes the choice to a file and `a` remembers "always copy the full response". `/copy 2` copies the second-to-last response. The clipboard path uses OSC 52 over SSH. ### Deleting sessions `/delete` removes the current session together with its attachments and snapshots, then starts a new one. `/delete <path>` deletes the session file at that path after a confirmation. Deletion is refused while another process has the session open. The picker's `Ctrl+D` does the same for the highlighted row. There is no undelete. ================================================================================ Title: Skills and prompt templates Section: Use mare URL: https://signalridge.github.io/mare/en/use/skills/ Markdown: https://signalridge.github.io/mare/raw/en/use/skills.md Source: docs/en/use/skills.md ================================================================================ # Skills and prompt templates Skills package reusable `SKILL.md` instructions that load on demand. Prompt templates turn Markdown files into `/command` shortcuts with shell-style argument expansion. ## Skills A skill is a directory containing a `SKILL.md` file with YAML frontmatter and Markdown instructions: ```text ~/.config/mare/skills/release-notes/SKILL.md ``` ```markdown --- name: release-notes description: Draft release notes from commits since the last tag. Use when asked to prepare a release. argument-hint: "[tag]" --- 1. Run `git describe --tags --abbrev=0` to find the previous tag. 2. Group commits since that tag by area. 3. Write the draft in `RELEASE_NOTES.md`. ``` Only each skill's `name`, `description`, and file location enter the system prompt. When a task matches the description, the model reads `SKILL.md` with the `read` tool. You can install dozens of skills without bloating every turn. ### Discovery order and trust The `context` plugin scans these directories in order. When two skills share a `name`, the first one found wins: | Order | Directory | Scope | Trust required | |---|---|---|---| | 1 | `~/.config/mare/skills/` | User | No | | 2 | `~/.agents/skills/` | User, shared across agents | No | | 3 | `.mare/skills/` | Project resource root (nearest `.mare/` or `.mcp.json` up to `.git`) | Yes | | 4 | `.agents/skills/` | Resolved against the same project resource root (`mare.project.root`) | Yes | | 5 | `<package>/skills/` | Installed [packages](https://signalridge.github.io/mare/en/configure/packages/) | No | Change search paths with `skill_dirs` in `init.lua`. Relative entries resolve via `mare.project.root` and require [project trust](https://signalridge.github.io/mare/en/use/permissions/#project-trust). ```lua mare.plugin("context", { skill_dirs = { "~/.config/mare/skills", "~/.agents/skills", ".mare/skills", ".agents/skills" }, }) ``` > Startup trust detection walks ancestor directories up to `.git` for `.agents/skills`, so an ancestor `.agents/skills/` can trigger a trust prompt even though the skill loader only scans the resolved project root. ### Frontmatter fields and validation | Field | Required | Effect | |---|---|---| | `name` | No | Defaults to the directory name. Lowercase `a-z`, `0-9`, and hyphens (`-`), up to 64 characters. | | `description` | Yes | Shown to the model and `/skills`. Skills without a `description` are skipped. Maximum 1024 characters. | | `argument-hint` | No | Shown after `/skill:<name>` in the `/` menu. | | `disable-model-invocation` | No | When `true`, omits the skill from the system prompt so it runs only when you invoke `/skill:<name>`. | | `compatibility` | No | Checked up to 500 characters; diagnostics warn if exceeded. | | `allowed-tools` | No | Parsed from frontmatter, not enforced by mare. | Naming and length issues produce warnings instead of blocking startup. Run `/skills` or `mare doctor` to inspect skipped skills and warnings. ### Running a skill manually Invoke any loaded skill as a slash command, with optional arguments appended after the instructions: ```text /skill:release-notes v0.2.0 ``` Running `/skills` with no arguments opens a searchable picker of loaded skills and prints any scan warnings. Before each prompt, mare checks modification times and sizes on `SKILL.md` files and rebuilds the cached system prompt if anything changed. ## Prompt templates A Markdown file under `~/.config/mare/prompts/` or `.mare/prompts/` registers a slash command named after the file (without `.md`). Installed packages can also ship templates in `prompts/`. When names collide, project templates override user templates, and user templates override package templates. A prompt template never shadows an existing built-in or plugin command such as `/review`. ```markdown --- description: Review staged changes before committing argument-hint: "[focus]" --- Inspect the output of `git diff --staged`. Focus on: ${@:-correctness, edge cases, and tests}. ``` Save this as `~/.config/mare/prompts/review-staged.md` and run: ```text /review-staged concurrency and error paths ``` ### Argument substitution Templates support shell-style quoting (for example `"error paths"`) and these placeholders: | Placeholder | Expands to | |---|---| | `$1`–`$9` | Single-digit positional argument (empty string if omitted; bare `$10` expands as `$1` plus literal `0`) | | `$@`, `$ARGUMENTS` | All arguments joined by spaces | | `${N:-default}` | Positional argument `N` (supports multi-digit indices such as `${10:-fallback}`), or `default` when omitted/empty | | `${@:-default}` | All arguments, or `default` when none are given | | `${@:N}` | Arguments starting from index `N` (supports multi-digit `N`) | | `${@:N:L}` | Up to `L` arguments starting from index `N` (supports multi-digit `N`, `L`) | Override the template directories in `init.lua` with `prompt_dirs`: ```lua mare.plugin("context", { prompt_dirs = { "~/.config/mare/prompts", ".mare/prompts" }, }) ``` Relative paths in `prompt_dirs` load only after the project is trusted (`mare trust`). ## Related - [Context and instructions](https://signalridge.github.io/mare/en/use/context/) for `AGENTS.md`, `SYSTEM.md`, and `APPEND_SYSTEM.md` - [Packages](https://signalridge.github.io/mare/en/configure/packages/) for sharing skills and prompts in git packages - [Permissions and sandbox](https://signalridge.github.io/mare/en/use/permissions/#project-trust) for how project trust is stored and checked ================================================================================ Title: Subagents and side threads Section: Use mare URL: https://signalridge.github.io/mare/en/use/subagents/ Markdown: https://signalridge.github.io/mare/raw/en/use/subagents.md Source: docs/en/use/subagents.md ================================================================================ # Subagents and side threads mare supports two ways to isolate work from your main conversation: persistent child agents (`subagent`) that execute tasks in separate threads, and ephemeral side threads (`/side`, `/btw`) for quick questions that never enter the session log. ## Subagents The `subagent` plugin lets the model spawn independent child sessions with their own session context; by default they inherit the parent working directory unless `cwd` is set, with per-type or per-call tool allowlist and model override. Child threads are tracked by the host's `AgentRegistry` (`crates/mare-host`), bounded by core `agents` limits, and persisted under `sessions/<project>/agents/<run>/<seq>-<label>.jsonl`. ### Tools exposed to the model | Tool | Role | |---|---| | `subagent` | Start a child agent with `prompt`, optional `type`, `fork` (`"none"`, `"all"`, or turn count), `name`, `cwd`, `model`, `effort`, `tools`, `system`, and `wait` (`false` by default). | | `subagent_wait` | Block until a child finishes (or until `timeout_ms`), returning its final output. | | `subagent_steer` | Send a steering message into a running child agent. | | `subagent_cancel` | Cancel a subagent and its descendants. | | `subagent_list` | List subagents spawned in the current session with their ids, names, statuses, and tasks. | By default, `subagent` starts the child in the background. When it finishes, mare delivers a one-line completion summary (`[subagent <id> finished: <status>...]`) to the parent, attaching a `<subagent-output agent="…">` block only when the child produced output or error text. Set `wait = true` to block on the result inline. A background subagent belongs to the mare process that started it. If that process exits or crashes before the subagent finishes, resuming the session marks it `interrupted`: `subagent_list` and `subagent_wait` report that status, and the model gets one notice naming the subagent and its transcript so it can start the work again. ### Built-in subagent types | Type | Purpose | Tool scope | |---|---|---| | `general` | General delegated implementation or investigation work | Inherits available tools and permissions from the parent | | `explore` | Inspect code and locate evidence without modifying files | `read`, `ls`, `bash` (read-only sandbox) | | `plan` | Design a concrete implementation plan without modifying files | `read`, `ls`, `bash` (read-only sandbox) | ### Custom subagent types Define reusable agent types as Markdown files with YAML frontmatter in `~/.config/mare/agents/*.md` or (for trusted projects) `.mare/agents/*.md`: ```markdown --- name: security-auditor description: Audits changes for auth, path traversal, and secret leaks. when_to_use: Use before merging changes to auth, RPC, or sandbox code. tools: - read - ls model: anthropic/claude-sonnet-5-5 effort: high --- You are a read-only security reviewer. Report concrete findings with file and line numbers. ``` Frontmatter fields: `name`, `description` (required), `when_to_use`, `tools`, `disallowed_tools`, `model`, and `effort`. The Markdown body becomes the agent's system prompt. > `tools` filters tool names only; custom subagents inherit the parent's permission ceiling. To enforce a read-only boundary, omit mutating tools such as `bash` or launch with `--permission read-only` (for example `mare --permission read-only --agent security-auditor`; built-in `explore`, `plan`, and `/review` set `permission = "read-only"`). Add extra search paths in `init.lua` (project-relative directories require trust): ```lua mare.plugin("subagent", { extra_agent_dirs = { ".mare/custom-agents" }, notify_inline_bytes = 4096, }) ``` ### Limits and approvals Root-shared thread limits are configured in `mare.setup`: ```lua mare.setup { agents = { max_active = 16, -- total live descendant threads across the tree (0 disables delegation) max_depth = 4, -- maximum nesting depth from the root session }, } ``` When a subagent requests an approval that leaves its sandbox, the `agent-approvals` plugin forwards the request to the parent session's UI (`agent/approval-dialog`). A queue line below the input shows pending child approvals in arrival order, and the dialog names the requesting child. ### Inspecting subagents with `/agents` Run `/agents` (or press `Left` on an empty input) to open the agent list. It shows active subagents, workflow members, background jobs, and (in the Peers tab) other running `mare` sessions on the machine. - Press `Enter` on a subagent to view its live transcript read-only. - Press `Alt+Left` / `Alt+Right` to cycle between subagent views. - Press `Esc` to return to the list, or `Ctrl+G` to jump to `/resume`. ## Side threads (`/side` and `/btw`) The `conversations` plugin runs ephemeral, parent-isolated side conversations branched from the committed history of your current session. Side threads never write messages to the session JSONL file. ```text /side why did the test fixture skip line 42? /btw what does EADDRINUSE mean here? ``` `/side` and `/btw` share the same entrypoint: | Command | Action | |---|---| | `/side` or `/btw` | Open an empty side thread widget above the editor | | `/side <question>` / `/btw <question>` | Open a side thread and send the question immediately | | `/side toggle` | Show or hide the active side thread | | `/side back`, `/side close`, or `Esc` | Close and discard the side thread | While a side thread is open, prompts you type in the input go to the side thread rather than the main agent, and the widget header displays the parent agent's live state (`idle`, `working`, or `blocked`). In the input box, only safe inspection commands (`/side`, `/btw`, `/help`, `/status`, `/session`) run inside a side thread, and any tool calls executed by the side loop run under the `ephemeral-read-only` tool execution lifetime. Token usage and cost from side requests are still counted by the `usage` plugin. ## Related - [Permissions and sandbox](https://signalridge.github.io/mare/en/use/permissions/) for how child approvals and sandbox inheritance work - [RPC peer sockets](https://signalridge.github.io/mare/en/integrate/rpc/#peer-sockets) for peer sockets and `mare peer send` - [Options](https://signalridge.github.io/mare/en/configure/options/) for `agents` configuration limits ================================================================================ Title: Tools and shell mode Section: Use mare URL: https://signalridge.github.io/mare/en/use/tools/ Markdown: https://signalridge.github.io/mare/raw/en/use/tools.md Source: docs/en/use/tools.md ================================================================================ # Tools and shell mode Every built-in tool in mare is registered by Lua plugins (`tools`, `tools-apply-patch`, `jobs`, `web`, `subagent`, `permissions`) and executed through one guarded pipeline that validates arguments, checks policy, enforces the OS sandbox, and captures file snapshots for mare's file tools (`write`, `edit`, `apply_patch`; shell subprocess side effects are not snapshotted). ## Built-in tools | Tool | Plugin | Purpose | |---|---|---| | `read` | `tools` | Read UTF-8 text files (with `offset`/`limit`), directory listings, or images (`png`, `jpg`, `jpeg`, `gif`, `webp`). | | `write` | `tools` | Create or overwrite files, capturing a snapshot before overwrite. Writes atomically for ordinary files, and in place (`atomic = false`) when the file has multiple hard links so the other links stay linked. | | `edit` | `tools` | Exact string replacement (`old_string`, `new_string`, `replace_all`). Active when `edit_mode = "replace"`, or under `"auto"` when neither the model's `edit_tool` nor the provider default selects `apply_patch`. | | `apply_patch` | `tools-apply-patch` | Multi-file patch format (`*** Begin Patch` / `*** End Patch`). Active when `edit_mode = "apply_patch"`, or under `"auto"` when selected by the model's `edit_tool` or provider default (built-in matching covers GPT and Codex). Explicit `edit_mode` always wins. | | `ls` | `tools` | List directory entries up to `ls_limit` (default `500`), including dotfiles. | | `bash` | `tools` | Run commands in a persistent or job-tracked shell inside the OS sandbox. | | `powershell` | `tools` | Run PowerShell commands on Windows (`powershell = "auto"` by default, or `"replace"` to swap in for `bash`). | | `job_output`, `job_list`, `job_write`, `job_kill` | `jobs` | Read, list, feed stdin/EOF to, or stop background jobs. | | `web_search`, `web_fetch` | `web` | Search the web or fetch HTTP(S) pages (fetched via `web-fetch-http` `http-text` backend or provider-native search). | | `tool_search` | `tools` | Discover deferred tools (such as deferred MCP tools) and inspect their input schemas by keyword or `select:<name>`. | | `call_tool` | `tools` | Invoke a deferred tool by name and arguments on models without native mid-conversation tool updates (`tool_update = "addition_only"`), keeping `tools[]` fixed for prompt caching. | | `subagent`, `subagent_*` | `subagent` | Spawn and manage child agents (see [Subagents and side threads](https://signalridge.github.io/mare/en/use/subagents/)). | | `request_permissions` | `permissions` | Request additional read/write paths or network hosts with a justification and `turn` or `session` scope (see [Permissions and sandbox](https://signalridge.github.io/mare/en/use/permissions/#requesting-additional-permissions)). | ### Read-before-edit and edit modes The `tools` plugin enforces `read_before_edit = true` by default: `edit`, `apply_patch`, and overwriting `write` refuse to touch an existing file unless the session read it first, and fail if the file changed on disk since that read. Switch edit tools in `init.lua` or on the command line: ```lua mare.plugin("tools", { edit_mode = "auto", -- "auto" | "apply_patch" | "replace" read_before_edit = true, bash_timeout_ms = 120000, max_lines = 2000, max_bytes = 50 * 1024, }) ``` ### Disabling or adding command tools Hide built-in tools or register shell-backed tools directly in `init.lua`, or exclude tools per invocation on the CLI with `--exclude-tools` (repeatable or comma-separated, supporting `*` globs, e.g. `mare --exclude-tools bash,write` or `mare --exclude-tools "mcp__*"`): ```lua mare.tools.disable({ "ls" }) mare.tool.command { name = "grep", description = "Search file contents with ripgrep.", command = { "rg", "--line-number", "--no-heading", "--max-columns=500", "--regexp={pattern}", "--", "{path}" }, params = { pattern = { type = "string", required = true }, path = { type = "string", default = "." }, }, readonly = true, } ``` Commands registered with `mare.tool.command` inherit the credential-scrubbed environment (`KEY`, `PASSWORD`, `SECRET`, `TOKEN`, and inherited `MARE_*` variables stripped) and honor the `tools` plugin's `env` settings: `env.include` keeps named inherited variables across the scrub, `env.exclude` drops additional names, and `env.set` assigns values after scrubbing. mare also injects runtime context variables (`MARE_CWD`, `MARE_SESSION_ID`, `MARE_SESSION_MODEL`, `MARE_SESSION_EFFORT`, and `MARE_PEER_SOCKET` when active). Without `readonly = true`, mare treats them as having side effects. ## Web search and fetch The `web` and `web-fetch-http` plugins provide `web_search` and `web_fetch`. `web-fetch-http` blocks URLs with embedded credentials as well as private, loopback, link-local, and metadata IP addresses (even under `auto`), and returned content is wrapped with an untrusted-data notice before reaching the model. - Inspect or switch backends inside a session with `/web`: - `/web` shows the current mode (`cached` by default) and available backends. - `/web mode disabled|cached|indexed|live` sets the search mode. - `/web search <id|auto>` and `/web fetch <id|auto>` pick a backend (`http-text` is built in for fetch). Configure limits in `init.lua`: ```lua mare.plugin("web", { web_search = "cached", search_timeout_ms = 30000, fetch_max_output_chars = 200000, }) ``` ## `@file` references and image attachments ### `@file` completion (`file-ref`) Type `@` in the prompt editor to fuzzy-complete paths across the working directory and any extra workspace roots added via `--add-dir <DIR>` at startup or `/add-dir` in a session (`@"path with spaces"` for paths containing spaces). `--add-dir` is repeatable and accepts existing absolute physical directories outside host-protected and project-protected paths (for ACP, pass `additionalDirectories` instead of `--add-dir`). - Default limits: `100 KiB` per file (`max_bytes`) and `256 KiB` total per message (`max_total_bytes`). - Directories attach as entry listings. - Unreadable, binary, denied, or oversized paths are never dropped silently: mare attaches a one-line note telling the model why and pointing to `read`. ### Image attachments (`images`) Paste an image from the clipboard with `Ctrl+V` (`Alt+V` on Windows) or let the model read an image file via `read`. On terminals supporting Kitty, iTerm2, or sixel protocols, the `images` plugin renders them inline; other terminals display `[image]`. ```lua mare.plugin("images", { user = true, read = true, tools = true, max_rows = 12, max_cols = 60, }) ``` ## Output spilling (`spill`) - Shell command logs: When `bash` output exceeds `shell_buffer_bytes` (`1 MiB`) or the truncation limit (`2000` lines / `50 KiB`), full output streams to `~/.local/state/mare/spill/bash-*.log` and the truncated tool result cites that path. Logs from exited processes are cleaned up automatically. - Session-scoped `spill` service: Tools, renderers, and RPC hosts store private text or binary blobs (up to `8 MiB` per object) via `spill.save` / `spill.read`, scoped to the owning `session_id` and pruned after `cleanup_period_days` (default `30`). ## `!` shell mode and background jobs ### Interactive shell mode (`shell-mode`) Start a line with `!` on an empty input to run a command yourself using the same shell, `prelude`, and `MARE_*` environment as `bash`, without an approval prompt: ```text !git status --short # runs command; adds command and output to model context !!cat .env.example # runs command; shows output in scrollback, keeps it out of context ``` Press `Esc` or `Ctrl+C` to cancel a running `!` command, or `Backspace` on an empty shell line to leave shell mode. Model-visible output is middle-truncated to `2000` lines / `50 KiB`. ### Background jobs (`jobs`) Long-running shell commands can run in the background without blocking your conversation: - Press `Ctrl+B` while a foreground command runs to move it to the background. - The model can start commands with `run_in_background = true` (and `tty = true` or `stdin = true` for interactive processes) and monitor them via `job_output` (including `until = "<regex>"` or `tail = N`), `job_write`, and `job_kill`. - Run `/jobs` to list running and finished jobs, inspect their live tail (`view_tail_bytes`), or stop one. When a background job finishes, mare notifies the agent with up to `notify_inline_bytes` (2048 bytes) of output. ```lua mare.plugin("jobs", { max_running = 8, max_jobs = 64, kill_grace_ms = 3000, }) ``` ## Related - [Permissions and sandbox](https://signalridge.github.io/mare/en/use/permissions/) for OS confinement and `bash` rules - [MCP servers](https://signalridge.github.io/mare/en/use/mcp/) for external tools and `tool_search` deferred loading - [Output-backed image resources](https://github.com/signalridge/mare/blob/main/docs/image-resources.md) for artifact image caching ================================================================================ Title: Interactive interface Section: Use mare URL: https://signalridge.github.io/mare/en/use/tui/ Markdown: https://signalridge.github.io/mare/raw/en/use/tui.md Source: docs/en/use/tui.md ================================================================================ # Interactive interface How the mare terminal UI works: the input editor, key bindings, slash commands, file mentions, shell commands, queued messages, transcript and notifications. mare runs in the terminal's main screen, not in an alternate screen. Finished output (messages, tool calls, diffs) is written to your terminal's normal scrollback, so you scroll, search and copy with your terminal's own tools. Only the bottom of the screen is live: the streaming reply, widgets, the input box and the status bar. Start it with: ```sh mare # new session mare "explain this repo" # new session, first prompt already sent mare -c # continue the last session in this directory ``` ## The input editor Type a prompt and press Enter to send it. | Key | Action | | --- | --- | | `Enter` | Send. A trailing `\` before Enter inserts a newline instead. | | `Shift+Enter`, `Ctrl+J` | Insert a newline. | | `Left` / `Right`, `Ctrl+B` / `Ctrl+F` | Move by character. | | `Alt+Left` / `Alt+Right`, `Alt+B` / `Alt+F` | Move by word. | | `Home` / `End`, `Ctrl+A` / `Ctrl+E` | Start / end of line. | | `Up` / `Down`, `Ctrl+P` / `Ctrl+N` | Move between lines; at the first or last line, browse prompt history. | | `Backspace`, `Ctrl+H`; `Delete`, `Ctrl+D` | Delete a character. `Ctrl+D` on an empty input exits. | | `Ctrl+W`, `Alt+Backspace` | Delete the previous word. | | `Alt+D` | Delete the next word. | | `Ctrl+U` / `Ctrl+K` | Cut to the start / end of the line. | | `Ctrl+Y`, `Alt+Y` | Paste the last cut text; cycle earlier cuts. | | `Ctrl+_` | Undo in the input. | | `Ctrl+G` | Edit the input in an external editor. | | `Ctrl+R` after `Up` | Search the prompt history. | | `Tab` | Complete a `@file` or `/command`. | Large pastes are folded into a placeholder in the input and expanded when you send. Prompt history is stored in `~/.local/state/mare/history.jsonl` (or under `$XDG_STATE_HOME/mare`). Not every terminal sends `Shift+Enter` and `Alt+Enter` distinctly. Run `/terminal-setup` to check yours and see how to fix it. ### External editor `Ctrl+G` hands the input to an editor and puts the result back when the editor exits successfully. mare uses the `editor` option, then `$VISUAL`, then `$EDITOR`, then `vi`. The value may contain arguments, for example `code --wait`. ```lua -- ~/.config/mare/init.lua mare.setup { editor = "nvim" } ``` ### Key bindings The bindings below are the defaults. Press `?` on an empty input, or run `/hotkeys`, to see the live list, including your changes. | Key | Action | | --- | --- | | `Esc` | Interrupt the agent. When idle, twice quickly opens the rewind picker (`/undo`). | | `Ctrl+C` | Close a menu, clear the draft, interrupt the running work. Twice on an idle empty input exits. | | `Ctrl+D` | Exit when the input is empty. | | `Ctrl+O` | Toggle compact and expanded tool output and thinking. | | `Ctrl+T` | Open the transcript view. | | `Ctrl+S` | Send the input into the running turn (steer). | | `Alt+Enter` | Queue the input as a follow-up. On Windows the key is `Ctrl+Q`. | | `Ctrl+V` | Paste an image from the clipboard. On Windows the key is `Alt+V`. | | `Ctrl+B` | Move the running shell command to the background; with nothing running, cursor left. | | `Ctrl+L` | Redraw the screen. | | `Ctrl+Z` | Suspend mare (`fg` resumes it). Not available on Windows. | | `Alt+S` | Select mode: drag with the mouse to select text in the live area; releasing copies. | | `?` | List all key bindings (on an empty input). | Rebind any of these with `mare.keymap.set`; see [Keymaps](https://signalridge.github.io/mare/en/configure/keymaps/). ## Slash commands Type `/` at the start of the input to open the command list, then pick with the arrow keys and `Tab` or `Enter`. `/help` lists every command, `/commands` opens a browsable list that runs the one you pick, and `/skills` does the same for [skills](https://signalridge.github.io/mare/en/use/context/). | Group | Commands | | --- | --- | | Session | `/new` (`/clear`), `/resume` (`/sessions`), `/name`, `/undo`, `/rewind`, `/fork`, `/clone`, `/tree`, `/compact`, `/export`, `/copy`, `/delete`, `/archive` | | Model | `/model`, `/effort`, `/login`, `/logout` | | Context | `/init`, `/memory`, `/context`, `/add-dir` | | Safety | `/permission` (`/permissions`), `/yolo`, `/approval` | | Inspect | `/status`, `/usage`, `/diff`, `/jobs`, `/mcp`, `/doctor`, `/config`, `/debug` | | Interface | `/theme`, `/statusline`, `/hotkeys`, `/terminal-setup`, `/show-reasoning` | | Other | `/btw`, `/reload`, `/plugins`, `/exit` (`/quit`) | The command list depends on which plugins are enabled, so use `/help` for the authoritative list in your install. The full reference is in [Slash commands](https://signalridge.github.io/mare/en/reference/slash-commands/). You can add your own short names with `mare.command.alias("m", "model")` in `init.lua`. ## File mentions Type `@` and start a path. `Tab` completes it with a fuzzy match over the files under the working directory and any directory added with `/add-dir`. ```text review @src/main.rs and compare it with @"docs/old design.md" ``` On send, mare attaches the contents of each mentioned file to your message. Paths with spaces use `@"..."`. A directory is attached as a listing. A reference that cannot be attached is not dropped silently: the message gets a one-line note saying why (missing, binary, too large, denied) and pointing at the `read` tool. Limits are 100 KiB per file and 256 KiB per message; both are options of the `file-ref` plugin (`max_bytes`, `max_total_bytes`). ```lua mare.plugin("file-ref", { max_bytes = 200 * 1024 }) ``` ## Shell commands Type `!` on an empty input to enter shell mode, then a command: ```text !git status runs the command; command and output go into the context !!cat .env.example runs the command; the output is shown but not added to the context ``` The command uses the same configured shell program and prelude as the agent's `bash` tool, but it is a separate process: it does not share the agent shell's state (working directory, exported variables) and does not get the `bash` tool's `env_include` and `env_exclude` policy. `Esc` or `Ctrl+C` aborts it. Backspace on an empty shell prompt leaves shell mode. If the agent is busy, the output is delivered after the current tool results, like a steering message. The model sees at most 2000 lines or 50 KiB of the output (the middle is cut). Shell commands you type do not go through the approval prompt; they are your commands. See [Permissions](https://signalridge.github.io/mare/en/use/permissions/) for what the policy covers. ## Working while the agent runs You can keep typing while the agent works. - `Enter` queues your message. It appears above the input until the agent takes it, then becomes a normal user message. - `Ctrl+S` steers: the text is injected into the running turn and delivered after the current tool calls finish. - `Alt+Enter` queues the message as a follow-up, the same as `Enter` while busy. - With an empty input, `Up` selects a queued message; `Up` and `Down` move between them, `Enter` loads the selected one into the input to edit it, `Delete` removes it and `Esc` leaves the selection. - `Enter` on an empty input while messages are queued opens a menu: steer now, interrupt and send, or keep queued. - `Esc` interrupts the turn. `Esc` twice on an idle, empty input opens the `/undo` picker. Pressing `Esc` while a `!cmd` runs aborts only that command. `/btw <question>` asks a side question that is answered in a widget above the editor and not added to the conversation. ## Transcript view `Ctrl+T` opens the full transcript in an overlay with tool output and thinking expanded. Keys follow `less` and Vim: | Key | Action | | --- | --- | | `j` / `Down`, `k` / `Up` | Scroll a line. | | `Space`, `f`, `PageDown`; `b`, `PageUp` | Scroll a page. | | `g` / `Home`, `G` / `End` | Top / bottom. | | `/`, `n`, `N` | Search, next match, previous match. | | `y` | Copy the message at the reading position. | | `q`, `Ctrl+T` | Close. | | `Esc`, `Ctrl+C` | Clear the search, then close. | Output already written to the scrollback cannot be redrawn, so `Ctrl+O` on an old tool call opens it in the transcript view, scrolled to that call. `Ctrl+O` while a call is still live switches all later output between compact and expanded. ## Images `Ctrl+V` (`Alt+V` on Windows) attaches an image from the clipboard to the next message. On terminals with an image protocol (Kitty, iTerm2, sixel) pasted images and images returned by tools are drawn inline; elsewhere the transcript shows `[image]`. Disable inline drawing or change the size with the `images` plugin options `user`, `read`, `tools`, `max_rows` and `max_cols`. ## Status line The bar under the input shows the permission mode, model and effort, a context gauge, the working directory, the git branch and its pull request (through `gh`), changed files, cost and quota. `/statusline` toggles segments and saves the choice in `state.json`. To run your own command instead, give it a JSON object on stdin and show its first output line: ```lua mare.plugin("statusline", { command = "~/bin/sl" }) ``` See [UI](https://signalridge.github.io/mare/en/configure/ui/) for layouts and themes. ## Notifications When a turn that took at least five seconds finishes, or mare is waiting for you (a question or an approval), it sends a terminal notification (OSC 9, 777 or 99, or a bell) while the terminal is unfocused. Tune it with the `notify` plugin: ```lua mare.plugin("notify", { min_turn_ms = 10000, only_unfocused = true }) -- or run a program with a JSON event on stdin: mare.plugin("notify", { cmd = { "notify-send-mare" } }) ``` `cmd` also runs in headless and RPC modes. Set `enabled = false` to turn the plugin off. ================================================================================ Title: Usage and compaction Section: Use mare URL: https://signalridge.github.io/mare/en/use/usage-and-compaction/ Markdown: https://signalridge.github.io/mare/raw/en/use/usage-and-compaction.md Source: docs/en/use/usage-and-compaction.md ================================================================================ # Usage and compaction mare tracks per-session token counts, cost, and provider quota windows (`usage`), compacts long histories in four stages before hitting context limits (`compact`), and records startup and frame timings (`profile`). ## Token usage and cost (`/usage`) The `usage` plugin counts `input`, `output`, `cache_read`, `cache_write`, and `cache_write_1h` tokens across the active session, including off-thread requests such as compaction summaries and `/side` / `/btw` queries. Run `/usage` (alias `/cost`) inside a session to see: - Request count (including how many were side requests outside the main conversation). - Input, output, cache read, and cache write token totals. - Estimated dollar cost using provider metadata or per-model `cost` overrides in `mare.setup { models = ... }` (subscription requests such as ChatGPT OAuth show as `subscription, not billed`). - Latest provider quota windows (`5h`, `weekly`, credits, and reset countdowns) reported via response headers. Totals belong to the session. Starting a new session resets counters to zero, and resuming or forking a session recounts usage from the saved JSONL entries. ## Staged compaction (`/compact`) The `compact` plugin keeps conversations inside the model's context window while leaving the original history intact in the session JSONL file. ### When automatic compaction runs Before each model request, mare computes the trigger threshold by kind in precedence order: `tokens` (`model_thresholds.<ref>.tokens` else `threshold_tokens`), then `percent` (`model_thresholds.<ref>.percent` else `threshold_percent`), then `ratio` (`model_thresholds.<ref>.ratio` else `threshold_ratio`). Within each kind, a per-model entry wins over the global option, while a global higher-precedence kind (such as `threshold_tokens`) still takes precedence over a per-model `percent` or `ratio`. The result is always capped at the request's pressure budget: `min(configured_threshold, context_window - max_output - headroom_tokens)` Defaults are `threshold_ratio = 0.8` and `headroom_tokens = 32768`. The status line warns when usage exceeds 90% of the threshold. You can also compact manually at any time: ```text /compact /compact preserve the database schema decisions and failing test names ``` ### The four stages Compaction walks `stages` in order (`{ "prune", "offload", "remote", "local" }`) and re-measures after each stage. Stopping behavior depends on why compaction ran: - **Automatic compaction** stops as soon as estimated usage drops to or below the threshold; if usage is still above the threshold after an earlier stage (including a summary stage), it continues walking `stages` until the threshold is met or the list ends. - **Manual `/compact`** continues past `prune` and `offload` even if usage is below the threshold, and stops once a summary stage (`remote` or `local`) succeeds. - **Overflow recovery** (after a provider rejects a request as too large, or on silent overflow) can bypass `prune_min_saving_tokens` and walks stages until a summary stage succeeds or the list ends. If compaction shrinks the context, the agent retries the request, up to `max_overflow_compactions` consecutive rounds (default `3` on the `agent` plugin) before stopping with an error. Stage details: 1. **`prune`**: Trims old tool outputs longer than `prune_tool_result_chars` (8192 chars) to head (4096) and tail (1024), leaving the most recent `prune_protect_tokens` (40,000) untouched. In automatic runs, it applies only when it saves at least `prune_min_saving_tokens` (20,000); overflow recovery may bypass that floor. 2. **`offload`**: Moves older inline images to attachment files referenced by path, keeping the newest `offload_keep_images` (2) inline. 3. **`remote`**: Uses provider-side compaction (such as OpenAI `/responses/compact`) when supported by the provider. 4. **`local`**: Calls the model (or a cheaper `summary_model`) to write a structured summary, keeping the most recent `keep_recent_tokens` (20,000) and up to `recent_user_tokens` (20,000) of older user messages verbatim. Non-converging summaries that fail to shrink context are rejected before saving. ### Failures, backoff, and `stalled` Any single automatic compaction failure sets an exponential backoff (`failure_backoff_ms` doubling up to `failure_backoff_max_ms`) before automatic compaction retries. If local summary candidates are exhausted during automatic compaction and the context is still above the threshold, compaction marks the session `stalled` and stops the current run with a breakdown of system/summary/kept tokens, advising `/new`, a larger-window model, or trimming instructions. ### Configuration options ```lua mare.plugin("compact", { auto = true, threshold_percent = 75, -- or threshold_tokens = 150000 summary_model = "opencode-go/glm-5.3-flash", keep_recent_tokens = 20000, stages = { "prune", "offload", "remote", "local" }, model_thresholds = { ["openai/gpt-6.1-terra"] = { percent = 80, headroom_tokens = 32768 }, }, }) ``` Run `/context` (or `/context all`) to inspect how many tokens the system prompt, tools, skills, instruction files, and messages consume right now. ## Startup and runtime profiling (`/profile`) The `profile` plugin records startup stage timings, individual plugin `apply` times, slow UI frames (> 16 ms), slow Lua callbacks (`slow_callback_ms`, `slow_callback_record_ms`), and mid-session changes to the tool definition list (which invalidate provider prompt caches). - Run `/profile` inside a session to open the timing overlay. - From the shell, pass `mare --profile-startup` to print startup timings and exit, or `mare --startuptime <file>` to write a startup log. ## Related - [Sessions](https://signalridge.github.io/mare/en/use/sessions/) for JSONL compaction records and `/tree` - [Context and instructions](https://signalridge.github.io/mare/en/use/context/) for what stays outside compaction - [Models and providers](https://signalridge.github.io/mare/en/use/models/#per-model-overrides) for setting `context_window` and `cost` ================================================================================ Title: Local WebSocket and HTTP listener Section: Use mare URL: https://signalridge.github.io/mare/en/use/web/ Markdown: https://signalridge.github.io/mare/raw/en/use/web.md Source: docs/en/use/web.md ================================================================================ # Local WebSocket and HTTP listener mare includes an authenticated host HTTP/WebSocket listener (`--web` / `webserver`) that exposes mare RPC protocol 3.0 (JSON-RPC 2.0 envelope) over WebSocket, plugin HTTP routes, and declarative static web assets (`web = { dir }`). It does not bundle a standalone frontend app by itself; plugins or external clients supply the UI over those endpoints. ## Starting the listener The host listener runs only in RPC mode. Running plain `mare` opens the interactive TUI and does not start the web listener, even when `webserver.enabled = true` is set in `init.lua`. Start the listener with `--web` or `--web-listen` (which select RPC mode), or combine `webserver.enabled = true` with `mare --rpc`: ```sh mare --web # binds 127.0.0.1:0 (OS-assigned ephemeral port) mare --web-listen 127.0.0.1:7432 # binds an explicit HOST:PORT mare --rpc # also starts the listener when webserver.enabled = true ``` ```lua -- ~/.config/mare/init.lua (takes effect under `mare --rpc`) mare.setup { webserver = { enabled = true, host = "127.0.0.1", port = 7432, }, } ``` When the listener starts, mare prints the listening URL, the `/readyz` probe URL, the WebSocket RPC URL (`ws://.../rpc` or `wss://.../rpc`), and the host token file path — never the raw token or a `?token=` URL. To print the authenticated login link for the running listener, run: ```sh mare web url ``` Opening that `?token=...` URL in a browser exchanges it for a session cookie and redirects to remove `?token=` from the address bar, while the host token itself stays reusable until rotated. ## Built-in endpoints | Path | Auth required | Purpose | |---|---|---| | `/readyz`, `/healthz` | No | Health check: `GET` returns `{"status":"ready"}`, `HEAD` returns status `200` with an empty body | | `/rpc`, `/` (WebSocket upgrade) | Yes | Bidirectional mare RPC protocol 3.0 stream using JSON-RPC 2.0 envelopes (`one JSON object per text frame`; binary frames close with `1003`). Closing or dropping the socket cancels pending callbacks and releases connection-owned subscriptions and registrations | | Plugin routes (`webserver.register_route`) | Yes | Dynamic HTTP handlers registered by Lua plugins or RPC (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `ANY`; max 256 routes) | | Static assets (`web = { dir }`) | Yes | Static files mounted by plugins or `webserver.register_assets` (max 64 mounts, 32 MiB max per file) | Plugin routes cannot override `/readyz`, `/healthz`, or `/rpc`. ## Authentication and token rotation Every request other than `/readyz` and `/healthz` requires authentication: 1. **Host token**: By default, mare generates a 32-byte OS-CSPRNG token stored in `~/.local/state/mare/host/token` (`0600` on Unix, restricted ACL on Windows). You can also set a static `webserver.token` string in `init.lua`; `webserver.token = false` is refused. 2. **Browser cookie exchange**: Opening `GET <url>/?token=<token>` sets an `HttpOnly; SameSite=Strict` session cookie (with `Secure` when TLS is active) and redirects (`303`) to strip `?token=` from the browser URL. This hides the token from the address bar; it does not make the token single-use. 3. **API / WebSocket clients**: Pass `Authorization: Bearer <token>`, `X-Mare-Token: <token>`, the session cookie, or `?token=<token>` on WebSocket upgrade. 4. **Lockout**: Five consecutive failed auth attempts from an IP trigger a 30-second lockout. Rotate the runtime host token file from the shell: ```sh mare token rotate ``` `mare token rotate` updates `~/.local/state/mare/host/token` and invalidates the previous file token immediately. Active WebSocket connections authenticated with that file token close with WebSocket close code `4001` on their next revocation check. Listeners configured with a static `webserver.token` string continue using that string and are unaffected by file rotation. ### Startup and rotation check (`fs_host_protect`) When using the default runtime token file, both listener startup and `mare token rotate` verify that the active sandbox backend can hide the token file from sandboxed commands (`fs_host_protect`). If the backend cannot protect it (for example on Linux without `bubblewrap`, or Windows without enhanced sandbox setup), startup fails with `SANDBOX_INSUFFICIENT` before creating the token file or starting the listener. To resolve that refusal, install `bwrap` (Linux) or run `mare sandbox setup` (Windows), switch to a static token if appropriate, or explicitly accept the missing protection: ```lua mare.setup { webserver = { accept_partial = { "fs_host_protect" } }, } ``` ```sh mare token rotate --accept-partial fs_host_protect ``` ## Host, Origin, and TLS checks `Host` and `Origin` headers are checked before authentication: - No wildcard binds: `0.0.0.0`, `[::]`, `::ffff:0.0.0.0`, `*`, and unspecified addresses are refused even with TLS. Bind a loopback IP (`127.0.0.1`, `[::1]`) or one concrete interface IP. - Non-loopback TLS / plain HTTP: Non-loopback binds require `tls_cert` and `tls_key` unless you bind one concrete IPv4/IPv6 literal (IPv6 may include `%zone`; hostnames are rejected) with `plain_http = true`. `localhost` uses the loopback path. For `%zone` IPv6 addresses, `mare web url` cannot emit a browser `?token=` URL; bind a non-link-local IP or authenticate via headers. - `Host` check: Loopback binds accept loopback `Host` headers. Concrete non-loopback binds trust their bound IP and port automatically; list reverse-proxied or custom hostnames in `trusted_hosts`. - `Origin` check: `Sec-Fetch-Site: cross-site` returns `403` before `allowed_origins` is checked. Other cross-origin browser requests require an entry in `allowed_origins`. - Local admin vs `remote_admin = false`: Local admin WebSocket rights require all three to be loopback: TCP peer IP, `Host` header, and listener bind address. Connecting from localhost to a non-loopback bind keeps `remote_admin = false`. While `remote_admin = false`, remote owners cannot call admin methods (`options.set`, `services.register`, `workspace.set_trust`, `subagent.register_type`, `hooks.subscribe`), cannot claim responder leases (`capabilities.approvals` / `elicitation` / `ui` or `ui.attach { responder: true }`), cannot call `session.load { path }`, and have restored presets, sandbox modes, and extra directories capped to the host ceiling. - Same-host reverse proxy: Because mare ignores forwarded headers (`X-Forwarded-For`, `Forwarded`), a reverse proxy on the same host forwarding remote traffic to `127.0.0.1:<port>` with a loopback `Host` header satisfies all three loopback checks and grants remote callers local admin rights. Reach a loopback listener over SSH tunnel / Tailscale / WireGuard, or bind a concrete non-loopback IP with TLS and `remote_admin = false`. ### Containers and public deployment - **Containers**: Wildcard binds (`0.0.0.0` / `[::]`) are refused inside containers as well. Pass one concrete container interface IP literal via `--web-listen` (or `webserver.host`) together with TLS or `plain_http = true`: ```sh mare --web-listen "$(hostname -i | cut -d' ' -f1):7432" --set webserver.plain_http=true ``` - **Public deployment**: Do not expose the listener directly to the public internet. Keep mare bound to loopback (`127.0.0.1`) or a private interface and reach it through an SSH tunnel (for example `ssh -L 7432:127.0.0.1:7432 user@host`) or a private mesh network (such as Tailscale or WireGuard), or place TLS in front of a concrete interface bind with explicit `trusted_hosts` and `allowed_origins`. ```lua mare.setup { webserver = { enabled = true, host = "192.168.1.20", port = 8443, tls_cert = "/etc/mare/cert.pem", tls_key = "/etc/mare/key.pem", trusted_hosts = { "mare.internal:8443" }, allowed_origins = { "https://mare.internal:8443" }, remote_admin = false, }, } ``` ## Serving plugin assets and routes Plugins can mount static directories declaratively on their plugin definition table or register handlers through the `webserver` service: ```lua return { name = "my-panel", web = { dir = "dist", prefix = "/panel", index = "index.html", fallback = "index.html" }, inject = { "webserver" }, apply = function(ctx) ctx.webserver:register_route("/api/ping", { method = "GET", handle = function() return { status = 200, headers = { ["content-type"] = "application/json" }, body = '{"ok":true}' } end, }) end, } ``` Active mounts and routes stay registered across the `HostManager` and are cleaned up automatically when the owning plugin or session disposes. ## Related - [mare RPC protocol 3.0](https://signalridge.github.io/mare/en/integrate/rpc/) for the protocol spoken over `/rpc` - [Options](https://signalridge.github.io/mare/en/configure/options/) for every `webserver` field and default - [Plugins](https://signalridge.github.io/mare/en/extend/plugins/) for plugin lifecycle and `web` definitions ================================================================================ Title: Configuration files Section: Configure URL: https://signalridge.github.io/mare/en/configure/files/ Markdown: https://signalridge.github.io/mare/raw/en/configure/files.md Source: docs/en/configure/files.md ================================================================================ # Configuration files Configure mare with Lua: where init.lua lives, how configuration layers combine, splitting a config into modules, reloading, and what happens on errors. ## Where configuration lives | Path | Purpose | |---|---| | `~/.config/mare/init.lua` | Your configuration. Created by `mare init`. | | `~/.config/mare/lua/` | Modules you load with `require` from `init.lua`. | | `~/.config/mare/plugins/` | Your own plugins. See [Plugins](https://signalridge.github.io/mare/en/extend/plugins/). | | `<project>/.mare/init.lua` | Project configuration in the project resource root (nearest `.mare/` or `.mcp.json`, up to the git root). Runs only in a trusted project. | | `<project>/.mare/lua/`, `<project>/.mare/plugins/` | Project modules and plugins. | | `~/.local/state/mare/state.json` | Choices made at runtime (`/model`, `/effort`, `/theme`, `/config` edits). Never edit it by hand. | | `~/.config/mare/mare-lock.json` | Package lock file. See [Packages](https://signalridge.github.io/mare/en/configure/packages/). | `$XDG_CONFIG_HOME` and `$XDG_STATE_HOME` replace `~/.config` and `~/.local/state` when they are set. `MARE_HOME=<dir>` moves everything under `<dir>/config`, `<dir>/state`, `<dir>/data` and `<dir>/cache`, which is useful for a throwaway setup. A project is trusted when you answered yes to the trust prompt, ran `mare trust` in it, or passed `--trust`. `mare trust --revoke` undoes the first two. `--no-trust` ignores the project for one run. ## Layer order Every option can come from six layers. A later layer wins over an earlier one. | # | Layer | Example | |---|---|---| | 1 | Defaults | The value listed in [Options](https://signalridge.github.io/mare/en/configure/options/). | | 2 | `state.json` | Saved by `/model`, `/effort`, `/theme`. | | 3 | User `init.lua` | `mare.setup { model = "..." }` | | 4 | Project `.mare/init.lua` | Same API, trusted projects only. | | 5 | Environment | `MARE_BORDER=single` | | 6 | Command line | `--set border=single`, `-m`, `-e` | Two details matter in practice: - `state.json` only fills top-level options that `init.lua` did not set. If `init.lua` sets `models = {...}`, the saved `models` is ignored as a whole. - Environment values replace the whole option. `--set` values are merged into it, so `--set plugins.tools.edit_mode=replace` changes one key and keeps the rest. ## A first init.lua `mare init` writes a commented starting point and a `.luarc.json`. It never overwrites an existing `init.lua`. ```sh mare init ``` ```lua -- ~/.config/mare/init.lua mare.setup { model = "openai/gpt-6.1-terra", border = "single", } mare.plugin("tools", { bash_timeout_ms = 120000 }) ``` `mare.setup` takes core options (`effort` is invocation-only via `--effort` or `MARE_EFFORT`, so a global `effort` in `init.lua` is ignored). Tables merge recursively with what is already set; lists and plain values replace it. The [Options](https://signalridge.github.io/mare/en/configure/options/) page lists every core option with its type and default. ## Plugin options `mare.plugin(name, opts)` overrides the defaults of one plugin. It uses the same merge rule as `mare.setup`. ```lua mare.plugin("statusline", { cwd_width = 32, changed_files = false }) mare.plugin("update-check", { enabled = false }) ``` `enabled = false` turns a plugin off. An unknown plugin name or option key produces a warning with a "did you mean" hint. The same values can be given on the command line: ```sh mare --set plugins.tools.edit_mode=replace ``` ## Reading and writing options at runtime `mare.o` reads an option (falling back to its default) and writes it. In `init.lua` a write is the same as `mare.setup`, except that a table is replaced, not merged. After startup, for example from `/lua`, a write takes effect immediately and emits the `option/changed` event. ```lua mare.o.border = "double" mare.o.plugins.url_format = "https://git.example.com/%s.git" -- dotted write into a table option local current = mare.o.model -- read; falls back to the default ``` ## Modules and require If `~/.config/mare/lua/` exists, `require` in `init.lua` loads from it. A name `a.b` resolves to `lua/a/b.lua` or `lua/a/b/init.lua`. Module names may contain letters, digits, `_` and `-`. A module sees the same `mare` API as `init.lua`. ```lua -- ~/.config/mare/init.lua require("keys") require("looks") ``` ```lua -- ~/.config/mare/lua/keys.lua mare.keymap.set("editor", "<M-g>", "transcript", { desc = "open the transcript" }) ``` In a project, `.mare/lua/` is searched first, then the user directory, then the standard library. A module that requires itself, directly or through others, is an error. Each evaluation of the configuration starts with an empty module cache, so `/reload config` runs your modules again. ## Inspect the result `/config` lists every option with its value and where it came from: `default`, `state.json`, a layer with file and line, `env MARE_<NAME>`, or `cli`. `/config border` filters by name. Plugin options you set appear in a second list, and configuration warnings at the end. In the full overlay, Enter edits a string, number or boolean option; the new value applies now and is saved to `state.json`, but a value set in `init.lua` still wins on the next start. `/settings` is an alias. ## Reload | Command | Effect | |---|---| | `/reload config` | Runs `init.lua` and the project `init.lua` again. Reloads only plugins whose `plugins.<name>` options changed (and plugins that depend on them) and notifies changed core options. | | `/reload` | Everything above, plus newly declared packages are installed, plugins of new packages start, plugins of removed packages stop, and every other plugin reloads. | | `/reload <plugin>` | Reloads one plugin. | `--set` values stay in force across a reload. A reload is refused while a model request is running or another reload is in progress; run it again afterwards. Package changes need the full `/reload`, and `watchdog_ms` is read only at startup. A reload that fails to evaluate leaves the old configuration in place. These registrations are restored to what they were before the attempt: options and their sources, key bindings from `init.lua`, UI components registered by the config, entries added by plugin config functions such as `mare.tool.command`, and `mare.on` subscriptions. What is not undone is anything else your Lua did while it ran: files written, commands started, global variables set. Keep `init.lua` free of side effects. ## When init.lua fails An error in `init.lua` does not stop mare from starting. The part of the file before the error ran; the rest did not. - In the TUI a dialog names the file, the line and the first line of the error. You can open the file in your editor (`editor` option, else `$VISUAL` / `$EDITOR`), exit, or continue. If you continue, every model request is blocked until the file is fixed and `/reload` succeeds. The status line shows `config error · /reload`. - With `-p`, `--json` or `--rpc` there is no dialog: mare prints the error and exits with code 2. Mistakes that are not errors, such as an unknown option name or a value of the wrong type, are warnings. They appear in `/config`, and in headless and RPC modes on stderr as `mare: config warning: ...`. With `--strict-config`, those two modes exit with code 2 instead. ```sh mare -p --strict-config "summarize README.md" ``` To start without any of your configuration, use `--clean`. It skips `init.lua`, project config, user and project plugins, packages and `state.json`, so only built-in plugins and command-line values remain. ## Editor completion `mare init` also writes `~/.config/mare/.luarc.json`, which points LuaLS at the Lua type definitions for the `mare` API and at the type files shipped by installed packages. The definitions are copied to the runtime directory when the mare version changes; `mare runtime` prints it (`~/.local/share/mare/runtime`, definitions in `types/`). The built-in plugin sources are there too, read-only, for reading or copying into `~/.config/mare/plugins/`. If you edit `.luarc.json`, mare stops rewriting it. ## Sensitive values Do not write API keys into `init.lua`. `mare login` stores credentials in `~/.config/mare/auth.json`. For a provider, `api_key` accepts an environment variable name or a command that prints the key: ```lua mare.provider("openai", { base_url = "https://proxy.example.com/v1", api_key = { cmd = { "pass", "show", "proxy/openai" }, refresh_interval_ms = 3600000 }, }) ``` `/config` and the RPC `options.get` method hide values whose key looks like a secret (`api_key`, `token`, `secret`, `password`, `credential`, `authorization`, `cookie`, `headers`, `query`, `env`) and URLs that carry a query string or user name. Mark your own plugin options the same way: ```lua mare.config_sensitive("plugins.myplugin.private_value") ``` This only affects what mare displays. It does not encrypt the file. ================================================================================ Title: Hooks, status line, and notifications Section: Configure URL: https://signalridge.github.io/mare/en/configure/hooks/ Markdown: https://signalridge.github.io/mare/raw/en/configure/hooks.md Source: docs/en/configure/hooks.md ================================================================================ # Hooks, status line, and notifications mare has no built-in shell-command hook runner in core; instead, hooks are Lua listeners (`mare.on`, `ctx:on`, `mare.policy.voter`, `ctx.policy:rewriter`) or external programs invoked by plugins such as `statusline`, `notify`, or community hook packages. ## Lifecycle hooks in `init.lua` and plugins Subscribe to kernel events in `~/.config/mare/init.lua` with `mare.on` or vote at decision points with `mare.policy.voter`: ```lua -- ~/.config/mare/init.lua mare.on("turn/started", function(ev) mare.log("info", "turn started: " .. tostring(ev.turn_id)) end) mare.policy.voter("tool/before", function(call) if call.name == "bash" and (call.arguments.command or ""):find("rm%s+%-rf%s+/%s*$") then return { decision = "deny", reason = "refusing rm -rf /" } end end) ``` For full plugin-level control (`ctx:on`, `ctx.policy:rewriter`, `ctx.bus:waterfall`), see [Services and events](https://signalridge.github.io/mare/en/extend/services-and-events/). ### Key lifecycle and policy hook points | Event / Point | Kind | Common use | |---|---|---| | `app/ready`, `app/shutdown` | Notify | Run setup after UI/plugins start or clean up before exit | | `session/started`, `session/loaded`, `session/changed` | Notify | React when sessions open or switch | | `input/submit`, `input/transform` | Notify / Waterfall | Inspect or rewrite user input before a turn starts | | `request/prepare`, `request/ready`, `request/build` | Checked / Policy / Waterfall checked | Block or customize outbound model requests | | `context/system`, `context/transform` | Waterfall | Append dynamic context or filter messages | | `tool/rewrite`, `tool/before`, `tool/approval`, `tool/after` | Rewrite / Policy / Waterfall | Sanitize arguments, block dangerous calls, or transform tool outputs | | `turn/started`, `turn/completed`, `agent/settled` | Notify | Track turn start/finish (`turn/completed` runs first; `agent/settled` fires after all its listeners return, carrying `busy`) | | `option/changed`, `reload/completed` | Notify | React to runtime option edits and reloads | ### Error behavior Error handling depends on the dispatch mode: - **Ordinary notifications (`emit`)**: if a listener throws during a turn, mare logs the traceback and prints one short inline line below the turn (`plugin <name> hook <event> failed: ...`) without stopping other listeners or disabling the plugin. - **Checked hooks (`emit_checked`, `waterfall_checked`)**: errors propagate to the caller. An error in `request/prepare` or `request/build` aborts the outbound model request before provider I/O. - **Policy gates**: if a `request/ready` voter denies a prompt, mare does not send it and returns the text to the input box. A `tool/before` or `tool/approval` voter that errors or times out (`policy_timeout_ms`, default 30s) fails closed as `deny`. ### Shell-hook packages (`mare-plugins`) If you want declarative JSON/shell hooks compatible with Claude Code and Codex hook event sets (`PreToolUse`, `PostToolUse`, `UserPromptSubmit`, `SessionStart`, and similar), install a hook package from `signalridge/mare-plugins` via `/plugins` or `mare.plugins.add` rather than reimplementing process runners in `init.lua`. ## Custom status line (`statusline`) The `statusline` plugin renders the bar below the input editor (`mode`, `model`, `effort`, `context`, `cwd`, `branch`, `pr`, `changes`, `cost`, `quota`). ### Built-in looks and toggles Run `/statusline` inside a session to toggle individual segments (saved in `state.json`), or configure layouts in `init.lua`: ```lua mare.plugin("statusline", { layout = "combined", -- "combined" | "classic" | "codex" | "kimi" | custom look table hidden = { "pr", "cost" }, cwd_width = 24, gauge_width = 6, changed_files = true, pr = true, layout_opts = { sep = "space", flash = 0 }, }) ``` ### External status-line command Set `command` to run your own script after startup, model changes, and each completed turn. It receives a JSON object on stdin (`session_id`, `transcript_path`, `cwd`, `width`, `model`, `context`, `cost`) and mare shows its first stdout line: ```lua mare.plugin("statusline", { command = "~/bin/mare-statusline.sh", command_timeout_ms = 1000, command_replaces = false, -- set true to hide built-in segments }) ``` Plugins can also register status segments in Lua with `ctx.ui:status(id, { align = "right", order = 20, render = ... })`. ## Notifications (`notify`) The `notify` plugin sends terminal notifications (OSC 9, OSC 777, Kitty OSC 99, tmux/screen passthrough, or bell, plus native desktop notifications on Windows outside Windows Terminal) when a turn exceeding `min_turn_ms` (default 5000 ms) finishes or when mare waits for user input. ```lua mare.plugin("notify", { on_done = true, on_input = true, only_unfocused = true, min_turn_ms = 5000, protocol = "auto", -- "auto" | "bel" | "native" bell = false, dedupe_ms = 10000, }) ``` ### External notification command (`notify.cmd`) To trigger desktop notifications, webhooks, or sounds in any mode (TUI, headless, or RPC), set `cmd`. mare passes one JSON object on stdin (`type` as `"agent-turn-complete"` or `"input-required"`, `session-id`, `turn-id`, `cwd`, and `last-assistant-message` or `message`): ```lua mare.plugin("notify", { cmd = { "notify-send-mare" }, cmd_timeout_ms = 10000, }) ``` ## Related - [Services and events](https://signalridge.github.io/mare/en/extend/services-and-events/) for writing Lua event and policy hooks - [Event reference](https://signalridge.github.io/mare/en/reference/events/) for generated public protocol event schemas - [Appearance](https://signalridge.github.io/mare/en/configure/ui/) for themes, borders, and UI component overrides ================================================================================ Title: Key bindings Section: Configure URL: https://signalridge.github.io/mare/en/configure/keymaps/ Markdown: https://signalridge.github.io/mare/raw/en/configure/keymaps.md Source: docs/en/configure/keymaps.md ================================================================================ # Key bindings Bind and remove keys with mare.keymap: key notation, contexts and conditions, the keys shorthand, Lua actions and the default bindings. ## Bind a key `mare.keymap.set(context, key, action, opts)` binds `key` in `context` to an action. The action is the name of a built-in action, the name of a Lua action, or a Lua function. ```lua -- ~/.config/mare/init.lua mare.keymap.set("editor", "<C-o>", "transcript", { desc = "open the transcript" }) mare.keymap.set("editor", "<M-n>", function() ui.notify("hello from a key") end, { desc = "say hello" }) ``` `opts` accepts: | Field | Meaning | |---|---| | `desc` | Text shown in `/hotkeys` and the `?` help. | | `unique` | When `true`, raise an error if the key is already bound in that context. Ignored for `false`. | | `when` | A predicate or a list of predicates. The binding takes the key only while all hold. An unbinding (`false`) cannot have a condition. | `set` returns a handle. `handle:remove()` or `mare.keymap.remove(handle)` undoes that binding. To register several bindings atomically in one host update, use `mare.keymap.set_many(specs, opts?)`. Each entry is either `{ context, key_or_keys, action, opts? }` or `{ context?, key?, keys?, action, desc?, unique?, priority?, when? }`; `opts` supplies defaults shared across the batch. Validation runs before any binding is applied, and the returned handle uses the same `handle:remove()` / `mare.keymap.remove(handle)` interface to remove the whole batch. ```lua local batch = mare.keymap.set_many({ { "editor", "<F7>", "redraw" }, { "editor", "<F8>", "suspend", { when = "editor_empty" } }, { "text", { "<M-b>", "<M-Left>" }, "text.word_left" }, }) ``` Bindings stack per key across four layers (`project > user > plugin > default`), regardless of load order: built-in defaults sit at `default`, third-party plugins at `plugin`, `~/.config/mare/init.lua` at `user`, and trusted `.mare/init.lua` at `project`. Within a layer, any mask (`false`) outranks every non-mask regardless of `priority` (for example, a priority-`0` mask beats a priority-`10` action in either registration order); non-mask bindings order by `priority` (default `0`) and then registration order. Removing a binding brings the one below back, and the editor's own handling sits at the bottom. ## Key notation These spellings are all the same key, and `<C-t>`, `C-t`, `Ctrl+T` and `ctrl+t` normalise to `ctrl+t`: | You write | Meaning | |---|---| | `<C-t>`, `ctrl+t`, `C-t` | Ctrl+T | | `<M-CR>`, `alt+enter` | Alt+Enter | | `<S-Tab>`, `shift+tab` | Shift+Tab | | `<Esc>`, `<Space>`, `<Up>`, `<F5>` | Escape, Space, Up, F5 | Modifiers: `ctrl` (`c`, `control`), `alt` (`m`, `meta`, `opt`, `option`), `shift` (`s`), `super` (`cmd`, `command`, `win`). Named keys: `esc`, `enter` (`return`, `cr`), `tab`, `backspace` (`bs`), `delete` (`del`), `insert`, `up`, `down`, `left`, `right`, `home`, `end`, `pageup` (`pgup`), `pagedown` (`pgdn`), `space`, `f1` to `f12`. A single character is itself. A key sequence is several keys in one string: `"<C-x>g"`, `"<C-x> g"` and `"ctrl+x g"` are the same. After the first key mare shows the continuations. Sequences work in `editor`, `transcript`, and their subcontexts. ```lua mare.keymap.set("editor", "<C-x>t", "transcript", { desc = "transcript (chord)" }) ``` Which keys reach mare at all depends on your terminal. `mare doctor` explains known conflicts such as Alt+Enter in Windows Terminal, and the `key_conflicts` and `terminal_caps` options in [Options](https://signalridge.github.io/mare/en/configure/options/) extend what mare knows. ## Contexts Keys are resolved along a context lookup chain determined by focus and state: | Context | Lookup chain | Where it applies | |---|---|---| | `global` | `global` | Shared non-modal fallback for `editor` and `transcript`. | | `text` | `text` | Line-editing context shared by text inputs (`editor`, `input`). | | `editor` | `editor` → `text` → `global` | The prompt input. | | `editor.completion`, `editor.queue`, `editor.history`, `editor.selection` | subcontext → `editor` → `text` → `global` | Active while completion is open, queue selection/editing is active, history is being browsed, or mouse selection is active. | | `input` | `input` → `text` | The `mare.ui.input` text dialog (falls back to `text` for line-editing keys). | | `transcript` | `transcript` → `global` | The transcript overlay (`Ctrl+T`) and views that plugins open, such as a sub-agent's view. | | `transcript.search` | `transcript.search` → `transcript` → `global` | Active while typing a `/` search in the transcript (printable keys append to the query before `transcript` and `global`). | | `select` | `select` | Selection dialogs (`mare.ui.select`); sequences are allowed. | | `select.vim` | `select.vim` → `select` | Active in a selection dialog opened with `vim = true` while not searching. | | `select.search` | `select.search` → `select` | Active while typing a `/` search filter in a selection dialog (printable keys append to the filter before `select`). | | `confirm` | `confirm` | Confirmation dialogs (`mare.ui.confirm`). | | `help` | `help` | Key help modals (`?`). | | `info` | `info` | Scrollable info overlays (`mare.ui.overlay`). | Printable rule: when a chain includes `text` and the key is a printable character without `Ctrl` or `Alt`, lookup stops after `text` so `global` bindings never steal typed text. `context` may also be a list: `mare.keymap.set({ "editor", "transcript" }, "<F2>", "redraw")`. Plugins can declare subcontexts with `mare.keymap.context(name, { parent })` (where `name` is `parent .. "." .. seg` with `seg` matching `^[a-z][a-z0-9_-]*$`); `handle:remove()` removes the subcontext, its descendants, and all bindings in them. Any unknown context name is an error. The install screen and startup error screen do not use the keymap. ## Reserved key `Ctrl+C` is reserved by the core and cannot be bound or unbound. It acts on the topmost focus: | Focus | Effect | |---|---| | Modal | Close it with reason `interrupted`; Esc and other ordinary dismissals give `cancelled`. | | Pending prefix or completion | Cancel the prefix or close the completion menu. | | Transcript or plugin view | Cancel a search being typed; otherwise close the view. | | Input | Copy a selection, clear a draft, interrupt work, or exit on a second press. | ## Conditions `when` lets one key do different things. The predicates are fixed; plugins cannot add more. Prefix a name with `!` to negate it. | Predicate | True when | |---|---| | `editor_empty` | The input has no text. | | `completion_open` | The completion menu is open. | | `paste_burst` | A fast run of keys is being treated as a paste. | | `working` | The agent is running. | ```lua -- F6 queues a follow-up, but only while the agent is busy mare.keymap.set("editor", "<F6>", "follow-up", { when = "working" }) -- "?" opens the key help only on an empty input mare.keymap.set("editor", "?", "keymap-help", { when = { "editor_empty", "!completion_open" } }) ``` ## Actions A string action is looked up in this order: a core action, then a named Lua action. An unregistered action passes the key to the next binding or the editor. Core actions declare the contexts they support; binding a core action in an unsupported context is an error. `mare.keymap.actions()` lists registered core and Lua actions. Core actions in the `editor` context: | Action | Does | |---|---| | `interrupt` | Close completion, or stop the running work. Twice when idle: the rewind picker. | | `quit-if-empty` | Quit when the input is empty. | | `quit` | Quit. | | `transcript` | Open the transcript overlay. | | `toggle-expand` | Switch tool output between compact and expanded. | | `steer` | Send the input into the running turn. | | `follow-up` | Queue the input to run after the current turn. | | `history-search` | Search the input history. | | `external-editor` | Edit the input in your editor. | | `paste-image` | Paste an image from the clipboard. | | `complete` | Complete `@file` or `/command`. | | `newline` | Insert a newline. | | `redraw` | Redraw the screen. | | `suspend` | Suspend mare (not on Windows). | | `select-mode` | Select text in the live area with the mouse. | | `keymap-help` | Open the searchable list of all bindings. | | `editor.submit` | Send the input (insert a newline when preceded by `\`). | In the `text` context (shared by `editor` and `input`), the line-editing actions are `text.newline`, `text.left`, `text.right`, `text.word_left`, `text.word_right`, `text.line_start`, `text.line_end`, `text.up`, `text.down`, `text.delete_back`, `text.delete_word_back`, `text.delete_forward`, `text.delete_word_forward`, `text.kill_line_start`, `text.kill_line_end`, `text.yank`, `text.yank_pop`, and `text.undo`. In the `input` context, the dialog actions are `input.accept` (confirm the dialog text) and `input.cancel` (dismiss with `cancelled`). In the `transcript` context the actions are `view.close`, `view.back`, `view.up`, `view.down`, `view.page_up`, `view.page_down`, `view.top`, `view.bottom`, `view.search`, `view.copy`, `view.next_match` and `view.prev_match`. In modal contexts the actions and their default keys (registered by `keymap-default`) are: - `select` (`select.vim` adds `k`/`j`/`g`/`<S-g>`/`l`/`h`): `select.up` (`<Up>`), `select.down` (`<Down>`), `select.page_up` (`<PageUp>`), `select.page_down` (`<PageDown>`), `select.top` (`<Home>`), `select.bottom` (`<End>`), `select.accept` (`<CR>`), `select.back` (`<Esc>`), `select.search` (`/`), `select.tab_next` (`<Tab>`, `<Right>`, `]`), `select.tab_prev` (`<S-Tab>`, `<Left>`, `[`), `select.help` (`?`), `select.preview_up`/`down`/`page_up`/`page_down`/`top`/`bottom` (`<S-Up>`/`<S-Down>`/`<S-PageUp>`/`<S-PageDown>`/`<S-Home>`/`<S-End>`), `select.body_up`/`down`/`page_up`/`page_down`/`top`/`bottom` (`<C-Up>`/`<C-Down>`/`<C-PageUp>`/`<C-PageDown>`/`<C-Home>`/`<C-End>`). - `confirm`: `confirm.yes` (`y`, `<S-y>`), `confirm.no` (`n`, `<S-n>`), `confirm.toggle` (`<Left>`, `<Right>`, `<Tab>`, `<S-Tab>`, `h`, `l`), `confirm.accept` (`<CR>`), `confirm.cancel` (`<Esc>`, `q`), `confirm.scroll_up`/`scroll_down`/`page_up`/`page_down`/`top`/`bottom` (`<Up>`/`k`, `<Down>`/`j`, `<PageUp>`, `<PageDown>`, `<Home>`, `<End>`). - `help`: `help.up` (`<Up>`), `help.down` (`<Down>`), `help.accept` (`<CR>`), `help.cancel` (`<Esc>`). - `info`: `info.up` (`<Up>`, `k`), `info.down` (`<Down>`, `j`), `info.page_up` (`<PageUp>`), `info.page_down` (`<PageDown>`, `<Space>`), `info.top` (`<Home>`), `info.bottom` (`<End>`). Plugins add more. The built-in `copy` plugin defines `copy.last` with no default key; the `agents` plugin defines `agents`, `agents.back`, `agents.prev` and `agents.next`. ```lua mare.keymap.set("editor", "<M-c>", "copy.last", { desc = "copy the last response" }) ``` ### Lua actions `mare.keymap.action(name, fn, opts)` registers a named action, so users can rebind it by name and hints can find its keys. `fn(ev)` receives `{ key, context }`. It runs at once, up to its first yield, so decide before waiting on anything. Returning exactly `false` declines: the key goes on to the binding below, then along the chain to the editor. Any other result takes the key. `opts.keys` declares default keys by context: a key string, a record such as `{ key = "<F5>", when = "working" }`, or a list of strings and records. A single record needs a string `key`; an empty table declares no keys. Removing the action also removes its default bindings. ```lua mare.keymap.action("greet", function(ev) if ev.context ~= "editor" then return false end -- decline: the key falls through ui.notify("pressed " .. ev.key) end, { desc = "show the key that ran this action" }) mare.keymap.set("editor", "<M-d>", "greet") ``` A function you pass directly to `set` behaves the same way. ## The keys shorthand `mare.setup { keys = { ... } }` binds editor keys from a table. A value of `false` or `"none"` masks bindings registered earlier at the plugin layer (such as `keymap-default` or `commands`); to mask a plugin loaded later, use `mare.keymap.set` in `init.lua`. ```lua mare.setup { keys = { ["<C-o>"] = "transcript", ["<M-p>"] = false, -- free Alt+P (the model picker's default key) }, } ``` Writing one key two ways with different actions (`"<C-o>"` and `"ctrl+o"`) is an error and neither is bound. Use `mare.keymap.set` when you need a context other than `editor`, `when`, or a function. ## Remove and inspect bindings | Call | Does | |---|---| | `mare.keymap.set(context, key, false)` | Mask bindings for the key in this context at the caller's layer and all contexts after it in the chain. Remove the returned handle to lift the mask. | | `mare.keymap.del(context, key)` | Remove the newest binding of `key` in `context` in the caller's own layer. The one below comes back. | | `mare.keymap.context(name, { parent })` | Declare a plugin subcontext under `parent`; `handle:remove()` deletes it, its descendants, and their bindings. | | `mare.keymap.remove(handle)` | Remove the binding a `set` call returned. | | `mare.keymap.list([opts])` | All reachable, unmasked bindings (multiple rows per context and key are possible, as with the two `Ctrl+R` entries below), as `{ key, context, desc, action, when }`. Supports `list({ context = "editor" })` and `list({ snapshot = true })`. | | `mare.keymap.hint(action, context)` | The keys that can trigger `action` with focus at `context` (`project > user > plugin > default`, then `priority`, then binding order). | | `mare.keymap.actions()` | Registered core and Lua actions (`{ name, desc, contexts, core, essential }`). | ```lua mare.keymap.set("editor", "<C-z>", false) -- disable suspend ``` `/hotkeys` shows the same list in the TUI. Press `?` on an empty input for a searchable list. During `/reload config` and `/reload`, config reevaluation commits staged `init.lua` bindings first and then opens the plugin keymap reload guard around plugin reloads: if `init.lua` fails to evaluate, the previous config bindings stay intact; if a later plugin reload fails or is cancelled, the plugin guard handles plugin keymaps while already-committed config bindings can remain active. If an essential action (`editor.submit`, `input.accept`, `input.cancel`) is left without any key (for example with `keymap-default` disabled or an explicit unbind), `/hotkeys` lists it under `No key` and `mare doctor` prints a warning instead of restoring a default key silently. ## Default bindings Core action defaults come from the built-in `keymap-default` plugin, and plugin actions (`review.viewer`, `agents`, `model.picker`, `model.cycle`, `effort.down`, `effort.up`, …) register their own `default`-layer keys. `mare.plugin("keymap-default", { enabled = false })` disables the core set; bindings registered by other plugins remain, and the reserved `Ctrl+C` keeps working. Rebind or disable any default key in `init.lua` with `mare.keymap.set`: ```lua mare.keymap.set("editor", "<M-o>", "model.picker") mare.keymap.set("editor", "<M-m>", false) -- unbind model.cycle mare.keymap.set("editor", "<C-y>", "review.viewer") mare.keymap.set("editor", "<M-a>", "agents", { when = "editor_empty" }) ``` <!-- BEGIN GENERATED KEYMAPS (scripts/gen_docs.py) --> | Context | Key | Action | When | Description | |---|---|---|---|---| | `editor` | `?` | `keymap-help` | `editor_empty`, `!completion_open`, `!paste_burst` | all key bindings (on an empty input) | | `editor` | `Alt+,` | `effort.down` | | lower reasoning effort (the model's levels) | | `editor` | `Alt+.` | `effort.up` | | raise reasoning effort (the model's levels) | | `editor` | `Alt+Enter` | `follow-up` | `working` | queue the input as a follow-up | | `editor` | `Alt+M` | `model.cycle` | | next favorite / recent model | | `editor` | `Alt+P` | `model.picker` | | select model (keeps the input) | | `editor` | `Alt+S` | `select-mode` | | select text in the live area with the mouse, release copies | | `editor` | `Alt+V` | `paste-image` | | paste an image from the clipboard (Windows) | | `editor` | `Ctrl+B` | `background` | | move the running command to the background | | `editor` | `Ctrl+D` | `quit-if-empty` | | exit when the input is empty | | `editor` | `Ctrl+G` | `external-editor` | | edit the input in $EDITOR | | `editor` | `Ctrl+L` | `redraw` | | redraw the screen | | `editor` | `Ctrl+O` | `toggle-expand` | | toggle compact / expanded tool output and thinking | | `editor` | `Ctrl+Q` | `follow-up` | | queue the input as a follow-up (Windows) | | `editor` | `Ctrl+R` | `history-search` | | search input history | | `editor` | `Ctrl+R` | `review.viewer` | | review changes: mare's edits per turn, or git unstaged / staged / last commit | | `editor` | `Ctrl+S` | `steer` | | send the input into the running turn | | `editor` | `Ctrl+T` | `transcript` | | expanded transcript | | `editor` | `Ctrl+V` | `paste-image` | | paste an image from the clipboard (Unix / macOS) | | `editor` | `Ctrl+Z` | `suspend` | | suspend mare (resume with fg) | | `editor` | `Enter` | `editor.submit` | | send the input | | `editor` | `Esc` | `interrupt` | | interrupt the agent · twice when idle: rewind picker (/undo) | | `editor` | `←` | `agents` | `editor_empty` | sub-agents and other sessions (/agents) | | `editor` | `Shift+Tab` | `permissions.cycle` | `!completion_open` | cycle permission mode | | `editor` | `Tab` | `complete` | | complete @file or /command | | `text` | `Alt+B` | `text.word_left` | | one word left | | `text` | `Alt+Backspace` | `text.delete_word_back` | | delete the word before the cursor | | `text` | `Alt+D` | `text.delete_word_forward` | | delete the word after the cursor | | `text` | `Alt+delete` | `text.delete_word_forward` | | delete the word after the cursor | | `text` | `Alt+Enter` | `text.newline` | | new line | | `text` | `Alt+F` | `text.word_right` | | one word right | | `text` | `Alt+←` | `text.word_left` | | one word left | | `text` | `Alt+→` | `text.word_right` | | one word right | | `text` | `Alt+Shift+Enter` | `text.newline` | | new line | | `text` | `Alt+Shift+←` | `text.select_word_left` | | extend selection one word left | | `text` | `Alt+Shift+→` | `text.select_word_right` | | extend selection one word right | | `text` | `Alt+Shift+Z` | `text.redo` | | redo the last undone edit | | `text` | `Alt+Y` | `text.yank_pop` | | cycle older deletions | | `text` | `Backspace` | `text.delete_back` | | delete the character before the cursor | | `text` | `Ctrl+_` | `text.undo` | | undo the last edit | | `text` | `Ctrl+A` | `text.line_start` | | start of line | | `text` | `Ctrl+B` | `text.left` | | one character left | | `text` | `Ctrl+Backspace` | `text.delete_word_back` | | delete the word before the cursor | | `text` | `Ctrl+D` | `text.delete_forward` | | delete the character after the cursor | | `text` | `Ctrl+delete` | `text.delete_word_forward` | | delete the word after the cursor | | `text` | `Ctrl+E` | `text.line_end` | | end of line | | `text` | `Ctrl+End` | `text.line_end` | | end of line | | `text` | `Ctrl+F` | `text.right` | | one character right | | `text` | `Ctrl+H` | `text.delete_back` | | delete the character before the cursor | | `text` | `Ctrl+Home` | `text.line_start` | | start of line | | `text` | `Ctrl+J` | `text.newline` | | new line | | `text` | `Ctrl+K` | `text.kill_line_end` | | delete to the end of the line | | `text` | `Ctrl+←` | `text.word_left` | | one word left | | `text` | `Ctrl+N` | `text.down` | | line down | | `text` | `Ctrl+P` | `text.up` | | line up | | `text` | `Ctrl+→` | `text.word_right` | | one word right | | `text` | `Ctrl+Shift+←` | `text.select_word_left` | | extend selection one word left | | `text` | `Ctrl+Shift+→` | `text.select_word_right` | | extend selection one word right | | `text` | `Ctrl+Shift+Z` | `text.redo` | | redo the last undone edit | | `text` | `Ctrl+U` | `text.kill_line_start` | | delete to the start of the line | | `text` | `Ctrl+W` | `text.delete_word_back` | | delete the word before the cursor | | `text` | `Ctrl+Y` | `text.yank` | | paste the last deletion | | `text` | `Ctrl+Z` | `text.undo` | | undo the last edit | | `text` | `delete` | `text.delete_forward` | | delete the character after the cursor | | `text` | `↓` | `text.down` | | line down | | `text` | `End` | `text.line_end` | | end of line | | `text` | `Home` | `text.line_start` | | start of line | | `text` | `←` | `text.left` | | one character left | | `text` | `→` | `text.right` | | one character right | | `text` | `Shift+Backspace` | `text.delete_back` | | delete the character before the cursor | | `text` | `Shift+delete` | `text.delete_forward` | | delete the character after the cursor | | `text` | `Shift+↓` | `text.select_down` | | extend selection one line down | | `text` | `Shift+End` | `text.select_line_end` | | extend selection to end of line | | `text` | `Shift+Enter` | `text.newline` | | new line | | `text` | `Shift+Home` | `text.select_line_start` | | extend selection to start of line | | `text` | `Shift+←` | `text.select_left` | | extend selection one character left | | `text` | `Shift+→` | `text.select_right` | | extend selection one character right | | `text` | `Shift+↑` | `text.select_up` | | extend selection one line up | | `text` | `↑` | `text.up` | | line up | | `input` | `Enter` | `input.accept` | | confirm input | | `input` | `Esc` | `input.cancel` | | cancel input | | `transcript` | `/` | `view.search` | | search | | `transcript` | `Alt+←` | `agents.prev` | | the previous sub-agent | | `transcript` | `Alt+→` | `agents.next` | | the next sub-agent | | `transcript` | `B` | `view.page_up` | | scroll up a page | | `transcript` | `Ctrl+T` | `view.close` | | close the transcript | | `transcript` | `↓` | `view.down` | | scroll down a line | | `transcript` | `End` | `view.bottom` | | go to the bottom | | `transcript` | `Esc` | `agents.back` | | back to the agents list | | `transcript` | `Esc` | `view.back` | | clear the search, else close the transcript | | `transcript` | `F` | `view.page_down` | | scroll down a page | | `transcript` | `G` | `view.top` | | go to the top | | `transcript` | `Home` | `view.top` | | go to the top | | `transcript` | `J` | `view.down` | | scroll down a line | | `transcript` | `K` | `view.up` | | scroll up a line | | `transcript` | `N` | `view.next_match` | | next search match | | `transcript` | `PageDown` | `view.page_down` | | scroll down a page | | `transcript` | `PageUp` | `view.page_up` | | scroll up a page | | `transcript` | `Q` | `view.close` | | close the transcript | | `transcript` | `Shift+G` | `view.bottom` | | go to the bottom | | `transcript` | `Shift+N` | `view.prev_match` | | previous search match | | `transcript` | `Space` | `view.page_down` | | scroll down a page | | `transcript` | `↑` | `view.up` | | scroll up a line | | `transcript` | `Y` | `view.copy` | | copy the message at the reading position | | `select` | `/` | `select.search` | | search (fuzzy) | | `select` | `?` | `select.help` | | all keys | | `select` | `[` | `select.tab_prev` | | previous tab | | `select` | `]` | `select.tab_next` | | next tab | | `select` | `Ctrl+↓` | `select.body_down` | | scroll body down | | `select` | `Ctrl+End` | `select.body_bottom` | | scroll body to bottom | | `select` | `Ctrl+Home` | `select.body_top` | | scroll body to top | | `select` | `Ctrl+P` | `select.toggle_preview` | | toggle preview | | `select` | `Ctrl+PageDown` | `select.body_page_down` | | scroll body page down | | `select` | `Ctrl+PageUp` | `select.body_page_up` | | scroll body page up | | `select` | `Ctrl+↑` | `select.body_up` | | scroll body up | | `select` | `↓` | `select.down` | | next item | | `select` | `End` | `select.bottom` | | last item | | `select` | `Enter` | `select.accept` | | choose the selected item | | `select` | `Esc` | `select.back` | | clear search / close | | `select` | `Home` | `select.top` | | first item | | `select` | `←` | `select.tab_prev` | | previous tab | | `select` | `PageDown` | `select.page_down` | | page down | | `select` | `PageUp` | `select.page_up` | | page up | | `select` | `→` | `select.tab_next` | | next tab | | `select` | `Shift+↓` | `select.preview_down` | | scroll preview down | | `select` | `Shift+End` | `select.preview_bottom` | | scroll preview to bottom | | `select` | `Shift+Home` | `select.preview_top` | | scroll preview to top | | `select` | `Shift+PageDown` | `select.preview_page_down` | | scroll preview page down | | `select` | `Shift+PageUp` | `select.preview_page_up` | | scroll preview page up | | `select` | `Shift+Tab` | `select.tab_prev` | | previous tab | | `select` | `Shift+↑` | `select.preview_up` | | scroll preview up | | `select` | `Space` | `select.toggle` | | toggle selection | | `select` | `Tab` | `select.tab_next` | | next tab | | `select` | `↑` | `select.up` | | previous item | | `select.vim` | `G` | `select.top` | | first item | | `select.vim` | `H` | `select.tab_prev` | | previous tab | | `select.vim` | `J` | `select.down` | | next item | | `select.vim` | `K` | `select.up` | | previous item | | `select.vim` | `L` | `select.tab_next` | | next tab | | `select.vim` | `Shift+G` | `select.bottom` | | last item | | `confirm` | `↓` | `confirm.scroll_down` | | scroll down | | `confirm` | `End` | `confirm.bottom` | | scroll to bottom | | `confirm` | `Enter` | `confirm.accept` | | confirm choice | | `confirm` | `Esc` | `confirm.cancel` | | cancel | | `confirm` | `H` | `confirm.toggle` | | switch choice | | `confirm` | `Home` | `confirm.top` | | scroll to top | | `confirm` | `J` | `confirm.scroll_down` | | scroll down | | `confirm` | `K` | `confirm.scroll_up` | | scroll up | | `confirm` | `L` | `confirm.toggle` | | switch choice | | `confirm` | `←` | `confirm.toggle` | | switch choice | | `confirm` | `N` | `confirm.no` | | answer no | | `confirm` | `PageDown` | `confirm.page_down` | | scroll page down | | `confirm` | `PageUp` | `confirm.page_up` | | scroll page up | | `confirm` | `Q` | `confirm.cancel` | | cancel | | `confirm` | `→` | `confirm.toggle` | | switch choice | | `confirm` | `Shift+N` | `confirm.no` | | answer no | | `confirm` | `Shift+Tab` | `confirm.toggle` | | switch choice | | `confirm` | `Shift+Y` | `confirm.yes` | | answer yes | | `confirm` | `Tab` | `confirm.toggle` | | switch choice | | `confirm` | `↑` | `confirm.scroll_up` | | scroll up | | `confirm` | `Y` | `confirm.yes` | | answer yes | | `help` | `↓` | `help.down` | | next item | | `help` | `Enter` | `help.accept` | | run selected key | | `help` | `Esc` | `help.cancel` | | close | | `help` | `↑` | `help.up` | | previous item | | `info` | `↓` | `info.down` | | scroll down | | `info` | `End` | `info.bottom` | | scroll to bottom | | `info` | `Esc` | `info.close` | | close overlay | | `info` | `Home` | `info.top` | | scroll to top | | `info` | `J` | `info.down` | | scroll down | | `info` | `K` | `info.up` | | scroll up | | `info` | `PageDown` | `info.page_down` | | scroll page down | | `info` | `PageUp` | `info.page_up` | | scroll page up | | `info` | `Space` | `info.page_down` | | scroll page down | | `info` | `↑` | `info.up` | | scroll up | <!-- END GENERATED KEYMAPS --> ================================================================================ Title: Options Section: Configure URL: https://signalridge.github.io/mare/en/configure/options/ Markdown: https://signalridge.github.io/mare/raw/en/configure/options.md Source: docs/en/configure/options.md ================================================================================ # Options Core options set with `mare.setup { ... }` in `init.lua`, `MARE_<NAME>` in the environment, or `--set name=value` on the command line. > This page is generated from the code by `scripts/gen_docs.py`. Do not edit it by hand. Plugin options are set with `mare.plugin("name", { ... })`; `/config` shows every value in a running session together with the layer and the file and line it came from. | Option | Type | Default | Description | |---|---|---|---| | `agents` | table | `{ max_active = 16, max_depth = 4 }` | root-shared subagent limits: non-negative integers max_active (all live descendant threads) and max_depth (edges from root); zero disables delegation | | `border` | string | `"rounded"` | panel/popup borders: rounded\|single\|double\|thick\|hidden | | `cache_retention` | string | `"short"` | prompt cache retention tier: none\|short\|long (default short) | | `char_widths` | table | | display width overrides { { from = 0x2600, to = 0x26FF, width = 2 }, { char = "⚡", width = 1 }, … } | | `copy` | table | | /copy: { always_full = true } skips the code-block picker and copies the whole response | | `editor` | string | | editor for Ctrl+G (default $VISUAL / $EDITOR) | | `effort` | string | | **Invocation only.** invocation-only model effort override | | `fallback_models` | list | | up to 3 models (provider/id or alias) tried in order when the current one is overloaded, missing or out of quota | | `favorite_models` | table | | models (provider/id or alias) the model-cycle key steps through; without it, the recently used models | | `flavor` | string | `"auto"` | theme flavor: auto (OSC 11 background query)\|dark\|light\|installed name | | `flavor_dark` | string | `"dark"` | flavor selected by auto on a dark or unknown terminal background | | `flavor_light` | string | `"light"` | flavor selected by auto on a light terminal background | | `icons` | string | | icon set: nerd\|unicode\|ascii (default: auto-detect) | | `images_protocol` | string | | terminal image protocol: kitty\|iterm2\|sixel\|none (default: detected) | | `key_conflicts` | table | | extra known key conflicts { { key = "ctrl+tab", terminal = "ghostty"\|"any", by = "…", fix = "…" }, … } (appended to the built-in table) | | `keys` | table | | key -> action shorthand | | `logo` | boolean or string | | startup logo on a new session: true (pixel logo) \| false \| "compact" (one line) | | `lua_memory_mb` | number | `512` | **Invocation only.** Lua VM memory limit in MiB (0 disables the limit). CLI/env only: --set lua_memory_mb=… or MARE_LUA_MEMORY_MB (the VM memory limit is applied before init.lua, so a value written in init.lua has no effect) | | `markdown` | table | | Markdown rendering: { glyphs = { bullet1 = "•", rule = "─", … }, code_line_numbers = false } | | `model` | string | | model as provider/id | | `models` | table | | per-model overrides | | `net` | table | `{ fake_ip = "off" }` | network authorization: { fake_ip = "off"\|"auto" } ("off" default; "auto" recognizes fake-IP 198.18.0.0/15 resolution shape and relaxes non-public checks for it) | | `news` | boolean | `true` | after mare or an enabled plugin is updated, show its NEWS.md once in the scrollback | | `paste_burst` | boolean | | treat a fast stream of keys as a paste (an Enter inside it inserts a newline); default on Windows only, where pastes aren't bracketed | | `peer` | boolean or table | | peer socket + registry: false disables; { name = "...", allow = { "agent.prompt", "events.subscribe", ... } } names the session and opens methods beyond the peer defaults; inbound messages always wait for the user | | `perf` | table | | cache sizes (entries) { highlight_cache = 256, markdown_cache = 128, wrap_cache = 1024, preview_cache = 256 } | | `plugins` | table | `{ allow_insecure = false, concurrency = 8, sources = { }, timeout = 120, url_format = "https://github.com/%s.git" }` | packages: { url_format = "https://github.com/%s.git" (short names), allow_insecure = false (http://, git://), timeout = 120 (seconds per git operation), concurrency = 8 (parallel fetches), sources = { "owner/repo", … } (more extras catalogs) } | | `policy_timeout_ms` | number | `30000` | default timeout for policy/rewrite listeners without explicit timeout_ms (ms) | | `prompt` | string | `"❯"` | input prompt symbol | | `providers` | table | | providers (mare.provider): { base_url, api_key, headers, query_params, retries, stream_idle_timeout_ms, connect_timeout_ms, wire, wire_api, login_hint, proxy, hosted_tools, cache_retention } plus wire-declared provider_fields | | `reduce_motion` | boolean | `false` | no spinner animation or other motion: static status text instead | | `shutdown_grace_ms` | number | `4000` | grace period (ms) for cooperative tasks during host shutdown before process-tree termination | | `slow_callback_ms` | number | `1000` | Lua callback busy-time threshold in ms for slow-callback warnings (default 1000 ms; /profile aggregates callbacks over 2 ms) | | `slow_callback_record_ms` | number | `1000` | Lua callback busy-time threshold in ms above which individual slow callbacks are recorded in /profile | | `slow_callback_table_rows` | number | `100` | maximum number of (plugin, event) rows shown in the /profile callback timing table | | `spinner` | table | | spinner glyphs: a list { "a", "b", … } or { frames = {…}, still = "•" } (still: the marker under reduce_motion); default braille | | `stall_ms` | number | `10000` | a plugin still loading, unloading or waiting for a service after this many ms is reported (/plugins tree, `mare plugin tree --json`, the log, a notice); never aborted; 0 turns it off | | `terminal` | table | `{ ambiwidth = "single", color = "auto", probe = { background = true, enabled = true } }` | terminal capability, probing, and ambiwidth configuration (`terminal.{ambiwidth,color,probe.{enabled,background}}`) | | `terminal_caps` | table | | terminal capability overrides { { match = { TERM_PROGRAM = "…" }, caps = { sync = false, … } }, … }; ui/caps listeners may also adjust them | | `theme` | table | | named style overrides { MareX = spec } | | `trust_default` | string | `"ask"` | project trust for a folder with no saved decision (after --trust/--no-trust and trust/resolve plugins): ask\|trust\|distrust | | `ui` | table | `{ layout = { regions = { } }, stopping = { spinner = true }, tool_call = { spinner = "braille" }, working = { elapsed = "auto", glyph = "swell", interrupt_hint = true, label = "glint", preset = "combined", sep = "dot", text_throttle_ms = 250, tips = true, tokens = true, tools = "still" } }` | UI configuration: { layout = { ... }, working = ..., tool_call = { ... }, stopping = { ... } } | | `update_check` | boolean | `true` | check GitHub releases for a newer mare (at most daily, interactive sessions; nothing else is sent) | | `watchdog_ms` | number | `10000` | **Invocation only.** per-callback limit for Lua that never yields (ms). CLI/env only: --set watchdog_ms=… or MARE_WATCHDOG_MS (the watchdog starts before init.lua, so a value written in init.lua has no effect) | | `webserver` | table | `{ accept_partial = { }, allowed_origins = { }, enabled = false, header_read_timeout_ms = 30000, host = "127.0.0.1", max_connections = 256, plain_http = false, port = 0, remote_admin = false, trusted_hosts = { }, ws_max_message_bytes = 67108864, ws_ping_interval_ms = 15000, ws_pong_timeout_ms = 10000 }` | Host HTTP/WebSocket RPC listener: { enabled, host, port, token?, trusted_hosts, allowed_origins, remote_admin, tls_cert?, tls_key?, plain_http?, max_connections, header_read_timeout_ms, ws_max_message_bytes, ws_max_frame_bytes, ws_ping_interval_ms, ws_pong_timeout_ms, accept_partial } | ## Plugin options Built-in plugin options declared via `config_schema`, set with `mare.plugin("<name>", { ... })`. Every plugin also accepts `enabled = false` to disable it. ### `agent` | Option | Type | Default | Description | |---|---|---|---| | `max_image_wire_bytes` | integer | `20971520` | Maximum estimated inline image bytes before offloading older images. | | `max_overflow_compactions` | integer | `3` | Consecutive context overflow, compact, retry rounds. | | `max_parallel` | integer | `10` | Concurrency-safe tool calls of one turn run in parallel, at most this many at once. | | `max_turns` | integer | `200` | Most model turns in one run. | | `request_retries` | integer | `3` | Attempts for a request interrupted by a crash, shared with network retries. | | `request_retry_base_ms` | integer | `2000` | First backoff of a request retry. | | `request_retry_max_ms` | integer | `60000` | Largest backoff of a request retry. | ### `agents` | Option | Type | Default | Description | |---|---|---|---| | `preview_min_width` | integer | `84` | The preview pane shows from this terminal width (side by side). | | `refresh_ms` | integer | `1000` | The open list refreshes in place this often (only when it changed). | | `split.min` | integer | `80` | Narrowest the list may get, in cells. | | `split.ratio` | number | `0.5` | Share of the width the list takes. | ### `approval-review-model` | Option | Type | Default | Description | |---|---|---|---| | `model` | string | | Model ref used to review approvals. | | `name` | string | `"model"` | Name the reviewer registers under. | ### `approvals` | Option | Type | Default | Description | |---|---|---|---| | `fallback` | boolean | `false` | Fall back to asking the user when the automatic reviewer fails. | | `policy` | ask\|never\|untrusted or object | `"ask"` | **Env:** `MARE_APPROVAL_POLICY`. Approval policy: ask, never, untrusted, or a granular table. | | `review_all` | boolean | `false` | Require review of every request. | | `review_timeout_ms` | integer | `30000` | Time an automatic reviewer has to decide. | | `reviewer` | string | `"user"` | Name of the approval reviewer; "user" asks the user. | ### `cells` | Option | Type | Default | Description | |---|---|---|---| | `execution_mode` | per-call\|persistent-in-memory\|vm-script | `"per-call"` | How script VMs are reused between calls. | | `grace_ms` | integer | `3000` | Grace period of a script run in milliseconds. | | `max_bytes` | integer | `1048576` | Byte cap of sandbox data; also the default of the message and output caps. | | `max_instructions` | integer | `10000000` | Instruction budget of a script. | | `max_message_bytes` | integer | `0` | Largest message; 0 inherits max_bytes. | | `max_output_bytes` | integer | `0` | Largest output; 0 inherits max_bytes. | | `max_parallel_sub_calls` | integer | `10` | Parallel tool sub-calls from a script. | | `max_pending_calls` | integer | `128` | Pending host calls allowed at once. | | `max_sub_calls_per_minute` | integer | `1024` | Rate cap of tool sub-calls from a script. | | `memory_bytes` | integer | `33554432` | Memory limit of a script VM. | | `script_persistence` | boolean | `false` | Persist scripts across sessions. | | `stop_grace_ms` | integer | `3000` | Grace period when stopping a script. | | `timeout_ms` | integer | `60000` | Script timeout in milliseconds. | ### `changes` | Option | Type | Default | Description | |---|---|---|---| | `cap_bytes` | integer | `67108864` | Cap for stored backups; the oldest turns' backups are trimmed first. | ### `compact` | Option | Type | Default | Description | |---|---|---|---| | `auto` | boolean | `true` | Compact automatically when the threshold is reached. | | `failure_backoff_max_ms` | integer | `600000` | Largest backoff after repeated failures. | | `failure_backoff_ms` | integer | `30000` | Initial backoff after a failed compaction. | | `headroom_tokens` | integer | `32768` | Tokens kept free of the window besides the output reserve. | | `keep_recent_tokens` | integer | `20000` | Recent context kept verbatim after a summary. | | `model_thresholds` | map | `{}` | Per-model trigger overrides by model ref. | | `offload_keep_images` | integer | `2` | The most recent images stay inline. | | `prune_head_chars` | integer | `4096` | Characters kept from the head of a pruned result. | | `prune_min_saving_tokens` | integer | `20000` | Prune stage: least saving that makes it worth running. | | `prune_protect_tokens` | integer | `40000` | Prune stage: most recent tokens left untouched. | | `prune_tail_chars` | integer | `1024` | Characters kept from the tail of a pruned result. | | `prune_tool_result_chars` | integer | `8192` | Tool results longer than this are pruned. | | `recent_user_tokens` | integer | `20000` | Older user messages kept verbatim. | | `remote` | boolean | `true` | Run the provider-side compaction stage (can also be removed from `stages`). | | `retain_ratio` | number | `0.16` | Share of the message budget retained after a summary. | | `stages` | list | `{ "prune", "offload", "remote", "local" }` | Compaction stages, in order. | | `summary_max_tokens` | number | | Output cap of a summary request; default headroom. | | `summary_model` | string | | Model ref for local summaries, e.g. a cheaper one. | | `threshold_percent` | number | | Explicit trigger as a percent of the window. | | `threshold_ratio` | number | `0.8` | Share of the context window that triggers compaction. | | `threshold_tokens` | number | | Explicit trigger as a token count. | ### `context` | Option | Type | Default | Description | |---|---|---|---| | `append` | string | `""` | Extra text appended to the system prompt (with APPEND_SYSTEM.md). | | `files` | list | `{ "AGENTS.override.md", "AGENTS.md", "CLAUDE.md" }` | Project instruction file names; per directory the first existing one wins. | | `persona` | string | `""` | Replaces only the identity line; `{{model}}` etc. are interpolated. | | `project_doc_max_bytes` | integer | `32768` | Byte cap of the project documents. | | `project_root_markers` | list | `{ ".git" }` | Markers of a project root; {} = only the cwd. | | `prompt_dirs` | list | | Prompt template directories (`<dir>/<name>.md` becomes `/name`); nil = `<config dir>/prompts` plus `.mare/prompts`. | | `rules` | list | `{}` | Extra rule bullets. | | `skill_dirs` | list | `{ "~/.config/mare/skills", "~/.agents/skills", ".mare/skills", ".agents/skills" }` | Directories skills are loaded from. | | `system` | string | `""` | The whole system prompt, verbatim, like SYSTEM.md; no default section is sent. | ### `copy` | Option | Type | Default | Description | |---|---|---|---| | `always_full` | boolean | `false` | Always copy the full text. | ### `file-ref` | Option | Type | Default | Description | |---|---|---|---| | `limit` | integer | `30` | Completion items. | | `max_bytes` | integer | `102400` | Byte cap per referenced file. | | `max_total_bytes` | integer | `262144` | Byte cap of all files of one message together. | | `refresh_ms` | integer | `1000` | The file index checks for changes at most this often. | ### `images` | Option | Type | Default | Description | |---|---|---|---| | `max_cols` | integer | `60` | Widest an image may be drawn, in cells. | | `max_rows` | integer | `12` | Tallest an image may be drawn, in cells. | | `read` | boolean | `true` | Show images returned by the read tool. | | `tools` | boolean | `true` | Show images in other tools' results. | | `user` | boolean | `true` | Show images pasted / attached to a prompt. | ### `jobs` | Option | Type | Default | Description | |---|---|---|---| | `batch_ms` | integer | `50` | Jobs finishing within this window share one notification. | | `buffer_bytes` | integer | `1048576` | Ring buffer per job. | | `kill_grace_ms` | integer | `3000` | SIGTERM, then SIGKILL after this long. | | `max_jobs` | integer | `64` | Jobs kept in total; finished ones beyond this are pruned, least recently used first. | | `max_running` | integer | `8` | Concurrent jobs per agent. | | `max_wait_ms` | integer | `600000` | Cap of the job_output wait. | | `max_wakeups` | number | | Consecutive wake-ups of an idle agent without user input (nil = no limit). | | `notify_inline_bytes` | integer | `2048` | Completion notices include output up to this size. | | `read_max_bytes` | integer | `51200` | Most job_output returns per call. | | `view_refresh_ms` | integer | `500` | /jobs output view refresh while open. | | `view_tail_bytes` | integer | `65536` | /jobs output view: the last this many bytes. | | `wait_timeout_ms` | integer | `30000` | Default wait of job_output. | | `widget` | boolean | `true` | Running-jobs line above the input box. | ### `llm` | Option | Type | Default | Description | |---|---|---|---| | `catalog_open_refresh_ms` | integer | `600000` | Opening /model refreshes the configured providers' lists older than this. | | `catalog_refresh_ms` | integer | `86400000` | Age after which a provider's cached model list is refreshed in the background. | | `crash_limit` | integer | `3` | A request that crashed mare this many times is not sent again. | | `models_dev` | boolean | `true` | Merge models.dev metadata (price, modalities, reasoning, limits) into listed models. | | `models_dev_url` | string | `"https://models.dev/api.json"` | Where the models.dev metadata is fetched from. | | `overloaded_retries` | integer | `3` | Retries of a 529 / overloaded response. | | `retries` | integer | `5` | Retries of a failed request. | | `retry_after_max_ms` | integer | `60000` | A server asking to wait longer than this fails at once. | | `retry_base_ms` | integer | `500` | First retry backoff. | | `retry_max_ms` | integer | `8000` | Largest retry backoff. | | `sse_max_event_bytes` | integer | `16777216` | Longest SSE event (its lines together); longer is a malformed_response. | | `sse_max_line_bytes` | integer | `16777216` | Longest SSE line; longer is a malformed_response. | | `stream_idle_timeout_ms` | integer | `300000` | No bytes at all for this long (heartbeats count) is a transport error. | ### `lua-console` | Option | Type | Default | Description | |---|---|---|---| | `history_max` | integer | `500` | Most history entries kept. | ### `mcp` | Option | Type | Default | Description | |---|---|---|---| | `call_timeout_ms` | integer | `120000` | One tools/call (progress notifications reset it). | | `files` | boolean | `true` | Read mcp.json / .mcp.json / .mare/mcp.json / $MARE_MCP_CONFIG. | | `servers` | map | `{}` | MCP servers by name. | | `startup_timeout_ms` | integer | `60000` | Initialize plus the first listings (at most 300000). | | `text_limit` | integer | `20480` | Longer text results are cut in the middle. | | `tier` | string | `"deferred"` | Default exposure tier for servers without their own. | ### `notify` | Option | Type | Default | Description | |---|---|---|---| | `bell` | boolean | `false` | Also ring the bell after the OSC notification. | | `cmd` | string or table | | Program (string) or argv list run with the event as JSON on stdin. | | `cmd_timeout_ms` | integer | `10000` | Timeout of `cmd` in milliseconds. | | `dedupe_ms` | integer | `10000` | Window in which an identical notification is dropped. | | `min_turn_ms` | integer | `5000` | Shortest turn that notifies. | | `on_done` | boolean | `true` | Notify when a turn is done. | | `on_input` | boolean | `true` | Notify when input is needed. | | `only_unfocused` | boolean | `true` | Notify only while the terminal is unfocused. | | `protocol` | string | `"auto"` | Notification protocol; "bel" is just the bell, "native" a desktop notification. | ### `onboarding` | Option | Type | Default | Description | |---|---|---|---| | `enabled` | boolean | `true` | Offer the guided first-run login when no credentials exist. | | `plugins` | boolean | `true` | Offer optional plugins on first open. | ### `permissions` | Option | Type | Default | Description | |---|---|---|---| | `accept_partial` | list | | Sandbox dimensions accepted as unenforced when the platform backend cannot provide them. | | `dangerous.disable` | list | `{}` | Built-in rules to turn off by name. | | `dangerous.enabled` | boolean | `true` | Whether dangerous-command detection is on. | | `dangerous.rules` | list | `{}` | Extra argv prefixes treated as dangerous. | | `deny_read` | list | `{}` | Literal deny-read paths. | | `network` | boolean or table | `true` | Network access of the `auto` preset: true (open), false, or a deny/allow table. | | `parse.deny_commands` | list | `{}` | Command words that make a command not analyzable. | | `parse.safe_sinks` | list | `{}` | Extra fixed redirect targets that keep a command analyzable. | | `preset` | read-only\|auto\|full-access\|<presets> | `"auto"` | Sandbox and approval preset (a built-in one or a name from `presets`). | | `presets` | map | `{}` | Extra presets by name. | | `readable` | list | `{}` | Extra readable roots for the `auto` preset. | | `rules` | list | `{}` | Permission rules. | | `rules_file` | string | | File of persisted rules ("always allow"); default <state>/permissions.json. | | `sensitive.disable` | list | `{}` | | | `sensitive.enabled` | boolean | `true` | | | `sensitive.patterns` | list | `{}` | | | `suggest_after` | integer | `3` | Consecutive approvals of the same kind before suggesting a wider preset. | | `unix_sockets` | list | `{}` | Unix sockets reachable while the network is restricted. | | `untrusted_preset` | string | `"read-only"` | Preset untrusted projects start with, whatever `preset` says. | | `writable` | list | `{}` | Extra writable roots for the `auto` preset. | ### `plugins` | Option | Type | Default | Description | |---|---|---|---| | `watch_ms` | integer | `2000` | Poll interval of the package watcher. | ### `provider-anthropic` | Option | Type | Default | Description | |---|---|---|---| | `answer_headroom` | integer | `8192` | Room kept for the answer next to the reasoning budget. | | `base_url` | string | `"https://api.anthropic.com"` | API endpoint root. | | `cache_retention` | none\|short\|long | | Prompt cache retention tier: "none" \| "short" \| "long" (nil = global/short). | | `default_max_output` | integer | `32000` | Output cap when the model declares none. | | `headers` | map | `{}` | Extra request headers. | | `reasoning_budgets` | map | `{ high = 24576, low = 4096, medium = 10240, minimal = 1024, xhigh = 32768 }` | Reasoning budget per effort for non-adaptive models. | | `reasoning_display` | string | `"summarized"` | How reasoning is returned: "summarized" or "omitted". | | `transport` | string | `"auto"` | "auto", "http" or a transport plugin's name (`provider/transport`). | ### `provider-faux` | Option | Type | Default | Description | |---|---|---|---| | `script` | string | | Scripted replies. | | `script_json` | string | | Scripted replies as JSON. | ### `provider-google` | Option | Type | Default | Description | |---|---|---|---| | `base_url` | string | `"https://generativelanguage.googleapis.com/v1beta"` | API endpoint root. | | `headers` | map | `{}` | Extra request headers. | | `transport` | string | `"auto"` | "auto", "http" or a transport plugin's name (`provider/transport`). | ### `provider-openai` | Option | Type | Default | Description | |---|---|---|---| | `auth_base_url` | string | `"https://auth.openai.com"` | Auth endpoint root. | | `base_url` | string | | API-key endpoint override (default https://api.openai.com/v1). | | `cache_retention` | none\|short\|long | | Prompt cache retention tier: "none" \| "short" \| "long" (nil = global/short). | | `callback_ports` | list | | Local ports tried for the browser login callback (default 1455, 1457). | | `codex_base_url` | string | `"https://chatgpt.com/backend-api"` | ChatGPT (Codex) endpoint root. | | `compact_timeout_ms` | integer | | Timeout for /responses/compact requests (ms). | | `device_code_timeout_ms` | integer | | How long the device-code login waits (default 15 minutes). | | `headers` | map | `{}` | Extra request headers, merged over the computed ones (e.g. a proxy's auth header). | | `originator` | string | `"mare"` | Originator reported to the API. | | `reasoning_summary` | string | | Reasoning summary mode sent with requests (default "auto"). | | `session_header` | string | | Request header carrying the session id on every request of a session; nil = none. | | `stream_idle_timeout_ms` | integer | `300000` | No bytes for this long ends a stream as a transport error. | | `transport` | string | `"auto"` | "auto", "websocket", "http" or a transport plugin's name (`provider/transport`). | | `verbosity` | string | | Overrides the model default (low\|medium\|high). | | `web_search` | disabled\|cached\|indexed\|live | | OpenAI hosted web_search tool; nil / "disabled" = off (explicit opt-in). | | `web_search_config` | map | | Policy / config passthrough of the web_search tool. | | `websocket_connect_timeout_ms` | integer | `15000` | WebSocket connect timeout. | ### `provider-openai-compat` | Option | Type | Default | Description | |---|---|---|---| | `cache_retention` | none\|short\|long | | Prompt cache retention tier: "none" \| "short" \| "long" (nil = global/short). | | `headers` | map | `{}` | Extra request headers for every endpoint; per-endpoint `headers` win. | | `transport` | string | `"auto"` | "auto", "http" or a transport plugin's name (`provider/transport`). | ### `provider-opencode-go` | Option | Type | Default | Description | |---|---|---|---| | `base_url` | string | `"https://opencode.ai/inference/go"` | The gateway root; each route's address is base_url .. path. | | `cache_retention` | none\|short\|long | | Prompt cache retention tier: "none" \| "short" \| "long" (nil = global/short). | | `custom_tools` | boolean | `false` | Send `custom` (freeform) tools; the gateway rejects them with a 400. | | `default_route` | string | `"responses"` | Route of every model unless something below picks another. | | `model_routes` | map | `{}` | Glob over model ids (or provider/id) to route; the longest pattern wins. | | `models_dev_routes` | boolean | `false` | Take a listed model's route from its models.dev protocol (only onto configured routes). | | `routes` | map | `{ anthropic = { auth = "bearer", path = "/anthropic", replay_unsigned_reasoning = true, wire = "anthropic-messages" }, responses = { path = "/openai/v1", wire = "openai-responses" } }` | Gateway routes by name: path, llm wire, auth and per-route wire options. | | `session_header` | string | `"x-opencode-session"` | Stable per-session header on every request, main and auxiliary (400 MissingSessionID without it). | | `supports_long_cache_retention` | boolean | | Whether the provider supports long (1h / 24h / 12h) prompt cache retention. | ### `repeat-guard` | Option | Type | Default | Description | |---|---|---|---| | `arguments_preview_chars` | integer | `500` | Bounds the quoted arguments, never the detection. | | `exclude` | list | `{}` | Tool-name patterns (`*` wildcard) never guarded. | | `include` | list | `{}` | Tool-name patterns (`*` wildcard) to guard; empty = every tool. | | `thresholds` | list | `{ 3, 5, 8 }` | Repeat counts at which the guard steps in. | ### `review` | Option | Type | Default | Description | |---|---|---|---| | `collapse_lines` | integer | `400` | Diffs longer than this many lines start collapsed. | | `prompt_diff_bytes` | integer | `122880` | /review: the diff in the reviewer's prompt is cut at this many bytes. | | `scopes` | list | `{ "turns", "unstaged", "staged", "committed" }` | Diff scopes offered, in order. | | `tools` | list | `{ "read", "ls", "bash" }` | The reviewer's tools (read-only). | | `untracked_file_bytes` | integer | `262144` | Most bytes of one untracked file. | | `untracked_files` | integer | `50` | Most untracked files included. | ### `session` | Option | Type | Default | Description | |---|---|---|---| | `branch_summary` | boolean | `true` | Summarize the branch left behind when switching branches. | | `picker_looks` | map | | Looks to add or replace, by name. | | `picker_segments` | map | | Custom picker segments by name. | | `picker_split` | map | | The list's share of a wide picker next to its preview. | | `picker_style` | string | `"comfortable"` | Default /resume look: a built-in one or a name from `picker_looks`. | | `resume_cwd` | ask\|current\|session | `"ask"` | Directory used when resuming a session recorded in another one. | | `transcript_poll_ms` | integer | `500` | Live refresh of an open sub-session transcript. | ### `shell-mode` | Option | Type | Default | Description | |---|---|---|---| | `context_max_bytes` | integer | `51200` | Bytes of output the model sees (middle-truncated beyond this). | | `context_max_lines` | integer | `2000` | Lines of output the model sees (middle-truncated beyond this). | | `preview_lines` | integer | `5` | Lines of the collapsed transcript preview; Ctrl+O always shows everything. | | `timeout_ms` | integer | `600000` | Timeout of a `!cmd` command. | ### `spill` | Option | Type | Default | Description | |---|---|---|---| | `backend` | string | `"local"` | Name of the spill store backend. | | `cleanup_period_days` | integer | `30` | Days stored spills are kept. | | `root` | string | | Directory of the local spill store. | ### `status` | Option | Type | Default | Description | |---|---|---|---| | `exit_timeout_ms` | integer | `3000` | How long shutdown waits for `exit` hooks in total. | | `message_max` | integer | `120` | Message length cap. | | `throttle_ms` | integer | `200` | Default per-hook coalescing window. | | `timeout_ms` | integer | `2000` | Default per-hook command timeout (the process is killed after it). | | `title` | boolean | `true` | Set the terminal title (OSC 2) from the state. | | `title_format` | string | `"%s — mare"` | Terminal title; %s = "working: …" / "waiting: …" / project name. | ### `statusline` | Option | Type | Default | Description | |---|---|---|---| | `changed_files` | boolean | `true` | Show `± N`: files `git status` reports changed (refreshed once per turn). | | `command` | string or table | | Command (string, run via the shell, or argv table) whose output joins the bar. | | `command_replaces` | boolean | `false` | Replace the built-in segments instead of adding the command's output to them. | | `command_timeout_ms` | integer | `1000` | Timeout of `command`. | | `cwd_min_terminal_width` | integer | `100` | The directory segment shows from this terminal width on. | | `cwd_width` | integer | `24` | Cells of the working directory (longer paths keep their last components). | | `gauge_width` | integer | `6` | Cells of the context usage bar. | | `git_timeout_ms` | integer | `10000` | Timeout of git queries. | | `hidden` | list | `{}` | Segments not shown. | | `layout` | string or table | | The bar's layout: a built-in look, a name in `looks`, or a look table. | | `layout_margin` | integer | `2` | Cells kept free at the right edge when fitting a layout. | | `layout_opts` | map | | Overrides single elements of the layout. | | `looks` | map | | Adds or replaces named looks. | | `pr` | boolean | `true` | Show the current branch's pull request via `gh pr view` (when gh is installed). | | `pr_timeout_ms` | integer | `5000` | Timeout of the pull request query. | ### `subagent` | Option | Type | Default | Description | |---|---|---|---| | `extra_agent_dirs` | list | `{}` | Additional agent definition directories; project-relative paths require trust. | | `notify_inline_bytes` | integer | `4096` | Completion notices include a sub-agent's output up to this size. | ### `theme-default` | Option | Type | Default | Description | |---|---|---|---| | `blend_background` | boolean | `true` | Blend the palette with the terminal background. | | `colors` | map | | Palette overrides by base (dark / light). | | `dirs` | list | | Theme directories; default `<config dir>/themes`. | | `flavors` | map | | Flavors by name. | | `ratios` | map | | Background blend ratios. | ### `tools` | Option | Type | Default | Description | |---|---|---|---| | `bash_max_timeout_ms` | integer | `600000` | Largest bash timeout a call may ask for. | | `bash_read_bytes` | integer | `4194304` | Most output a finished command returns from its job buffer. | | `bash_timeout_ms` | integer | `120000` | Default bash timeout. | | `cancel_grace_ms` | integer | `2000` | After cancellation, how long a tool may take to stop by itself. | | `edit_max_bytes` | integer | `10485760` | Largest file edit / apply_patch accept. | | `edit_mode` | auto\|apply_patch\|replace | `"auto"` | Edit tool: "auto" (apply_patch for GPT models, replace otherwise), "apply_patch" or "replace". | | `env.exclude` | list | `{}` | More names to drop. | | `env.include` | list | `{}` | Names to keep despite the scrubbing. | | `env.set` | map | `{}` | Name to value, added after scrubbing. | | `image_max_dim` | integer | `2000` | Images read by `read` are downscaled to fit. | | `live_tail_bytes` | integer | `4096` | Running-command output shown in the UI. | | `ls_limit` | integer | `500` | Default `ls` entry limit. | | `max_bytes` | integer | `51200` | Tool output truncation: bytes. | | `max_line_chars` | integer | `500` | Search output: per-line cap. | | `max_lines` | integer | `2000` | Tool output truncation: lines. | | `powershell` | string or boolean | `"auto"` | PowerShell tool: "auto" (on Windows), true, false or "replace". | | `prelude` | string or table | | String or list run before every shell command (bash tool, `!cmd`), e.g. 'eval "$(mise env -s bash)"'. | | `read_before_edit` | boolean | `true` | Require a read of a file in this session before editing or overwriting it. | | `read_max_line_bytes` | integer | `2000` | Read: lines longer than this are cut on a UTF-8 boundary. | | `read_stream_min_bytes` | integer | `10485760` | Files at or above this size are read by streaming the requested window. | | `search_results` | integer | `5` | Default result count of tool_search. | | `shell` | string | | Path of the shell; default $SHELL (bash/zsh) or bash; Windows: Git Bash. | | `shell_buffer_bytes` | integer | `1048576` | Output of one command the persistent shell keeps in memory. | | `shell_session` | string | `"persistent"` | "persistent" (one shell per agent) or "fresh" (a new shell per call). | | `stall_ms` | integer | `30000` | A command silent this long is returned as "still running"; 0 = only the timeout. | | `timeout_ms` | integer | `600000` | Generic per-tool timeout. | | `update_interval_ms` | integer | `150` | UI update throttle for running commands. | ### `ui` | Option | Type | Default | Description | |---|---|---|---| | `diff_fold_lines` | integer or boolean | `8` | Rows a compact diff keeps before folding the rest (false = show full diff). | | `double_esc_ms` | integer | `600` | Esc Esc window (the /undo picker when idle). | | `group_lines` | integer | `4` | Merged lines an exploration group keeps; older ones become "N earlier". | | `preview_lines` | integer | `2` | Compact view (Ctrl+O toggles): lines of command / output shown per tool call. | | `tool_update_interval_ms` | integer | `100` | Refresh of live tool output. | | `widget_area_ratio` | number | `0.5` | Share of the terminal height the widget area may use, minus the input box and status bar. | | `widget_reserved_rows` | integer | `4` | Rows kept free of widgets. | ### `update-check` | Option | Type | Default | Description | |---|---|---|---| | `enabled` | boolean | `true` | Check for a newer release. | | `interval_hours` | number | `24` | Hours between checks. | | `timeout_ms` | integer | `5000` | Request timeout in milliseconds. | | `url` | string | `"https://api.github.com/repos/signalridge/mare/releases/latest"` | Release API endpoint to query. | ### `web` | Option | Type | Default | Description | |---|---|---|---| | `allowed_domains` | list | | Native search: only these domains (exclusive with blocked_domains). | | `blocked_domains` | list | | Native search: never these domains (exclusive with allowed_domains). | | `context_size` | low\|medium\|high | | Native search context size. | | `fetch` | boolean | `true` | Offer the web fetch tool. | | `fetch_max_output_chars` | integer | `200000` | Most characters a fetch returns. | | `fetch_provider` | string | | Fetch provider name (overridden by MARE_WEB_FETCH_PROVIDER). | | `fetch_timeout_ms` | integer | `30000` | Fetch timeout. | | `location` | map | | Approximate user location passed to native search. | | `native_max_uses` | integer | `5` | Most uses of a provider's native search per request. | | `native_version` | string | | Version of the provider-native search tool. | | `search` | boolean | `true` | Offer the web search tool. | | `search_max_queries` | integer | `10` | Most queries in one search call. | | `search_max_results` | integer | `10` | Most results per query. | | `search_provider` | string | | Search provider name (overridden by MARE_WEB_SEARCH_PROVIDER). | | `search_summary_max_chars` | integer | `800` | Characters kept of a result summary. | | `search_timeout_ms` | integer | `30000` | Search timeout. | | `web_search` | disabled\|cached\|indexed\|live | `"cached"` | Web search mode. | ### `web-fetch-http` | Option | Type | Default | Description | |---|---|---|---| | `max_html_depth` | integer | `128` | Maximum DOM nesting depth during conversion. | | `max_html_nodes` | integer | `50000` | Maximum DOM node count traversed during conversion. | | `max_html_tags` | integer | `100000` | Maximum HTML tag count parsed during conversion. | | `max_output_bytes` | integer | `100000` | Maximum extracted text/markdown output size in bytes. | | `max_redirects` | integer | `5` | Maximum number of HTTP redirects to follow. | | `max_response_bytes` | integer | `5000000` | Maximum raw HTTP response body size in bytes. | | `max_url_length` | integer | `8192` | Maximum allowed URL length in bytes. | | `redirect` | string | `"same-origin"` | Redirect policy: same-origin, follow, or manual. | | `timeout_ms` | integer | `30000` | Overall fetch request timeout in milliseconds. | | `user_agent` | string | `"mare-web-fetch/1"` | User-Agent header sent on fetch requests. | ================================================================================ Title: Packages Section: Configure URL: https://signalridge.github.io/mare/en/configure/packages/ Markdown: https://signalridge.github.io/mare/raw/en/configure/packages.md Source: docs/en/configure/packages.md ================================================================================ # Packages Install plugins, themes and skills from git with mare.plugins.add: declaring and pinning versions, the lock file, the mare plugin commands and startup behavior. ## Declare packages `mare.plugins.add` takes a list. Each entry is a string or a table. ```lua -- ~/.config/mare/init.lua mare.plugins.add { "someone/mare-git-tools", -- newest semver tag, else the default branch { "someone/mare-extras", version = "^1.2" }, -- a semver range over the tags { "someone/monorepo:mare", only = { "tidy" } }, -- a subdirectory; load only some plugins { "git@example.com:team/internal-tools.git", branch = "main" }, { dir = "~/code/my-plugin" }, -- a local directory, never installed { import = "packages" }, -- more declarations from lua/packages.lua } ``` A short name `owner/repo` expands through the `plugins.url_format` option (default `https://github.com/%s.git`). A full address works too: a URL, an `ssh` address, or a path. Only `https`, `ssh` and `file` transports are used, and git never prompts for a password. Plain `http://` and `git://` need `plugins = { allow_insecure = true }`. Fields of a table entry: | Field | Meaning | |---|---| | `[1]` | The source: `owner/repo`, `owner/repo:subdir` or a git address. | | `name` | A display name. With no `[1]`, it is the source. | | `only` | Names of the plugins to load from the package. The rest are ignored. | | `subdir` | A subdirectory of the repository (the same as `owner/repo:subdir`). | | `version`, `tag`, `branch`, `commit`, `rev` | What to check out. See below. | | `pin` | `true`: `update` leaves it where it is. | | `submodules` | `false`: do not fetch git submodules. | | `dir` | A local directory, loaded from there, never installed or locked. | | `dependencies` | Packages that load first (strings or full entries). | | `enabled` | `false`, or a function returning a boolean. A disabled package is neither installed nor loaded; its lock entry stays. | | `required` | `true`: failure to install or load this package blocks model requests until repaired and `/reload`ed (separate from `optional`, which only affects declaration merging). | | `optional` | Declaration-merge only: the entry counts only if the package is declared elsewhere too. | | `opts` | Per-plugin defaults, `{ pluginname = { ... } }`, or a function that returns them. | | `opts_extend` | Dotted paths in `opts` whose lists are appended across declarations instead of replaced. | | `init` | `function(pkg)`, runs before the package's plugins load. | | `config` | `function(pkg, opts)`, runs after its plugins load, and again on `/reload`. | | `import` | A module under `lua/` that returns more declarations. | A package declared more than once is merged: the last value wins for single fields, `opts` merge deeply, `dependencies` and `only` accumulate, and the last explicit `enabled` value wins (omitting `enabled` in a later declaration preserves the previous value). Options from `opts` sit under `mare.plugin`: a value you set with `mare.plugin` always wins. ```lua mare.plugins.add { { "someone/mare-extras", version = "^1.2", opts = { tidy = { max_lines = 80 } }, config = function(pkg, opts) mare.log("info", pkg.name .. " ready") end, }, } ``` ### Split declarations across files `{ import = "packages" }` loads `lua/packages.lua`, `lua/packages/init.lua`, every `lua/packages/*.lua`, and every `lua/packages/<subdir>/init.lua`. Each file returns a list of declarations. Imports nest up to 16 levels, each module is imported once, and a cycle is skipped with a warning. ```lua -- ~/.config/mare/lua/packages/git.lua return { "someone/mare-git-tools", { "someone/mare-extras", enabled = function() return mare.os ~= "windows" end }, } ``` ## Pin versions The first of these fields present decides the target, in this order: | Field | Target | |---|---| | `commit = "<sha>"` | That commit. `update` never moves it. | | `tag = "v1.4.0"` | That tag. | | `branch = "main"` | The head of that branch. | | `version = "^1.2"` | The newest tag inside the semver range. | | `rev = "<ref>"` | Any git revision. `rev = "=<sha>"` is an exact pin. | | none | The newest semver tag, else the default branch. | Add `pin = true` to hold any package where it is until you change the declaration. ## The lock file `~/.config/mare/mare-lock.json` (and `.mare/mare-lock.json` for project-scoped packages in a trusted project) records, for each package, its URL, the commit, the constraint it was locked for, the branch it follows, and a content hash of the checkout. Commit it with your dotfiles or repository to get the same packages on every machine. mare writes it after each package finishes, so a failed package does not lose the others. A corrupt lock file stops normal package commands without modifying checkouts; run `mare plugin restore --repair` (or `mare doctor --fix`) to rebuild it from clean installed checkouts, or fix or delete the file and run `mare plugin update`. Selections in `plugins.json` use version 2: `{ "version": 2, "plugins": [{ "source": "owner/repo", "name": "plugin" }] }`. Shared checkouts are kept while any user or project scope still references them. Checkouts live in `~/.local/share/mare/packages/<host>/<path>`. ## Commands | Command | Does | |---|---| | `mare plugin sync` | Install missing packages at the locked commit. If the constraint in `init.lua` changed, it resolves again. | | `mare plugin update [name]` | Move packages (or one) to the newest revision their constraint allows, list the new commits, rewrite the lock. Exact pins stay. | | `mare plugin check [name...] [--json]` | Fetch and compare revisions without moving checkouts or changing the lock. | | `mare plugin restore [name]` | Check out all sources, or the named one, at the locked commit. The lock is unchanged. | | `mare plugin restore --repair` | Rebuild a missing or corrupt lock from clean installed checkouts. | | `mare plugin list [--json]` | List declared sources with their state. | | `mare plugin tree [--json]` | Show the composed runtime plugin tree. | | `mare plugin install <name...>` | Enable catalog plugins by short name and install their required sources. | | `mare plugin uninstall <name...>` | Disable catalog plugins by short name and clean unused sources. | | `mare plugin clean` | Remove checkouts no longer declared and stale lock entries. | ```sh mare plugin sync mare plugin update someone/mare-extras mare plugin list ``` Fetches run in parallel (`plugins.concurrency`, default 8), each git operation has a timeout (`plugins.timeout`, default 120 seconds), and Ctrl-C cancels them. A checkout with local edits is flagged and never deleted by `clean`. `mare plugin` commands resolve project trust from `--trust`, `--no-trust`, or your saved trust decision: in a trusted project they also load `.mare/init.lua` (executing its Lua) and can use `.mare/mare-lock.json`. Pass `--no-trust` if you want to operate on user-level config only. Inside the TUI, `/plugins` opens a panel with the same operations for everything or for one package, plus log and diff views, and a Discover tab to turn catalogued packages on and off (stored in `~/.config/mare/plugins.json`). It also reports the state of each row: installed, behind or ahead of the lock, local changes, missing, disabled, local directory, or not loaded and why. The `plugins` options are in [Options](https://signalridge.github.io/mare/en/configure/options/): On the first interactive open, mare offers to fetch the official plugin catalog and let you choose optional plugins; nothing is preselected. You can skip and use `/plugins` → Discover later. Disable this offer with `mare.plugin("onboarding", { plugins = false })`; delete `onboarding.plugins` from `state.json` to offer it again when `plugins.json` is absent. ```lua mare.setup { plugins = { url_format = "https://git.example.com/%s.git", timeout = 60, concurrency = 4 }, } ``` ## Startup and reload At startup, before plugins load, mare installs declared packages that are missing, at the locked commit, and shows progress in the TUI. Then it runs each package's `init` hook, loads plugins from each installed package in dependency order, and runs each package's `config` hook last. A required package, its hooks, or a core or explicitly required plugin can block requests until repaired and reloaded. An optional package or plugin failure is reported as a warning; other plugins and sessions continue. A failed provider blocks requests that use its models. Package changes (a sync, an update, an edit to `init.lua`) apply on `/reload`: new packages are installed and started, removed ones are unloaded, and `config` hooks run again. mare also notices when `init.lua` or `plugins.json` changes on disk and tells you to run `/reload`. `--clean` skip packages entirely. ## What a package contains | Directory | Loaded by | |---|---| | `plugins/` | The plugin loader: `name.lua` or `name/init.lua` files. See [Plugins](https://signalridge.github.io/mare/en/extend/plugins/). | | `skills/`, `prompts/` | Context: skills and prompt templates. | | `themes/` | Theme files. See [Appearance](https://signalridge.github.io/mare/en/configure/ui/). | | `types/` | LuaLS definitions, mirrored for your editor. | An optional `mare-plugin.toml` at the root can set `requires = ">=0.4"` (a package that needs a newer mare does not load), `dependencies`, `name`, `description` and `version`. To publish your own package, push a repository with these directories and tag releases with semver tags such as `v1.0.0`. [Writing a plugin](https://signalridge.github.io/mare/en/extend/writing-a-plugin/) shows the layout. ================================================================================ Title: Appearance Section: Configure URL: https://signalridge.github.io/mare/en/configure/ui/ Markdown: https://signalridge.github.io/mare/raw/en/configure/ui.md Source: docs/en/configure/ui.md ================================================================================ # Appearance Change how mare looks: named styles, themes and flavors, overriding UI components and tool renderers, the status line, borders and other appearance options. ## Styles A style is a name such as `MareAccent` with a spec: foreground, background and text attributes. Set one with `mare.ui.style`; call it with one argument to read it. ```lua mare.ui.style("MareAccent", { fg = "#7aa2f7", bold = true }) mare.ui.style("MareDim", "#5c6370") -- a string is a foreground color local spec = mare.ui.style("MareAccent") -- read it back ``` A spec accepts `fg`, `bg` (a theme slot name or `#rrggbb`) and the booleans `bold`, `dim`, `italic`, `underline`, `strike`, `reverse`. Styles you set explicitly always win over a theme, and they are re-applied when the theme changes. The `theme` option does the same for several styles at once. A string value is a foreground color. ```lua mare.setup { theme = { MareToolName = { fg = "#7aa2f7", bold = true }, MareDim = "#5c6370", }, } ``` The main style names: | Name | Used for | |---|---| | `MareText`, `MareMuted`, `MareDim`, `MareSubtle` | Body text and its quieter levels. | | `MareAccent`, `MareTitle`, `MareHeading` | Highlights, titles, Markdown headings. | | `MareError`, `MareWarning`, `MareSuccess`, `MareInfo` | Status colors. | | `MareUserMessage`, `MareUserPrompt`, `MareReasoning` | Your messages and model reasoning. | | `MareToolName`, `MareToolArgs`, `MareToolOk`, `MareToolError`, `MareToolPending`, `MareToolResult` | Tool call lines. | | `MareDiffAdd`, `MareDiffDelete`, `MareDiffAddWord`, `MareDiffDeleteWord` | Diffs. | | `MareBorder`, `MareBorderActive`, `MareSelection` | Panels and the selected row. | | `MareModeReadOnly`, `MareModeAuto`, `MareModeFull`, `MareModeCustom` | The permission capsule in the status line. | `mare.ui.styles()` returns every name. In the TUI, `/lua mare.ui.styles()` prints them. ## Themes and flavors A flavor is a complete set of styles for a dark or a light terminal. Choose one with these options: | Option | Default | Meaning | |---|---|---| | `flavor` | `auto` | `auto`, `dark`, `light`, or the name of an installed theme. | | `flavor_dark` | `dark` | The flavor `auto` picks on a dark or unknown background. | | `flavor_light` | `light` | The flavor `auto` picks on a light background. | With `auto`, mare asks the terminal for its background color after the first frame and switches. `/theme` opens a picker with a live preview; `/theme <name>` selects one directly. Both save the choice to `state.json`, and a `flavor` set in `init.lua` still wins on the next start. ```lua mare.setup { flavor = "auto", flavor_dark = "night", -- a theme you installed flavor_light = "light", } ``` ### Write a theme Put a file `<name>.lua` (or a `.tmTheme` document for syntax highlighting only) in `~/.config/mare/themes/`. A package can ship the same files in its `themes/` directory. The file returns a table. The simplest form changes the palette of the dark or light base: ```lua -- ~/.config/mare/themes/night.lua return { base = "dark", -- "dark" or "light" palette = { accent = "#7aa2f7", accent2 = "#ff9e64", selection = "#2a2f45", }, } ``` Palette keys are `accent`, `accent2`, `text`, `muted`, `dim`, `subtle`, `border`, `selection`, `code_bg`, `green`, `yellow`, `red`, `blue`, `add_bg`, `del_bg`, `add_word`, `del_word` and `on_color`, each `#rrggbb`. mare derives the named styles from the palette. To control styles directly, return `styles = { MareAccent = { fg = "#7aa2f7" } }` instead of `palette`. A paired theme gives `variants = { dark = {...}, light = {...} }`; both are required, and `auto` then follows the terminal. Without a file, define flavors in the `theme-default` plugin options: ```lua mare.plugin("theme-default", { flavors = { night = { MareAccent = { fg = "#7aa2f7" } } }, blend_background = false, -- do not mix the palette with the terminal's background }) ``` `mare.plugin("theme-default", { dirs = { "~/themes" } })` replaces the directory that is searched. ## Override a component The pieces of the transcript are Lua tables in `mare.ui` whose methods you can replace. `init.lua` runs after the defaults are installed, so an assignment wins. ```lua -- replace how a tool call header looks function mare.ui.ToolCall:header(summary, state) local mark = state == "ok" and "+" or state == "error" and "x" or "." local hl = state == "error" and "MareToolError" or "MareToolOk" return ui.Line({ ui.Span(mark .. " "):hl(hl), ui.Span(summary):hl("MareToolName") }) end -- wrap a component instead of replacing it local render = mare.ui.UserMessage.render function mare.ui.UserMessage:render(text) return ui.Lines({ render(self, text), ui.Gap() }) end ``` Components you can override include `UserMessage`, `AssistantMessage` (`render`, `marker`), `Reasoning`, `TurnEnd`, `Notice`, `ToolCall`, `Status`, `Editor`, `Logo`, `Working`, and the overlay pieces `KeyHints`, `Tabs`, `Select` and `Confirm`. Components run when a message starts or finishes and when it is invalidated, never per streamed token. `ui.Span`, `ui.Line`, `ui.Lines`, `ui.Gap`, `ui.Paragraph`, `ui.Row`, `ui.Block`, `ui.Markdown` and the rest build the nodes a component returns; the [Lua API](https://signalridge.github.io/mare/en/extend/lua-api/) page lists them. ### Tool renderers `mare.ui.renderer(kind, { compact = fn, expanded = fn })` changes how one tool's finished result is drawn. `kind` is `"tool:<name>"`. `compact` is used in the scrollback and `expanded` in the transcript (`Ctrl+T`); both receive `(call, result)` and return a node. The function returns a remove function. ```lua mare.ui.renderer("tool:bash", { compact = function(call, result) local command = call.arguments and call.arguments.command or "bash" return ui.Line({ ui.Span("$ "):hl("MareAccent"), ui.Span(command) }) end, }) ``` The user and reasoning messages accept `message:user` and `message:reasoning` renderers the same way, taking `(text)` and `(text, secs)`. Renderers and components set in `init.lua` are removed and set again on `/reload config`. ## Status line The `statusline` plugin draws the bar under the input: permission capsule, model and effort, context gauge, directory, branch, pull request, changed files, cost. `/statusline` opens a picker to hide segments; the choice is saved in `state.json`. In `init.lua`: ```lua mare.plugin("statusline", { hidden = { "pr", "cost" }, -- mode, model, effort, context, cwd, branch, pr, changes, cost, quota cwd_width = 32, gauge_width = 8, changed_files = true, }) ``` `layout` picks a different arrangement: `combined` (the default), `classic`, `codex` or `kimi`. `layout_opts` overrides single elements of it, and `looks` defines your own. ```lua mare.plugin("statusline", { layout = "combined", layout_opts = { sep = "space", flash = 0, cwd_segments = 3 }, }) ``` A look is data: `left` and `right` list the segments, `drop` lists the order in which they give way as the terminal narrows (`hints:short` shortens before dropping), and the other keys choose each element's form: `sep` (`dot` or `space`), `mode` (`word`, `capsule`, `dim`, `off`), `model` (`text`, `dim`, `muted`), `effort` (`reasoning`, `suffix`, `off`), `jobs` (`bracket`, `icon`), `context` (`kimi`, `left`, `gauge`), `context_color`, `hints`, `flash` (seconds a change stays visible) and `cwd_segments`. To show the output of your own script instead, set `command` (a string run through the shell, or an argv table). It receives a JSON object on standard input (session id, cwd, width, model, context, cost) and its first output line is shown. `command_replaces = true` hides the built-in segments. ```lua mare.plugin("statusline", { command = "~/bin/statusline.sh", command_timeout_ms = 500 }) ``` Background-probed segments: `changes` (`git status`), `pr` (`gh pr view`), and external `command` output run asynchronously in the background after startup becomes ready (`ui/ready`) and refresh after turns so startup never blocks on subprocess probes (`branch` is read synchronously from `.git/HEAD` on the first frame and refreshed in the background after turns). Because external `command` runs only after `ui/ready`, it does not run in headless or RPC sessions without a UI. When a probe completes, those segments update their content in place. All other segments (`mode`, `hints`, `flags`, `model`, `effort`, `context`, `cwd`, `branch`, `cost`, `quota`, `peer_allow`, `tips`, `jobs`, `workflow`, `mcp`) render synchronously from the first frame onward. To add a segment from your own plugin, use the `ui` service: `ctx.ui:status(id, { align = "right", order = 20, render = function() ... end })`. See [Writing a plugin](https://signalridge.github.io/mare/en/extend/writing-a-plugin/). ## Other appearance options | Option | Values | Effect | |---|---|---| | `border` | `rounded` (default), `single`, `double`, `thick`, `hidden` | Border of panels and popups. | | `icons` | `nerd`, `unicode`, `ascii` | Icon set (detected from the terminal when unset). Under `nerd`, callouts and fenced code block headers show Nerd Font icons (70+ language tags such as `rust`, `python`, `ts`, `go`, `lua`, `bash`, `sql`, `docker`, `yaml`). | | `prompt` | a string, default `❯` | The input prompt symbol. | | `terminal.ambiwidth` | `single`, `double` | Width of East Asian ambiguous characters, like Vim. | | `spinner` | list of glyphs, or `{ frames = {...}, still = "•" }` | Glyphs of the spinners. | | `ui.working` | `{ glyph, label, elapsed, tokens, interrupt_hint, sep, tools, interval_ms, text_throttle_ms, frames, glyphs, verbs }` | Fine-grained working indicator options (default `{ glyph = "swell", label = "glint", elapsed = "auto", tokens = true, interrupt_hint = true, sep = "dot", tools = "still", text_throttle_ms = 250 }`). | | `ui.tool_call`, `ui.stopping` | `{ spinner = "braille" }` / `{ spinner = true }` | Tool-call and stopping spinners (`false` for static dot). | | `markdown` | `{ glyphs = {...}, code_line_numbers = false }` | Markdown rendering (fenced code blocks show Nerd Font language icons automatically when `icons = "nerd"`). | | `logo` | `true`, `false`, `"compact"` | Startup logo. | | `reduce_motion` | boolean | Static text instead of animation. | | `images_protocol` | `kitty`, `iterm2`, `sixel`, `none` | Terminal image protocol. Detected when unset. | | `char_widths` | list of `{ from, to, width }` or `{ char, width }` | Display width overrides. | ```lua mare.setup { border = "single", prompt = ">", icons = "nerd", ui = { working = { glyph = "swell", label = "glint", elapsed = "auto", tokens = true, interrupt_hint = true, sep = "dot", tools = "still", text_throttle_ms = 250, }, tool_call = { spinner = "braille" }, }, = { code_line_numbers = true }, reduce_motion = true, } ``` Each leaf of `ui.working` can be configured independently: `glyph` (`swell`, `ember`, `braille`, `moon`, `phase`, `wave`, `sail`, `bullet`, `pulse`, `none`, or a key in `glyphs`), `label` (`accent`, `shimmer`, `glint`, `foam`, `dots`), `elapsed` (`auto`, `seconds`, `off`), `tokens`, `interrupt_hint`, `sep` (`dot`, `bullet`), `tools` (`still`, `spin`), `interval_ms`, `text_throttle_ms`, inline `frames` / custom `glyphs`, and `verbs` to rename each phase (`reasoning`, `responding`, `tool`, `shell`, `exploring`). Everything holds still under `reduce_motion`. The [Options](https://signalridge.github.io/mare/en/configure/options/) page has the full list with defaults. Plugin options that affect the transcript, such as `preview_lines` (lines of output shown per tool call in compact view) and `diff_fold_lines` (rows kept in a compact diff before folding, default `8`, or `false` to show full diffs), belong to the `ui` plugin: ```lua mare.plugin("ui", { preview_lines = 4, diff_fold_lines = 12 }) ``` ================================================================================ Title: The boot fragment and the `task` host plugin Section: Extend URL: https://signalridge.github.io/mare/en/extend/host-kernel/ Markdown: https://signalridge.github.io/mare/raw/en/extend/host-kernel.md Source: docs/en/extend/host-kernel.md ================================================================================ # The boot fragment and the `task` host plugin `crates/mare-kernel/lua/mare_kernel/boot.lua` builds the cordis host on `mare.task` and the root context, uses the host plugins (`task`, `loader`), and turns each plugin definition into a cordis component (`component.lua`: its owner record, its `lua/` directory, the apply's outcome for the failure and reload reports). Types: `types/mare/host/kernel.lua`. ## Primitives The boot fragment receives `prims` from Rust (`lua_env/cordis_host.rs`). Host plugins get the typed part as their config. Not listed (the boot fragment's own): `capture`, `spawn_root`, and `run_root`. | entry | | |---|---| | `handler_failed(plugin, what, err)` | report a plugin callback's error: problem line, log, `kernel/error` | | `unload_modules(name)` | drop the plugin's modules from `package.loaded` (called when its fiber unloads) | | `mark_active(name, owner \| nil, config?)` | record the active plugin instance and its effective `config` table while its fiber runs, or clear it when `owner` is `nil` | The owner, event, definition and reload tables are in [the prims types](https://github.com/signalridge/mare/blob/main/crates/mare-plugin/preset/types/mare/host/prims.lua). The rows are in [the loader host plugin](https://signalridge.github.io/mare/en/extend/host-loader/). ## Start and reload `booted.start()` and `booted.reload(name, targets)` run in the host's own context (`prims.run_root`). A reload triggered by a restricted peer or from inside a tool does not pass that caller's grant to the fibers it rebuilds. - `reload(name)` of a running plugin: `loader:replace`. If the new definition fails, the old one is put back. - Otherwise, the rows leave the tree one at a time, last row first: first the rows that are gone, then `targets`. Then the full row list builds each target again from its new definition and config. ## `task` `ctx:after(ms, fn)`, `ctx:every(ms, fn)` and `ctx:spawn(fn, ...)` start tasks owned by the caller's fiber; they are aborted when it unloads. A plugin that uses them declares `inject = { "task" }`. ## `kernel` The contracted service `kernel` (`mare_kernel.plugins.kernel`, a `mare.Service`). It replaces the old Ctx methods `plugins`, `problems`, `is_builtin`, `provides`, `reload` and `reload_barrier`; a plugin that uses it declares `inject = { "kernel" }`. `kernel:reload(name?)` takes the full reload path (Rust prepares the definitions, then the tree switches), detached from the caller, which the reload may dispose. ================================================================================ Title: The `loader` host plugin Section: Extend URL: https://signalridge.github.io/mare/en/extend/host-loader/ Markdown: https://signalridge.github.io/mare/raw/en/extend/host-loader.md Source: docs/en/extend/host-loader.md ================================================================================ # The `loader` host plugin The plugin tree runs on cordis-lua's loader (`cordis.loader`). mare wraps it in a host plugin, `mare_kernel.plugins.loader`, which the boot fragment (`boot.lua`) uses on the root context. It provides the service `loader`. Types: `types/mare/host/loader.lua`. Host plugins use only typed, documented primitives. The tables below are passed to the host plugin as its config by the boot fragment; the live `prims` tables are not globals and are not exposed as a `require`-able module (while `mare_kernel.*` source modules themselves follow the open `require` model and are internal/undeclared in `types/`). ## Config ```lua root:use(require("mare_kernel.plugins.loader"), { component = component, -- fun(name): the cordis component for a plugin name prims = prims, -- row primitives; prims.refused and prims.profile_record are read }) ``` `component(name)` is the only way the tree gets a component. An unknown name raises `module '<name>' not found:`, and the loader reports that for that row only. ## Row primitives | Primitive | Returns | |---|---| | `prims.rows()` | The rows for the current definitions and config, in load order, then one disabled row per definition the config turned off. | | `prims.refused()` | The definitions refused by the static provide check. | | `prims.profile_record(label, ms)` | Adds one entry to the startup profile (`/profile`, `--startuptime`). The loader records `plugin <name> (<origin>)` with the CPU time of each plugin's `apply`, as the old path does. | A row is `{ id, name, config, disabled, origin, path, overrides }`. `id` and `name` are the plugin name. `disabled` is set when `plugins.<name>.enabled = false` or a builtins profile turns the plugin off. The loader reads `id`, `name`, `config` and `disabled`. It keeps `origin`, `path` and `overrides` for `dump()`. A refused definition declares a service another definition already provides. It is never a row: rows are keyed by plugin name, so a refused row could stand in for the running one. `dump()` lists refused definitions after the rows, with the reason, and they never run. ## The `loader` service | Method | Used by | What it does | |---|---|---| | `loader:apply_rows(rows)` | startup, `/reload config` | The tree follows `rows`. New rows start. Removed and disabled rows are disposed, and their cleanups are awaited. A row whose config changed updates its fiber with the new config. Other fibers are left alone. A fiber that had failed before the call is updated once with its config. | | `loader:replace(name, component)` | `/reload <name>` | Replaces the running definition, and its fibers restart on the new one. If the new definition fails to apply, the old one is put back and the future raises the error. | | `loader:dump()` | `mare plugin tree`, `/plugins` | One item per row: origin, path, overrides, disabled, the fiber state, the services a pending plugin still waits for (`missing`), the services it provides and its effect count. Then the refused definitions. | `apply_rows` and `replace` return a cordis Future; `:await()` it. `missing` is read from each fiber's `_store`, the field cordis-lua's `api-core.md` lists under "Diagnostics". This is a read-only diagnostic. Nothing else in mare reads `_store`. ## `mare plugin tree` `mare plugin tree` prints `loader:dump()` as one line per plugin: id, origin, status (the fiber state, `disabled` or `refused`) and details. `mare plugin tree --json` prints the dump itself. ================================================================================ Title: Lua API Section: Extend URL: https://signalridge.github.io/mare/en/extend/lua-api/ Markdown: https://signalridge.github.io/mare/raw/en/extend/lua-api.md Source: docs/en/extend/lua-api.md ================================================================================ # Lua API The public `mare.*`, `ui.*`, and `ctx.*` functions, taken from the LuaLS definitions that ship with mare. Run `mare init` to get completion and inline documentation for all of them in your editor. > This page is generated from the code by `scripts/gen_docs.py`. Do not edit it by hand. ## ctx Defined in `types/mare/events.gen.lua`, `types/mare/services/ctx.lua`. | | | |---|---| | `ctx:on(name, listener, options)` | | | `ctx:inject(names, fn)` | A plugin's ctx (`apply(ctx, cfg)`): the cordis context (`effect`, `on`, `emit`, `inject({...}, fn)`, `get`, ...; `ctx.bus` for mare events, `ctx.policy` for decisions), with each service its definition injects as a field, and `after` / `every` / `spawn` from the `task` host plugin (`inject = { "task" }`). `inject({ names }, fn)` (Cordis): run `fn(ctx)` while the named optional services are up — a child fiber on the cordis tree, undone when one goes away or is replaced; the plugin itself does not restart. Use it for registrations into an optional service made at apply time. | | `ctx:after(ms, fn)` | Run `fn` once after `ms`; cancelled when the plugin is disposed. Errors are shown in the UI. | | `ctx:every(ms, fn)` | Run `fn` every `ms` until it returns false or the plugin is disposed. Errors are shown in the UI (the timer keeps going). | | `ctx:spawn(fn, ...)` | Run `fn(...)` as a task of this plugin, cancelled when the plugin is disposed. | | `ctx:get(name)` | The service `name` as this context reads it, or nil when it is not up (Cordis `get`: for an optional service the definition does not inject). | ## ctx.agent Defined in `types/mare/services/agent.gen.lua`. | | | |---|---| | `ctx.agent:activity()` | Synchronously capture detached agent activity state without yielding, queueing, or persisting partials. | | `ctx.agent:adopt_session(snapshot)` | Atomically install a prepared session state snapshot without yielding or emitting events. | | `ctx.agent:append(msg, opts)` | Append a message to the active conversation; returns `ok, err`. | | `ctx.agent:baseline_cut()` | Non-yielding snapshot cut of agent runtime state and active turn items. | | `ctx.agent:cancel(opts)` | Cancel or halt the active turn (optionally checking `turn_id` and/or clearing queued inputs) and return any removed queued items. | | `ctx.agent:capabilities()` | Declare feature capabilities implemented by the active agent service. | | `ctx.agent:check_session_revision(revision)` | Return false for a stale or foreign session revision token, synchronously and without mutation or events. | | `ctx.agent:continue(opts)` | Resume an interrupted turn or run queued inputs (`steer` and `follow_up`). | | `ctx.agent:delete_queued(input_id)` | Remove one queued input item by `input_id`. | | `ctx.agent:enqueue(input, owner, opts)` | Durably enqueue an input item into the active session inbox without starting a turn, returning a receipt scoped to the active session owner. | | `ctx.agent:get()` | Snapshot of current agent activity (`busy`, `turn_id`, `queued` count, `model`, `effort`, `activity`). | | `ctx.agent:interrupted()` | True when the conversation context ends mid-turn and the loop can resume via `continue()`. | | `ctx.agent:list_messages(opts)` | Current conversation messages visible to the model (optionally paginated by cursor and limit). | | `ctx.agent:list_queue()` | Queued inputs in delivery order (steer items first, then follow-ups; image metadata only). | | `ctx.agent:messages()` | Raw lossless conversation messages array for bounded in-process host inspection. | | `ctx.agent:notify(text, opts)` | Queue a notification message for the model (joins the next step while busy, or wakes a new turn when `wake = true`). | | `ctx.agent:pending_request()` | Return the interrupted request that a resume will retry, or nil. | | `ctx.agent:persist_error()` | Return the current persistence fault error message, or nil when healthy. | | `ctx.agent:prepare_commit(inbox, messages, turn_id)` | Prepare one atomic session-owned inbox/message publication; external readers use `list_queue()`. | | `ctx.agent:prompt(input, opts)` | Submit user input to the agent (queued inputs enter follow_up by default, or steer via `agent.steer`); starts a turn when idle, or handles busy state via `when_busy` (`queue` default, or `reject`). | | `ctx.agent:queue_custom(msg, mode, opts)` | Queue or append a custom message with delivery mode (`next_turn` \| `pending` \| `steer` \| `follow_up`). | | `ctx.agent:register_activity(namespace, snapshot_fn)` | Register a namespaced synchronous JSON snapshot provider owned by the caller ctx; returns an unregister disposer. | | `ctx.agent:resume_input(owner, opts)` | Un-park and start a turn for a durably queued input scoped to the active session owner. | | `ctx.agent:session_revision()` | Return an opaque provider-owned revision token for the current session state, synchronously and without mutation. | | `ctx.agent:set_messages(msgs, opts)` | Replace the active conversation message array (`notify = false` is synchronous and event-free for guarded publication). | | `ctx.agent:set_pending_request(rec, opts)` | Record an interrupted request marker found on resume so it can be retried with the same request id. | | `ctx.agent:set_queued(q)` | Restore queued inputs on session resume so they run as follow-ups. | | `ctx.agent:set_session_id(session_id)` | Bind the active session id for durable queue persistence. | | `ctx.agent:set_tool_states(states)` | Restore recorded tool call states on resume (`{ [tool_call_id] = {state, side_effect, idempotent} }`). | | `ctx.agent:steer(input, opts)` | Inject steering input into the currently running turn. | | `ctx.agent:step_participant(name, prepare, opts)` | Register a namespaced model-step participant whose prepared JSON state commits atomically before each model request. | | `ctx.agent:step_preview(name, step_id)` | Return the frozen candidate state of the active step (`step_id`), or the committed state when omitted. | | `ctx.agent:step_state(name)` | Return a detached JSON snapshot of the last committed step participant state, restored per session. | | `ctx.agent:update_queued(input_id, opts)` | Update the content and/or lane of one queued input item. | | `ctx.agent:wait(turn_id, opts)` | Block until the specified (or active) turn settles and return its `Turn` snapshot. | ## ctx.approvals Defined in `types/mare/services/approvals.gen.lua`. | | | |---|---| | `ctx.approvals:admit(cancel)` | Validate the selected reviewer within the configured review timeout. | | `ctx.approvals:delegation_services()` | Services that delegation requires even when a child changes provider configuration. | | `ctx.approvals:gate(category)` | Evaluate the independent policy gate for a category; returns a denial or nil. | | `ctx.approvals:inheritance()` | All ancestor policy ceilings plus this session's live policy, copied for delegation. | | `ctx.approvals:policy()` | Current effective approval policy. | | `ctx.approvals:register_reviewer(name, review, opts)` | Register a named approval reviewer owned by the calling ctx; automatically withdrawn on dispose. | | `ctx.approvals:request(category, action, policy, answer, cancel, opts)` | Apply the independent gate, selected reviewer, cancellation and audit lifecycle for an approval request. | | `ctx.approvals:review_required()` | Whether every request requires review under current configuration or inherited flags. | | `ctx.approvals:revision()` | Monotonic revision counter incremented whenever policy or reviewers change. | | `ctx.approvals:set(value)` | Persist a session override before changing the effective approval policy. | | `ctx.approvals:version()` | Reload-safe service incarnation plus policy/reviewer revision. | ## ctx.bus Defined in `types/mare/host/bus.lua`. | | | |---|---| | `ctx.bus:emit(event, ...)` | Notify every listener in order; a failing one is reported and the rest still run. | | `ctx.bus:emit_checked(event, ...)` | Like `emit`, but the first failing listener (or one past its timeout_ms) raises. | | `ctx.bus:bail(event, ...)` | The first listener's non-nil answer (`false` included), or nil. | | `ctx.bus:waterfall(event, value, ...)` | `value` through the listeners in order (each may pass on a replacement); a failure keeps `value`. | | `ctx.bus:waterfall_checked(event, value, ...)` | Like `waterfall`, but a failing listener raises instead of keeping `value`. | ## ctx.cells Defined in `types/mare/services/cells.gen.lua`. | | | |---|---| | `ctx.cells:cancel(cell_id)` | Cancel an active cell owned by this caller. | | `ctx.cells:get()` | Status of the caller's cell environment. | | `ctx.cells:list(opts)` | List cells owned by this caller. | | `ctx.cells:list_tools(opts)` | Discover tools currently callable from code cells, including the MCP codemode tier. | | `ctx.cells:reset()` | Cancel active cells owned by this caller and release caller-owned retained VM state. | | `ctx.cells:start(code, opts)` | Start an asynchronous script cell in this caller's scope and wait up to yield_time_ms for initial output or completion. Lua callers may pass `cancel` / `wait_cancel` returning their cancel token. | | `ctx.cells:wait(cell_id, opts)` | Wait for an active or completed cell owned by this caller, consuming newly emitted output. terminate cancels the cell and waits up to 5 s. Lua callers may pass `cancel` returning their cancel token. | ## ctx.changes Defined in `types/mare/services/changes.gen.lua`. | | | |---|---| | `ctx.changes:diffs()` | Each turn's before/after file contents and diff stats, oldest first. | | `ctx.changes:rewind(turn, opts)` | Restore workspace files to their snapshot before `turn`. | | `ctx.changes:turns()` | Recorded journal turns with modified files, oldest first. | ## ctx.commands Defined in `types/mare/services/commands.gen.lua`. | | | |---|---| | `ctx.commands:get(name)` | Current definition data of command `name` (or alias), or nil if absent. | | `ctx.commands:list()` | Registered non-alias slash commands, sorted by name (data only, no callbacks). | | `ctx.commands:register(name, opts)` | Register a slash command or alias (`alias_of`) owned by the caller; remote callers must pass `replace = true` to overwrite an existing name, and releasing a registration restores any previous definition. | | `ctx.commands:run(line, input, opts)` | Run a slash command line (optionally targeting a loaded `session_id`); returns {result?} on success and throws a coded error on failure. | ## ctx.compact Defined in `types/mare/services/compact.gen.lua`. | | | |---|---| | `ctx.compact:busy()` | Whether compaction or a branch summary is currently running. | | `ctx.compact:cancel()` | Stop a running compaction. | | `ctx.compact:measure(opts)` | Current usage: the larger of the local estimate and provider-reported usage (or a per-source breakdown table when `{ by_source = true }`). | | `ctx.compact:offload_images(opts)` | The offload stage on its own, for a provider's image_limit error. | | `ctx.compact:prepare_request(request, history)` | Measure a prepared request and compact its uniquely mapped session history when needed. The budget uses the protocol-independent request and the output cap from its resolved parameter mappings; later `provider/request` changes to the output cap are not included. | | `ctx.compact:register_stage(name, fn, opts)` | Add a stage or replace a built-in one; order comes from the `stages` option. Withdrawn when the caller is disposed or the returned disposer is called. | | `ctx.compact:run(instructions, opts)` | Compact the session's context now (`reason`: manual by default); `instructions` adds a focus to the summary. Returns `{status, tokens_before, tokens_after}` (or `{status = "summarized", tokens_before = 0, tokens_after = 0, summary, dropped}` with `summarize_only`). A failure raises `compact.not_compacted`. | | `ctx.compact:threshold(model)` | Tokens at which auto compaction triggers for a model (default: current); nil when `auto` is off or budgets are invalid. | ## ctx.context Defined in `types/mare/services/context.gen.lua`. | | | |---|---| | `ctx.context:expand_template(body, args)` | Fill a template body with shell-style split arguments ($1, $@, ${1:-default}...). | | `ctx.context:files()` | The context files read into the prompt: {path, content}. | | `ctx.context:invalidate()` | Drop the cached prompt; the next request assembles it again. | | `ctx.context:preview(model, agent, opts)` | Preview the assembled prompt with candidate sections and section diagnostics without modifying the registry. | | `ctx.context:replaced()` | Whether SYSTEM.md or the `system` option replaces the whole default prompt, else nil. | | `ctx.context:report()` | Per-source /context report table. | | `ctx.context:section(def)` | Register a prompt section (`name`, `order`, `text`, `when`, `scope`, ...); released with the caller or returned disposer. | | `ctx.context:skill_problems()` | What the last skill scan warned about or skipped: {path, message, skipped?}. | | `ctx.context:skills()` | The skills offered to the model: {name, description, path}. | | `ctx.context:suppress(name)` | Hide a section by name in every scope until released; sections registered under that name later stay hidden too. | | `ctx.context:suppress_runtime(opts)` | Hide non-required runtime sections (`runtime = true`, not `required = true`) in the matching layer until released. | | `ctx.context:system_prompt(model, agent)` | The assembled prompt (cached per model and agent); raises when it can't be built. | | `ctx.context:templates()` | Prompt templates, each registered as /name unless a command with that name exists. | | `ctx.context:variable(name, fn)` | Register a `{{name}}` for interpolated sections (name: ^[a-z][a-z0-9_]*$) until released. | ## ctx.conversations Defined in `types/mare/services/conversations.gen.lua`. | | | |---|---| | `ctx.conversations:cancel()` | Cancel the active side conversation turn without closing it. | | `ctx.conversations:close()` | Cancel and discard the active side conversation. | | `ctx.conversations:info()` | Return the open side conversation snapshot, or nil when closed. | | `ctx.conversations:start(opts)` | Start a side conversation from a committed snapshot of the current session. | | `ctx.conversations:toggle()` | Toggle focus between the main conversation and an open side conversation. | ## ctx.copy Defined in `types/mare/services/copy.gen.lua`. | | | |---|---| | `ctx.copy:align_tables(md)` | Re-pad every GFM table in Markdown text so its columns line up. | | `ctx.copy:blocks(md)` | Extract fenced code blocks from Markdown text, in order. | | `ctx.copy:last(n)` | Copy the Nth-last response (default 1); opens a code-block picker when code blocks are present. | | `ctx.copy:response(n)` | Markdown source of the Nth-last assistant response (1 = last), or nil. | | `ctx.copy:text(text, target)` | Copy text to the clipboard, reporting the path used, and emit `copy/completed`. | | `ctx.copy:write(text, lang)` | Write text to `mare-copy-<time>.<ext>` in the working directory and return the path, or nil on error. | ## ctx.fs Defined in `types/mare/services/fs.gen.lua`. | | | |---|---| | `ctx.fs:list(path)` | List directory entries filtered by the active sandbox read policy. | | `ctx.fs:read(path, opts)` | Read a file as base64, bounded by active sandbox policy and optional max_bytes. | | `ctx.fs:stat(path)` | Inspect file metadata within the active sandbox read policy. | | `ctx.fs:watch(path)` | Watch a workspace path for policy-filtered filesystem changes (emits `fs/changed`; release via `registrations.release`). | | `ctx.fs:write(path, data_base64, opts)` | Write base64 bytes to a file within writable sandbox roots and protected-path exclusions. | ## ctx.hooks Defined in `types/mare/services/hooks.gen.lua`. | | | |---|---| | `ctx.hooks:subscribe(event, opts)` | Subscribe `handle(event, mode, args)` to a bus event or policy decision point. Returns a registration removed on release or client disconnect. `prepend = true` inserts before earlier listeners (`prepend = false` keeps append order); `timeout_ms` requires `>= 1` and is clamped to the host policy timeout ceiling for remote callers. | ## ctx.images Defined in `types/mare/services/images.gen.lua`. | | | |---|---| | `ctx.images:show(content)` | Render image blocks from a message or tool-result content list when an image protocol is active. | ## ctx.jobs Defined in `types/mare/services/jobs.gen.lua`. | | | |---|---| | `ctx.jobs:background(job_id)` | Mark a job as backgrounded so completion emits a notification. | | `ctx.jobs:cancel(job_id, reason, opts)` | Request a running job to stop (SIGTERM, then SIGKILL after kill_grace_ms). | | `ctx.jobs:get(job_id, owner)` | Look up a tracked job by id (optionally scoped to `owner`), or nil. | | `ctx.jobs:list(opts)` | Background jobs in start order, optionally filtered by owner (with optional cursor pagination). | | `ctx.jobs:read(job_id, opts)` | Non-consumingly read job output starting at byte `offset`, with a trailing [status: ...] line. | | `ctx.jobs:start(opts)` | Start and track a background process job. | | `ctx.jobs:track(opts)` | Track an external handle implementing the `mare.Job` interface (sub-agents, terminals) as a job. | | `ctx.jobs:write(job_id, data, opts)` | Write stdin data to a running job (optionally closing stdin with `eof = true`). | ## ctx.kernel Defined in `types/mare/services/kernel.gen.lua`. | | | |---|---| | `ctx.kernel:begin_session_switch(opts)` | begin an atomic session identity switch: reserve target `session_id` (if given) and revoke session-only trust before publish; `handle:commit(session_id)` automatically marks any active session export call as committed | | `ctx.kernel:get_caller()` | return the opaque caller identifier of the running request | | `ctx.kernel:is_builtin(name)` | whether plugin `name` is a built-in | | `ctx.kernel:list_sessions()` | list currently open sessions across managed runtimes (or this standalone host) | | `ctx.kernel:mark_call_committed()` | mark the running service export call as past its commit boundary | | `ctx.kernel:plugin_row(name)` | plugin `name`'s row in the plugin list, 0 if it has none | | `ctx.kernel:plugins()` | the plugin rows: name, origin, active, overrides | | `ctx.kernel:problems()` | the current problem lines | | `ctx.kernel:provides(name)` | whether the caller's fiber provides `name` | | `ctx.kernel:reload(name)` | reload plugin `name`, or all plugins | | `ctx.kernel:reload_barrier()` | wait until no reload is running | | `ctx.kernel:reload_generation()` | the running (or latest) reload's generation: one more per plugin reload and per config row update | | `ctx.kernel:request_lease(cancel)` | acquire the exclusive per-host request/reload lease bound to the caller owner lifetime | | `ctx.kernel:session_capacity()` | whether this host orchestrates a single session runtime ("single") or multiple concurrent runtimes ("multi") | | `ctx.kernel:session_epoch()` | the current event stream session epoch | | `ctx.kernel:stalled()` | the plugins stuck loading, unloading or waiting for `stall_ms` or longer; observed, never aborted | ## ctx.llm Defined in `types/mare/services/llm.gen.lua`. | | | |---|---| | `ctx.llm:active_credential(provider, env_names)` | Return the winning credential descriptor for `provider` (`init.lua` > `auth.json` > env), or nil. | | `ctx.llm:active_scope()` | Return the currently active effort scope name, or nil. | | `ctx.llm:alias_target(name)` | Return what a model alias points to, or nil. | | `ctx.llm:api_key(provider, env_names)` | Resolve the API key string for `provider` from config, `auth.json`, or `env_names`, or nil. | | `ctx.llm:api_key_source(name, envs)` | Describe where a provider's API key would come from (never returns the secret), or nil. | | `ctx.llm:apply_params(req, wire, opts)` | Write resolved request parameters into `wire.body` and `wire.headers`. | | `ctx.llm:auth_get(key)` | Read a stored credential record from `auth.json` (`version` is reserved). | | `ctx.llm:auth_keys(prefix)` | Stored credential key names in `auth.json`, optionally filtered by literal prefix; never returns secret values. | | `ctx.llm:auth_set(key, value, opts)` | Atomically write or delete a credential record in `auth.json`; returns whether committed. | | `ctx.llm:auth_status(provider)` | Return JSON-safe masked credential and directory status for all providers (or one provider). | | `ctx.llm:base_url(provider, default)` | Return the resolved base URL for `provider` (falling back to `default`), or nil. | | `ctx.llm:cancel_side_requests(session_id)` | Optional lifecycle extension: cancel auxiliary LLM requests belonging to `session_id`. | | `ctx.llm:capabilities(ref)` | Return a detached JSON-safe capability descriptor for `ref` (default current model), or `nil, err`. | | `ctx.llm:clamp_effort(model, effort)` | Clamp `effort` to the levels supported by `model`, or return nil. | | `ctx.llm:classify(err, cancelled)` | Classify a provider error table or message into `(kind, retryable)`. | | `ctx.llm:clear_scope(scope, model, opts)` | Clear a scoped effort override (`save = false` hides it for this session only). | | `ctx.llm:close_response(resp)` | Close a provider HTTP response immediately to release its connection. | | `ctx.llm:compact_remote(opts)` | Run provider-side compaction; returns `{items, model_id, provider_id}` or `nil, err, kind`. | | `ctx.llm:complete(req)` | Non-streaming convenience wrapper around `stream`; returns the final assistant `mare.Message`. | | `ctx.llm:constrain_request(req)` | Apply all registered tool declaration constraints to `req` and return the constrained request copy. | | `ctx.llm:constrain_tools(fn)` | Register a monotone tool declaration constraint applied once per model request; returns a remove disposer. | | `ctx.llm:credential_sources(provider)` | Return all credential sources present for `provider`, active first (never returns secrets). | | `ctx.llm:current()` | Return the currently selected `mare.Model`, or nil. | | `ctx.llm:cycle_param(name, dir)` | Advance a `cycleable` parameter to the next offered option (`dir` +1 / -1); returns `value, err`. | | `ctx.llm:define_params(rule, layer)` | Register model parameter definitions and wire mappings owned by the calling plugin. | | `ctx.llm:describe_wire(name)` | Return a copy of the registered wire's `mare.WireDescribe`, or nil. | | `ctx.llm:effort()` | Return the effective effort clamped to the current model (including active_scope override if set). | | `ctx.llm:effort_options(model)` | Return every effort value defined for `model` (built-in levels plus rule additions), or nil. | | `ctx.llm:efforts()` | Return the built-in effort levels, lowest first ("off" ... "max"). | | `ctx.llm:explain_lines(ref)` | Format human-readable explanation lines for the effective parameters of `ref`. | | `ctx.llm:explain_params(ref)` | Return the effective parameters, source layers, wire fields, and options for `ref`. | | `ctx.llm:fingerprint(req)` | Compute the crash-guard fingerprint key of a model request. | | `ctx.llm:get_model(ref)` | The session's current model, or with ref any model the providers resolve (hidden ones and ids a provider serves without listing them included); never changes the selection. | | `ctx.llm:get_selection()` | Return the mutable session selection snapshot (`model`, `default_model`, `recent`, `params`) for resume comparison. | | `ctx.llm:global_effort(model)` | Return the global unscoped effort clamped to `model`, ignoring `active_scope`. | | `ctx.llm:has_api_key(provider, env_names)` | Whether an API key is available for `provider` without returning the secret. | | `ctx.llm:has_auth(key)` | Whether `auth.json` holds a credential under `key` without returning the secret. | | `ctx.llm:has_credentials()` | Whether at least one provider has usable credentials (or the current model requires none). | | `ctx.llm:http_error(label, resp, opts)` | Build a classified provider error table from a non-2xx HTTP response. | | `ctx.llm:identify_key_provider(key)` | Identify a registered login-capable provider from a pasted API key using declared `key_prefixes`, or nil when unmatched or ambiguous. | | `ctx.llm:invalidate_api_key(provider)` | Drop the cached API key for a key-helper provider so the next call re-runs the command. | | `ctx.llm:invalidate_catalog(name)` | Invalidate in-memory catalog models for `name` (or all providers when omitted). | | `ctx.llm:list_auth_keys(prefix)` | Stored credential key names in `auth.json`, optionally filtered by literal prefix; never returns secret values. | | `ctx.llm:list_models()` | Every visible model with its abilities, sorted by ref. | | `ctx.llm:list_providers()` | Providers and their masked login state; never a secret value. | | `ctx.llm:logged_in()` | List providers that currently have credentials stored in `auth.json`. | | `ctx.llm:login(provider, opts)` | Run a provider's login. Without key the flow is interactive and needs a connected UI; Lua callers may pass their own say/ask/choose functions. | | `ctx.llm:login_api_key(name, title, lio)` | Run an interactive API-key login flow for provider `name`. | | `ctx.llm:login_io(lio)` | Complete a login I/O table with the connected UI's `say`, `ask`, and `choose` callbacks. | | `ctx.llm:logout(provider)` | Remove every stored credential of a provider (revoked first where possible); kept lists the environment and config sources that cannot be removed here. | | `ctx.llm:model_default(model, field)` | Return the default value for `field` declared via the provider's `model_defaults` globs. | | `ctx.llm:model_sources(ref)` | Return per-field model metadata provenance (`user`, `measured`, `server`, `static`, `models_dev`, `default`), or nil. | | `ctx.llm:models()` | Return all known models across registered providers. | | `ctx.llm:no_browser()` | Whether this frontend cannot open a browser (headless, SSH), selecting device login flows. | | `ctx.llm:note_param(model, note)` | Record a parameter adjustment note and emit `llm/params-adjusted`. | | `ctx.llm:param_list(model)` | Return a model's parameter definitions in order. | | `ctx.llm:params_log()` | Return recent parameter adjustments (oldest first). | | `ctx.llm:prepare(model, opts)` | Prepare `model` (default current) via credential refresh/retry and check readiness; returns `ready, reason?`. | | `ctx.llm:prepare_request(args)` | Run every registered readiness step's `prepare` hook in order; raises on the first failure. | | `ctx.llm:provider(name)` | Look up a guarded provider accessor by name (projecting I/O, tracking side requests and usage, and invalidated on replace/unload), or nil. | | `ctx.llm:provider_config(name)` | Return a provider's merged config (`mare.config.providers[name]`), or nil; may carry secrets. | | `ctx.llm:provider_from_config(provider_id, cfg, opts)` | Convert a user `providers.<id>` config table into a validated `mare.Provider` declaration, or `nil, err`. | | `ctx.llm:providers()` | Return data descriptors for every registered provider (excluding functions). | | `ctx.llm:raw_effort()` | Return the raw unclamped effort setting, or nil. | | `ctx.llm:readiness(name, def)` | Register a request-readiness step (`prepare` / `ready`) ordered by `def.order`; returns a dispose function. | | `ctx.llm:ready(model)` | Synchronously check readiness of `model` (default current); returns `ready, reason?` without sending requests or refreshing auth. | | `ctx.llm:recent()` | Return recently chosen model refs, most recent first. | | `ctx.llm:refresh_catalog(opts)` | Refresh provider model lists merged with `models.dev` metadata. | | `ctx.llm:refresh_credential(provider, key, refresh_fn, opts)` | Refresh a stored credential under the auth lock with single-flight coordination per key. | | `ctx.llm:refresh_models(name, opts)` | Fetch a provider's model catalogue now. | | `ctx.llm:register_provider(opts)` | Register an LLM provider (`provider`, `default_model?`, `models?`, `replace?`) and optional remote `stream` callback; released on disposer/release or disconnect. | | `ctx.llm:register_providers(entries)` | Lua-only: register multiple LLM providers in one batch and emit `llm/providers-changed` once; valid entries are registered even if others fail (each invalid entry is reported in the second return value and as a plugin problem); returns a single disposer releasing all registered entries. | | `ctx.llm:register_wire(spec_or_name, spec)` | Register a spec-based wire protocol (`register_wire(spec)` or `register_wire(name, spec)`); dropped on dispose. | | `ctx.llm:remember_param(ref, name, value)` | Persist a parameter value for model `ref` in `state.json` `model_params`. | | `ctx.llm:request_ready(args)` | Run every registered readiness step's `ready` hook in order; returns the first non-allow vote or nil. | | `ctx.llm:reset_session_effort()` | Fallback to the default effort when a session effort cannot be restored. | | `ctx.llm:reset_session_model()` | Fallback to the default model when a session model cannot be restored. | | `ctx.llm:resolve(ref)` | Resolve a model reference string (`provider/id` or alias) to a `mare.Model`, or nil. | | `ctx.llm:resolve_params(model, opts)` | Resolve every parameter's effective value, source layer, and notes for `model`. | | `ctx.llm:restore_selection(opts)` | Restore session model and/or effort from history without budget admission or persisting defaults; emits checked change events to preserve the poison barrier. | | `ctx.llm:route_of(model)` | Return `(route, source, wire_route, error, auth)` for `model` (default current). | | `ctx.llm:scoped_effort(scope, model)` | Return the effort clamped to `model` for `scope`. | | `ctx.llm:set_active_scope(scope, opts)` | Set or clear the active effort scope name. | | `ctx.llm:set_effort(effort, opts)` | Set the reasoning effort of the current model. target session\|global (default global) decides whether it is remembered; scope_name names an override scope; also_global updates the unscoped value as well. | | `ctx.llm:set_model(ref, opts)` | Select a model after admitting its context budget; target session keeps the default, global (the default) also saves it. A compaction error keeps the old selection. | | `ctx.llm:set_param(name, value, opts)` | Set a parameter of the current model for this session; returns `used, err`. | | `ctx.llm:side_requests_pending(session_id)` | Optional lifecycle extension: whether auxiliary LLM requests are still pending for `session_id`. | | `ctx.llm:status_lines()` | Format one credential status line per provider plus warnings for overridden sources. | | `ctx.llm:stream(req, sink)` | Execute a streaming LLM request with retries, idle watchdog, and fallback handling, returning the final `mare.Message`. | | `ctx.llm:stream_error(label, e, opts)` | Build a classified error table from a provider's mid-stream error event. | | `ctx.llm:subagent_params(model_ref)` | Return the resolved parameter layer a sub-agent on `model_ref` starts with, or nil. | | `ctx.llm:supports_remote_compact(model)` | Whether `compact_remote` is supported for `model` (default: current model). | | `ctx.llm:text_of(msg)` | Extract concatenated visible text content from a `mare.Message`. | | `ctx.llm:transform_messages(messages, model, tools, policy)` | Convert message history into the form `model` expects without mutating the source history. | | `ctx.llm:wire(name)` | Look up registered wire `name`; returns `(stream_fn, owner_plugin)` or nil. | | `ctx.llm:wire_owner(name)` | Return the plugin name that owns or declares wire `name`, or nil. | ## ctx.mcp Defined in `types/mare/services/mcp.gen.lua`. | | | |---|---| | `ctx.mcp:catalog(tier)` | Prepare/discover one exposure tier using lazy connection and tool registration (default `codemode`). | | `ctx.mcp:connect(server)` | Connect one configured MCP server and return its status. | | `ctx.mcp:get_prompt(server, name, arguments)` | Expand a prompt on a configured MCP server. | | `ctx.mcp:list_prompts(opts)` | Prompts exposed by connected MCP servers (or one named server). | | `ctx.mcp:list_resources(opts)` | Resources and resource templates exposed by connected MCP servers (or one named server). | | `ctx.mcp:list_servers()` | Configured MCP servers and their current connection status (never connects). | | `ctx.mcp:list_tools(opts)` | Tools discovered from configured MCP servers (or one named server). | | `ctx.mcp:read_resource(server, uri)` | Read one MCP resource URI from a server. | | `ctx.mcp:reconnect(server)` | Reconnect one configured MCP server and return its status. | ## ctx.message Defined in `types/mare/services/message.gen.lua`. | | | |---|---| | `ctx.message:append(opts)` | Append a custom message that enters model context while honoring display, delivery, and optional `request_id` idempotency. | | `ctx.message:get_type(custom_type)` | Look up the normalized active spec for a registered custom message type (Lua-only). | | `ctx.message:list_types()` | List currently registered custom message types in sorted name order. | | `ctx.message:register_type(type, opts)` | Register a custom message type with optional validation and render callbacks; returns a disposer (`registration_id` over RPC). | ## ctx.options Defined in `types/mare/services/options.gen.lua`. | | | |---|---| | `ctx.options:get(keys, opts)` | Read effective options (or descriptors when opts.describe is true) with live service overrides and shared sensitive-path redaction. | | `ctx.options:set(values, opts)` | Validate and transactionally commit a batch of option updates (core options, llm model/effort, and plugins.<plugin>.<option>) with full rollback on refusal. | ## ctx.permissions Defined in `types/mare/services/permissions.gen.lua`. | | | |---|---| | `ctx.permissions:add_rules(rules)` | Add a rule source owned by the calling plugin (removed when the caller is disposed). | | `ctx.permissions:check(call, info)` | Evaluate the vote the permissions plugin casts for a tool call (for UIs and tests). | | `ctx.permissions:commit_request(call)` | Recheck and commit a previously resolved structured permission request immediately before execution. | | `ctx.permissions:describe(name)` | Return the display metadata of a built-in or configured preset, or nil if unknown. | | `ctx.permissions:describe_request(call, expected)` | Describe a frozen call's structured permission request without granting it. | | `ctx.permissions:get()` | Current active permission preset and policy revision for this session (`rules` and `grants` are included for primary/in-process callers and omitted for peer callers). | | `ctx.permissions:grants()` | Detached snapshot of this turn's and session's granted permission profiles. | | `ctx.permissions:is_partial()` | Whether the active sandbox backend cannot enforce network restrictions requested by the preset. | | `ctx.permissions:list()` | Available permission presets (built-in and configured) with display metadata and active indicator. | | `ctx.permissions:policy_revision()` | Monotonic revision counter incremented whenever permission policy or rules change. | | `ctx.permissions:preset()` | Current sandbox preset ("off" when the host policy is unavailable). | | `ctx.permissions:presets()` | List available permission preset names. | | `ctx.permissions:request(profile, opts)` | Request structured permissions through the ordinary tool policy, approval, and execution chain. | | `ctx.permissions:resolve_request(call, constraints, scope, expected)` | Intersect approval constraints with a frozen permission request and current policy. | | `ctx.permissions:rule_verdict(call, info)` | What configured and remembered rules alone decide about a call (excluding session-only rules), or nil. | | `ctx.permissions:rules()` | Effective permission rules: `init.lua` rules, persisted rules, and session rules. | | `ctx.permissions:set(name, opts)` | Switch the active permission preset (`confirm` asks before the first switch to full access); returns the updated permission state or raises a coded error. | ## ctx.plugins Defined in `types/mare/services/plugins.gen.lua`. | | | |---|---| | `ctx.plugins:check(names)` | Fetch and compare plugin revisions without moving checkouts or modifying locks. | | `ctx.plugins:choose_plugins()` | Offer the optional plugins, install selected packages, and return the outcome; nil when the offer is not due. | | `ctx.plugins:install(name, opts)` | Install a catalog plugin by short name or sync a declared source; raises `plugins.failed` on error. | | `ctx.plugins:list(kind)` | Declared/installed packages, parsed `mare-plugin.toml` manifests, and resource directories. | | `ctx.plugins:news()` | Show NEWS.md sections for mare / enabled plugins whose version changed since last seen. | | `ctx.plugins:uninstall(name, opts)` | Uninstall a catalog plugin by short name or clean an unused source; raises `plugins.failed` on error. | | `ctx.plugins:update(name, opts)` | Update declared git packages to their newest allowed revision (`update`); raises `plugins.failed` on error. | ## ctx.policy Defined in `types/mare/host/policy.lua`. | | | |---|---| | `ctx.policy:voter(point, fn, opts)` | Register a voter for decision point `point`; an effect of the caller's fiber (it goes with it). The voter gets the decision's arguments (frozen) and returns nil (no objection), "allow", "deny", "ask" or a vote table. | | `ctx.policy:rewriter(point, fn, opts)` | Register a rewriter for rewrite point `point` (`tool/rewrite`): it gets a copy of the call with the arguments so far and returns nil (keep) or a table of new arguments. | | `ctx.policy:decide(point, args, options)` | Decide `point` over `args`: the voters in order, the first deny stops, an error, timeout or invalid vote is a deny. Returns the folded decision `{decision, reason?, reasons, grant?, ...}`. | | `ctx.policy:rewrite(point, call)` | Rewrite `call` through `point`'s rewriters: returns the rewritten `arguments` table directly, or raises a structured `mare.Error` (`policy.rewrite_refused`, with `message` set to the failure reason) when any rewriter refuses, times out, or returns a non-table value. | | `ctx.policy:epoch()` | The policy epoch: it moves when what a decision would answer may change (an approval's fingerprint). | | `ctx.policy:has_voters(point)` | Whether any voter (rewriter) takes part in `point` now. | ## ctx.proc Defined in `types/mare/services/proc.gen.lua`. | | | |---|---| | `ctx.proc:kill(opts)` | Terminate an owned running process and its process group. | | `ctx.proc:resize(opts)` | Resize the PTY of an owned process started with tty = true. | | `ctx.proc:spawn(opts)` | Start a sandboxed piped or PTY child process bound to the caller lifecycle. | | `ctx.proc:write(opts)` | Write base64 bytes to stdin or PTY of an owned process, optionally closing piped stdin. | ## ctx.query Defined in `types/mare/services/query.gen.lua`. | | | |---|---| | `ctx.query:call(operation, arguments, opts)` | Run an in-process query operation inside an ephemeral-read-only sandbox rooted at the active execution context's cwd, or at `mare.cwd` when called directly from Lua without an active `mare.exec.current()`. Lua callers may pass `cancel`, a function returning their cancel token or nil. | | `ctx.query:list_providers()` | Registered query providers and the operations they serve, sorted by name. | | `ctx.query:register(name, def)` | Register capability operations owned by this caller; removed automatically on disposal. Paginated results return next_cursor; subsequent requests receive cursor. | | `ctx.query:supports(operation)` | Whether a registered in-process provider serves this operation. | ## ctx.review Defined in `types/mare/services/review.gen.lua`. | | | |---|---| | `ctx.review:run(target)` | Run an isolated read-only code review for `target` and return findings or `nil, err`. | | `ctx.review:viewer(only)` | Open the interactive change diff viewer, optionally narrowed to `only`. | ## ctx.session Defined in `types/mare/services/session.gen.lua`. | | | |---|---| | `ctx.session:add_record(kind, data, opts)` | Append a custom plugin record outside the model message tree. | | `ctx.session:add_workspace_dirs(dirs)` | Atomically validate, persist, and publish additional workspace directories. | | `ctx.session:append_compaction(summary, first_kept_msg, tokens_before, details, extra)` | Record a compaction entry and return the updated message context or `nil, err`. | | `ctx.session:append_prune(map, meta)` | Record a message-content prune entry and return the updated message context or `nil, err`. | | `ctx.session:archive(session_id)` | Archive a saved inactive session (and its child agent sessions) by id, unique prefix, or path. | | `ctx.session:available()` | Whether the session store is usable now (`false, reason` under `--no-session`, in a child agent, or during a persistence fault). | | `ctx.session:baseline_cut()` | Non-yielding snapshot cut of in-memory session entries. | | `ctx.session:child(opts)` | Open a sub-session transcript handle under `<session dir>/agents/<run_id>/` owned by the caller. | | `ctx.session:children(run_id)` | List sub-session transcript files, newest run first. | | `ctx.session:claim_operation(identity, cancel)` | Claim or replay a generic idempotent operation; concurrent duplicates wait on the same writer. | | `ctx.session:close(session_id, opts)` | Unload the active session runtime and release its lock without exiting the host. | | `ctx.session:commit(batch, opts)` | Atomically append accepted user messages and the remaining identified inbox. | | `ctx.session:commit_step(record, messages, opts)` | Atomically commit one model step's `agent/step-state` record and validated context disclosure messages. | | `ctx.session:create(opts)` | Create a new idle session runtime (optionally named, in cwd, or idempotent by request_id). | | `ctx.session:delete(session_id)` | Permanently delete a saved inactive session (and its child agent sessions) by id, unique prefix, or path. | | `ctx.session:entries(opts)` | Return session journal entries (`expand = true` expands compacted/pruned views). | | `ctx.session:entry_id(msg)` | Return the session entry id of a message in the current context, or nil when unknown. | | `ctx.session:file_changes()` | Return files edited by tools in this session (`old`/`new` content or `false` when absent). | | `ctx.session:fork(opts)` | Create a new session forked from an active or saved session (optionally before an item). | | `ctx.session:get(session_id)` | Fetch one session snapshot by id, unique prefix, or path. | | `ctx.session:get_item(opts)` | Read one semantic item by session_id and item_id, inline or UTF-8 chunked, with optional neighbors. | | `ctx.session:info()` | Return live session identity, path, leaf entry id, message count, and status flags. | | `ctx.session:label_item(label, opts)` | Set or clear a label on a session entry (defaults to the current leaf). | | `ctx.session:leaf()` | Return the id of the current session leaf entry, or nil before the first message. | | `ctx.session:list(opts)` | List saved sessions in the index, newest first. | | `ctx.session:list_items(opts)` | List semantic items of the open session, optionally filtered by branch, item type, or order. | | `ctx.session:list_records(kind, opts)` | List custom plugin records of the given kind in the open session. | | `ctx.session:live_snapshot()` | Return a detached live snapshot of the active session for step-bounded history queries, or nil. | | `ctx.session:load(opts)` | Load an existing session by session_id, unique prefix, name, or (for primary) path. | | `ctx.session:load_transcript(path, title, opts)` | Open a session transcript file in the live transcript viewer. | | `ctx.session:on_drain(fn)` | Register a pre-switch session resource drain callback owned by the caller; returns a release disposer. | | `ctx.session:operation_receipt(identity)` | Read-only lookup of a committed generic operation receipt without claiming or mutating state. | | `ctx.session:path_to(leaf_entry_id)` | Return the branch path of entries leading to `leaf_entry_id` (default: current leaf). | | `ctx.session:persist_message(opts)` | Persist one conversation message synchronously to the session journal. | | `ctx.session:prepare_children()` | Ensure the parent session header exists before recording sub-agent transcripts. | | `ctx.session:prepare_fork()` | Drain side requests, flush the active journal, and return `{ path, images? }` for a multi-runtime fork. | | `ctx.session:record_request(opts)` | Record an agent/request marker synchronously. | | `ctx.session:record_request_aborted(opts)` | Record an agent/request-aborted marker synchronously. | | `ctx.session:record_request_end(opts)` | Record an agent/request-end marker synchronously. | | `ctx.session:record_run_end(opts)` | Record an agent/run-end fork boundary marker durably. | | `ctx.session:record_tool_state(opts)` | Record one tool execution phase marker synchronously. | | `ctx.session:release_operation(claim, reason)` | Release an uncommitted operation claim and wake duplicate waiters without changing durable state. | | `ctx.session:rewind(opts)` | Move the active session leaf back before an item (optionally summarizing or restoring files). | | `ctx.session:search(opts)` | Full-text and metadata search across persisted and live sessions in the active workspace. | | `ctx.session:search_items(opts)` | Search matching semantic items inside one session under workspace policy. | | `ctx.session:set_default_sandbox_mode(spec)` | Retain the configured default sandbox policy for new or unrecorded resumed sessions without changing the current policy. | | `ctx.session:set_leaf(entry_id)` | Move the session leaf to `entry_id` (`nil` = before the first message) and return the new context or `nil, err`. | | `ctx.session:set_sandbox_mode(spec)` | Switch this session's sandbox policy, log it in the session, and emit `sandbox/changed`. | | `ctx.session:short_id(session_id)` | Return the shortest unique prefix (8+ characters) of a session id in the index. | | `ctx.session:snapshot(opts)` | Create a persisted fork snapshot of an active or saved session without changing the active session target or cancelling running turns. | | `ctx.session:snapshot_context(opts)` | Build a normalized SES-FORK context snapshot without switching or modifying the source session. | | `ctx.session:switch(opts)` | Switch the active session in-place on a single-runtime host (`new`, `load`, or `fork`). | | `ctx.session:switching()` | True while a session switch is preparing or finishing, or after an indeterminate failure. | | `ctx.session:trace(session_id)` | Trace ancestor and descendant session lineage under workspace policy. | | `ctx.session:trace_item(opts)` | Trace the containing entry and compaction surface for one semantic item. | | `ctx.session:transition(spec, opts)` | Orchestrate a clean-context (`new`) or `workspace` session transition. | | `ctx.session:unarchive(session_id)` | Restore an archived session (and its child agent sessions) by id, unique prefix, or path. | | `ctx.session:update(name, opts)` | Rename the open session (optionally guarded by expected_revision) and return its Session snapshot. | ## ctx.spill Defined in `types/mare/services/spill.gen.lua`. | | | |---|---| | `ctx.spill:delete(spill_id)` | Invalidate and delete a session-owned spill object. | | `ctx.spill:delete_owned(session_id, spill_id)` | Delete a spill object owned by an explicit `session_id` (Lua-only). | | `ctx.spill:list_backends()` | Registered spill storage backends, with which one is currently selected. | | `ctx.spill:read(spill_id, opts)` | Read a UTF-8 text page (default) or base64 byte page (`encoding = "base64"`) from a session-owned spill object. | | `ctx.spill:read_bytes(session_id, spill_id, opts)` | Read raw binary bytes owned by an explicit `session_id` (Lua-only; used by UI image materializers). | | `ctx.spill:read_owned(session_id, spill_id, opts)` | Read UTF-8 text owned by an explicit `session_id` (Lua-only). | | `ctx.spill:register(name, backend)` | Register a named spill backend; removed automatically on disposal. | | `ctx.spill:save(opts)` | Persist UTF-8 text (`content`) or strict padded base64 bytes (`data_base64`, max 8 MiB decoded) in the active session's spill storage. | | `ctx.spill:save_bytes(session_id, bytes, opts)` | Save raw binary bytes (max 8 MiB) owned by an explicit `session_id` (Lua-only; includes host `path`). | | `ctx.spill:save_owned(session_id, content, opts)` | Save UTF-8 text owned by an explicit `session_id` (Lua-only; includes host `path`). | ## ctx.status Defined in `types/mare/services/status.gen.lua`. | | | |---|---| | `ctx.status:get()` | The current unified agent status. | ## ctx.subagent Defined in `types/mare/services/subagent.gen.lua`. | | | |---|---| | `ctx.subagent:cancel(subagent_id)` | Request cancellation of a subagent and its descendants. | | `ctx.subagent:drain()` | Close admission and wait for the current session's subagents and completion notices. | | `ctx.subagent:get(subagent_id)` | Get a subagent by its subagent_id (or unique name). | | `ctx.subagent:list(opts)` | List subagents started in this host (optionally paginated by cursor and limit). | | `ctx.subagent:list_types()` | List current subagent type definitions in bytewise name order. | | `ctx.subagent:register_type(definition, opts)` | Register a session-owned subagent type. Names use ASCII letters, digits, underscore, hyphen or dot; tool lists are dense, nonempty-string arrays without duplicates. | | `ctx.subagent:start(opts)` | Start an isolated child subagent and return its subagent info. | | `ctx.subagent:steer(subagent_id, text)` | Deliver steering input to a running subagent. | | `ctx.subagent:wait(subagent_id, opts)` | Wait for a subagent to finish (non-consuming; timeout or cancellation does not cancel the child). | ## ctx.terminal Defined in `types/mare/services/terminal.gen.lua`. | | | |---|---| | `ctx.terminal:close(opts)` | Stop and close an owned PTY session cleanly. | | `ctx.terminal:create(opts)` | Create an owner-bound PTY session; automatically closed when the caller context or RPC connection ends. | | `ctx.terminal:list()` | List PTY sessions owned by the caller connection or plugin. | | `ctx.terminal:read(opts)` | Read incremental `output_offset` or VT-paged output from an owned PTY, capped at `max_bytes` bytes. | | `ctx.terminal:resize(opts)` | Resize an owned PTY window. | | `ctx.terminal:send(opts)` | Send input bytes/text to an owned PTY and optionally wait for output/exit, capped at `max_bytes` bytes. | | `ctx.terminal:signal(opts)` | Deliver a signal to the foreground process group of an owned PTY. | ## ctx.theme Defined in `types/mare/services/theme.gen.lua`. | | | |---|---| | `ctx.theme:cancel_preview()` | End the current preview. | | `ctx.theme:get()` | The active theme snapshot. | | `ctx.theme:inspect()` | Builtin, dynamic, inactive and override-only style tokens. | | `ctx.theme:list()` | Installed and registered themes, sorted by name. | | `ctx.theme:preview(theme)` | Preview a theme. Affects rendering only, never the preference; ends with its caller. | | `ctx.theme:register(definition)` | Register a theme owned by the caller. Duplicate or invalid definitions fail without changing state; releasing the registration removes only it, and releasing the selected theme restores auto. | | `ctx.theme:register_override(layer_id, styles)` | An owned style layer; later layers win, config.theme and explicit ui.style win over layers. Replacing a layer id keeps one layer; an older registration cannot remove its replacement. | | `ctx.theme:select(theme, opts)` | Validate, optionally save atomically, then publish the selection. save defaults to false (process only); init.lua still wins on the next start. | ## ctx.tools Defined in `types/mare/services/tools.gen.lua`. | | | |---|---| | `ctx.tools:bind_declarations(declarations)` | Bind the tool declarations returned for a model request; returns opaque tokens and bound declarations. | | `ctx.tools:capabilities()` | Declare feature capabilities implemented by the active tools service. | | `ctx.tools:command(def)` | Register a declarative command tool (`mare.CommandTool`). | | `ctx.tools:concurrency_safe(call)` | Whether tool call `call` is safe to run concurrently with adjacent calls. | | `ctx.tools:cwd()` | Current working directory used by tool execution. | | `ctx.tools:definitions(model, names)` | Build wire-ready tool declaration tables for `model` (optionally filtered to `names`). | | `ctx.tools:disable(name)` | Disable tool `name` for this session. | | `ctx.tools:edit_mode(model)` | Active edit tool strategy for `model` (`apply_patch` or `replace`). | | `ctx.tools:enable(name)` | Re-enable a previously disabled tool `name`. | | `ctx.tools:env_policy()` | Return the `{env_include, env_exclude}` filter for child processes. | | `ctx.tools:execute(call, opts)` | Run a tool call through the guarded rewrite, validation, policy vote, approval, and sandbox execution pipeline. | | `ctx.tools:executor(exposure)` | Look up the registered executor backend for an exposure kind, or nil. | | `ctx.tools:fs_commit(path, content, cur, tool, opts)` | Atomic, version-checked file write following `fs_guard`. | | `ctx.tools:fs_guard(path, verb, tool)` | Pre-write guard for edit/write tools: checks read-before-edit and dispatches `fs/edit-intent` or `fs/write-intent`. | | `ctx.tools:get(name)` | Return the registered tool definition for `name`, or nil. | | `ctx.tools:has_dynamic_admission()` | Whether any registered tool carries dynamic admission hooks. | | `ctx.tools:invalidate()` | Invalidate cached tool declaration snapshots. | | `ctx.tools:is_disabled(name)` | Whether tool `name` is currently disabled. | | `ctx.tools:list()` | Return all registered tool definitions. | | `ctx.tools:observation(path)` | Return the latest read-before-edit observation record for `path`, or nil. | | `ctx.tools:observe(path, data)` | Record that the agent has observed `path` (with optional read `data`); emits `fs/observed`. | | `ctx.tools:output_channel()` | Open an optional streaming output channel owned by the tools service, or `nil, err`. | | `ctx.tools:process_env()` | Return `MARE_*` environment variables passed to child tool processes. | | `ctx.tools:readonly(name)` | Whether the named tool is declared read-only. | | `ctx.tools:register(name, opts)` | Register a tool owned by the caller; released on disposer/release or disconnect. Remote registrations force `unconfined = true` and dispatch `execute(args, ctx)` via `callback.call`. | | `ctx.tools:register_executor(executor_id, definition)` | Register a named tool executor backend owned by the calling ctx. | | `ctx.tools:register_search_source(definition)` | Register a search source prepared before `tool_search` reads the deferred catalog. | | `ctx.tools:revision()` | Monotonic tool registry revision counter. | | `ctx.tools:send_output(channel, blocks, opts)` | Send structured output blocks over a channel returned by `output_channel`. | | `ctx.tools:shadow(name, def)` | Re-register a copy of a tool returned by `get`; revoked with its exact parent version. | | `ctx.tools:shell()` | Return the default shell configuration (`mare.ShellConfig\|nil, err?`) for model commands. | | `ctx.tools:shell_command(cmd)` | Build `(shell, args, input?)` for executing a shell command string. | | `ctx.tools:side_effect(name)` | Return `(side_effect, idempotent, unconfined)` classification for tool `name`. | | `ctx.tools:snippets(model)` | Prompt snippets for tools enabled for the given model, in registration order. | | `ctx.tools:touch()` | Bump the tool registry generation (for example after deferred tool loading changes). | | `ctx.tools:with_file_lock(paths, fn)` | Run `fn` while holding the in-process file mutation locks for `paths` in sorted realpath order. | ## ctx.ui Defined in `types/mare/services/ui.gen.lua`. | | | |---|---| | `ctx.ui:action(name, fn, opts)` | Register a named key action with optional default keys; removed when the caller is disposed. | | `ctx.ui:artifact_image(artifact, opts)` | Bind a saved output image artifact to the current session epoch and return a renderable `mare.Node`. | | `ctx.ui:call_keymap(context, key, action)` | Dispatch a key sequence or named keymap action in the session runtime. | | `ctx.ui:cancel_markdown(document_id)` | Cancel outstanding presenter work for a Markdown document and fall back to source. | | `ctx.ui:card(opts)` | Emit a durable, reflowable titled Markdown card in the transcript; returns block id/status or `nil, err`. | | `ctx.ui:clear()` | Clear the conversation scrollback in the connected UI frontend. | | `ctx.ui:completion_register(spec)` | Register a completion source for `/` commands, `@` mentions, or custom triggers; withdrawn on dispose. | | `ctx.ui:confirm(prompt, default, opts)` | Present a yes/no confirmation prompt and return `boolean\|nil, err?`. | | `ctx.ui:context(name, opts)` | Register a plugin-scoped keymap subcontext; removed when the caller is disposed. | | `ctx.ui:delete_keymap(context, key)` | Delete the topmost runtime keymap binding of a key sequence in a context. | | `ctx.ui:delete_markdown(document_id)` | Remove a caller-owned Markdown document and cancel its pending work. | | `ctx.ui:editor(opts)` | Open an interactive multi-line editor dialog and return the edited text or `nil, err`. | | `ctx.ui:editor_config(opts)` | Configure editor appearance options (`prompt`, `placeholder`, `busy_placeholder`, `border`, `shell`). | | `ctx.ui:editor_cursor()` | Return the current 0-based editor cursor position `{row, col}` aligned to grapheme boundaries. | | `ctx.ui:editor_hint(text)` | Set the transient hint text displayed beneath the editor. | | `ctx.ui:editor_insert(text)` | Insert `text` at the current cursor (replacing any active selection) as an undoable edit. | | `ctx.ui:editor_replace(range, text)` | Replace `range` (`{start, end}` or nil for selection/cursor) with `text` as an undoable edit. | | `ctx.ui:editor_selection()` | Return the active editor selection `{start, end, anchor, head, text}`, or nil when collapsed. | | `ctx.ui:editor_state()` | Return the full editor state snapshot (`text`, `cursor`, `selection`, `empty`, `revision`). | | `ctx.ui:exit(opts)` | Request the UI frontend to exit (`force = true` bypasses exit guards). | | `ctx.ui:exit_guard(on)` | Enable or disable the frontend exit guard. | | `ctx.ui:flag(name, value)` | Set a named boolean UI context flag used by keymap `when` expressions. | | `ctx.ui:get_editor()` | Return the current raw editor input text (including leading `!`/`!!` in shell mode). | | `ctx.ui:get_keymap(context)` | Return the runtime keymap snapshot (contexts, actions, bindings, and essential conflicts). | | `ctx.ui:get_markdown(document_id)` | Latest rendered snapshot for a caller-owned Markdown document. | | `ctx.ui:get_select_preview(select_id, index, tab)` | Evaluate the active `ui.select` preview callback for the highlighted item and tab. | | `ctx.ui:handler(kind, name, opts, fn)` | Register an ordered handler for `input/submit` ("submit") or `key/interrupt` ("interrupt"); withdrawn with the caller. | | `ctx.ui:input(opts)` | Present a single-line input prompt and return the entered string or `nil, err`. | | `ctx.ui:invalidate(component, opts)` | Invalidate a rendered widget or status segment, or update viewport dimensions and trigger resize. | | `ctx.ui:invalidate_presentations()` | Invalidate cached Markdown presentations across active documents after a display or presenter state change. | | `ctx.ui:keymap()` | Return a summary map of active key bindings. | | `ctx.ui:list_markdown_presenters()` | Active fenced-code presenter registrations, sorted by language. | | `ctx.ui:markdown_presenter(language, def)` | Register a fenced-code presenter for `language`; disposing the returned function removes it and cancels its work. | | `ctx.ui:notify(text, level)` | Show a transient notification message with optional severity level (`info`, `success`, `warning`, `error`). | | `ctx.ui:overlay(title, node, opts)` | Display a titled modal overlay containing `node`. | | `ctx.ui:print(node)` | Append a rendered `mare.Node` block to the conversation scrollback. | | `ctx.ui:questions(opts)` | Present a structured multi-question prompt to the user and return the answers or `nil, err`. | | `ctx.ui:register_entry_renderer(kind, opts)` | Register a display-only custom entry renderer owned by the caller. | | `ctx.ui:register_markdown_transform(opts)` | Register a Markdown transformer for selected message surfaces, owned by the caller. | | `ctx.ui:register_override(name, fn)` | Wrap or replace `select`, `input`, `confirm`, or `notify`; released on dispose. | | `ctx.ui:render_markdown(document_id, source, opts)` | Render fenced blocks in a caller-scoped Markdown document asynchronously via registered presenters. | | `ctx.ui:render_text(node, width)` | Render a `mare.Node` into plain text wrapped to optional column `width`. | | `ctx.ui:renderer(kind, r)` | Register a display renderer for a message or tool kind (`tool:<name>`, `message:user`, etc.); removed on dispose. | | `ctx.ui:select(opts)` | Present an interactive item picker and return `(index, tab_or_error, key, filter)`. | | `ctx.ui:send_editor(text, opts)` | Submit the current editor buffer (or override text) to the session's agent lane. | | `ctx.ui:set_editor(text, opts)` | Set or update the main input editor buffer text and optional draft/attachment options. | | `ctx.ui:set_editor_cursor(row, col)` | Move the editor cursor to `(row, col)` (or `{row, col}`), clamped to grapheme boundaries, and clear selection. | | `ctx.ui:set_editor_selection(anchor, head)` | Set the editor selection `{anchor, head}` or pass nil to clear it. | | `ctx.ui:set_external_editor(action, text)` | Acquire, commit, or cancel the per-session external editor lock. | | `ctx.ui:set_keymap(context, key, action, opts)` | Bind or mask a key sequence in a context for the caller's lifetime. | | `ctx.ui:set_queue_mode(mode)` | Update the active queue input mode indicator in the UI. | | `ctx.ui:set_queued(n)` | Update the displayed count of queued inputs in the UI. | | `ctx.ui:status(status_id, def)` | Register a named statusline segment; returns a release disposer. | | `ctx.ui:style(name, spec)` | Set a named UI style override; the previous style returns when the caller is disposed. | | `ctx.ui:theme(colors)` | Apply a color map to the connected UI frontend. | | `ctx.ui:transcript(title, node, opts)` | Open or update the live transcript view with `title` and `node`. | | `ctx.ui:transcript_close(title)` | Close the open transcript view (optionally matching `title`). | | `ctx.ui:transcript_title()` | Return the title of the currently open transcript view, or nil. | | `ctx.ui:transform_markdown(text, opts)` | Run registered Markdown transformers for a message surface. | | `ctx.ui:update_editor(text, opts)` | Synchronize the external editor draft state and broadcast updated state to attached frontends. | | `ctx.ui:widget(widget_id, def)` | Register a named widget rendered above or below the editor; withdrawn when the caller is disposed. | | `ctx.ui:width()` | Return the current frontend viewport width in columns. | | `ctx.ui:working(label, detail, opts)` | Set or clear the active working indicator (`label = nil` clears it). | ## ctx.usage Defined in `types/mare/services/usage.gen.lua`. | | | |---|---| | `ctx.usage:context_tokens()` | Tokens occupying the context window after the last request. | | `ctx.usage:cost_text(format)` | Cost as text: "$0.1234", "subscription, not billed", or both. | | `ctx.usage:get()` | Totals, context tokens and rate limits of the session in one object. | | `ctx.usage:quota_lines()` | Subscription quota as display lines, one per window (/status, the statusline). | | `ctx.usage:rate_limits()` | Latest subscription quota per provider (the llm/rate-limits event). | | `ctx.usage:set_context(tokens, opts)` | Update the context token estimate and emit usage/changed; notify = false is silent. | | `ctx.usage:totals()` | The session's totals: reset by a new session, recounted on resume. | ## ctx.web Defined in `types/mare/services/web.gen.lua`. | | | |---|---| | `ctx.web:fetch(url, opts)` | Fetch a URL using the currently selected fetch backend under active sandbox limits. | | `ctx.web:list_providers(kind)` | Registered web backends of `kind` sorted by provider_id, each marked `selected` when active. | | `ctx.web:register_fetch(opts)` | Register a fetch backend owned by the caller; removed on release or disconnect. | | `ctx.web:register_search(opts)` | Register a search backend owned by the caller; removed on release or disconnect. | | `ctx.web:search(queries, opts)` | Search the web using the currently selected search backend under active sandbox limits. | ## ctx.webserver Defined in `types/mare/services/webserver.gen.lua`. | | | |---|---| | `ctx.webserver:get()` | Status and bound endpoints of the host webserver listener. | | `ctx.webserver:list_assets()` | Registered static asset mounts on the host webserver. | | `ctx.webserver:list_routes()` | Registered HTTP routes on the host webserver. | | `ctx.webserver:register_assets(dir, opts)` | Register a static asset directory served under a URL prefix on the host webserver. | | `ctx.webserver:register_route(path, opts)` | Register a named HTTP route on the host webserver. Requests are forwarded to the caller handler. | ## ctx.workspace Defined in `types/mare/services/workspace.gen.lua`. | | | |---|---| | `ctx.workspace:get()` | Return the canonical workspace root, trust state, and workspace directory list. | | `ctx.workspace:set_trust(trusted, save)` | Update project trust for this workspace across all active sessions attached to it. | ## mare Defined in `types/mare.lua`, `types/mare/config.lua`, `types/mare/loader.lua`, `types/mare/profile.lua`. | | | |---|---| | `mare.setup(opts)` | Layers, lowest first: defaults < state.json < user init.lua < project .mare/init.lua < env `MARE_<NAME>` < CLI `--set name=value`. An unknown name warns (did-you-mean); a wrong type or value is reported and keeps the default (`--strict-config` refuses to start on either); `/config` shows each value with its source and file:line. | | `mare.plugin(name, overrides)` | Override a plugin's default config (lazy.nvim merge: tables merge recursively, lists replace). | | `mare.config_clear(path)` | Clear one layer's override at `path` (`nil` cannot say "clear"). In a config file the value (any depth, e.g. `"plugins.web.search.engine"`) and its sources go, so the default or a later layer applies. At runtime the runtime write of a whole option (`"name"` or `"plugins.<plugin>.<option>"`) goes and the startup configuration shows through again, applied and announced like a write. Clearing what nothing set does nothing. | | `mare.config_declared()` | Every declared plugin option, leaf by leaf (`"plugins.<plugin>.<path>"`; an object's fields are its leaves, a list, map or union is one), sorted — set or not. `/config` and `config.describe` list these. | | `mare.config_sensitive(path)` | Hide a configuration path and all its descendants in `/config` diagnostics (for example, `plugins.myplugin.private_value`). This does not encrypt the configuration or redact arbitrary plugin output. Marks are retained during config reloads. | | `mare.config_sensitive_paths()` | | | `mare.config_is_sensitive(path)` | Whether a dotted configuration path is sensitive (via `mare.config_sensitive`, `mare.options[k].sensitive`, or sensitive key/segment names such as `api_key`, `headers`, `query`). | | `mare.config_redact(path, value)` | Redact sensitive values in a configuration value at `path`: the one redactor for every way a config value leaves (`/config`, RPC `options.get` / `config.describe`, `option/changed`). It knows every rule — `mare.config_sensitive` marks, `sensitive` in core options and in plugins' `config_schema` (at the path or a parent), key-name rules. | | `mare.on(event, fn)` | Subscribe to a kernel event from init.lua, e.g. `mare.on("model/changed", function(e) ... end)`: a native listener (a plugin's `ctx:on`). A waterfall listener is `fn(value, ..., next)` and passes on with `next(...)`; a decision point is voted on with `mare.policy.voter`. Handlers are dropped and re-registered on `/reload config`. | | `mare.model(def)` | a provider with several routes (opencode-go): this model's route, above every other layer Wire plugins may declare additional model fields via `WireSpec.model_fields`. this model's parameters: a definition (mare.ParamDef) adds or changes one, a plain value is its default (or, with `alias`, the value the alias pins) Add a model or override fields of a built-in one. | | `mare.params(rule)` | a route some plugin provides: a registered wire's `describe.route`, a provider's route, or one a plugin's own rules map (a third-party wire's route included); another one never matches and `/doctor` names it Model parameters and their wire mappings. Layers, low → high: built-in < provider < model < user (init.lua; provider < route < family/glob < one model; state.json's remembered values below init.lua's) < trusted project (.mare/init.lua) < agent < session (/model, /effort, keys) < request. Function mappings run with the trust of provider/request hooks; from project scope they can't write authorization / x-api-key. | | `mare.provider(name, opts)` | "ENV_NAME", a literal key, or a key helper: a command whose stdout is the key (or JSON {key\|token, expires_at}); run one at a time, cached until `refresh_interval_ms` / `expires_at`, and run again after a 401 Wire plugins may declare additional provider fields via `WireSpec.provider_fields`. Configure a provider (endpoint / credentials). | | `mare.config_origin()` | The currently executing config layer and its root file. An unrelated coroutine or ordinary plugin/runtime call returns {layer="runtime"}, even while init.lua yields. Host-owned, detached metadata; changing this table cannot change config provenance. | | `mare.config_resolve_preset(spec, value)` | Resolve a preset-as-data configuration (`defaults < inherited preset < explicit leaf overrides`). Supports `like` inheritance chains with cycle detection and did-you-mean diagnostics on unknown presets. | | `mare.config_sources()` | Where each effective config value came from: `{ [key] = {layer, where?} }`. | | `mare.config_cli(path)` | Validated value of `path` supplied via a dedicated startup CLI flag such as `--permission`, `--yolo`, or `--approval-policy` (unaffected by runtime writes), or `nil` when `path` was not pinned by a CLI flag. | | `mare.config_describe(keys, opts)` | Describe configuration options and dotted paths with redacted effective/default values and provenance. | | `mare.config_warnings()` | Config warnings (unknown names, wrong types) with file:line. | | `mare.reload_config()` | Re-run init.lua and reload plugins whose options changed (`/reload config`). `pending`: plugins left waiting for a service nobody provides (not failures; they start when it appears). | | `mare.reload()` | plugins started, plugins of removed packages disposed, everything else reloaded (a plugin whose new definition fails keeps the old one), packages' config() again. Also emitted as `reload/completed`. | | `mare.reload_version()` | The host's reload state as an opaque string: it changes with every config or plugin reload (and while one is running or incomplete). Compare it with an earlier value to tell whether a cached decision (e.g. a tool approval) predates a reload. `"closed"` once the host is gone. | | `mare.log(level, msg)` | Write a log line attributed to the running plugin. | | `mare.caller_site(skip)` | "file:line" of the nearest Lua caller outside the core prelude and the config API (`/config` shows where an option was set, like Neovim's `:verbose set`); `skip` skips that many more frames first (a helper names its caller's line, not its own). nil when there is none. | | `mare.date(fmt, ms)` | | | `mare.error(code, message, data)` | A mare.Error value to raise with `error(value, 0)`: a core code or one the service declares (`<service>.<name>`), with data its declaration describes. It keeps its fields through service proxies and mare.exec.run. | | `mare.shared(name)` | One table per name for the life of the Lua VM, the same for every plugin and kept across plugin reloads and provider replacement: state the providers of one contract share (e.g. `mare.shared("my.state")`). | ## mare.Service Defined in `types/mare/host/service.lua`. | | | |---|---| | `mare.Service.constructor(self, ctx, name, options)` | Construct and provide service `name` from `ctx` under its contract (admitted before anything is published; a refusal fails the providing fiber). | | `mare.Service.new(ctx, ...)` | A new instance (`cordis.class` constructor form). | | `mare.Service.is(value)` | Whether `value` is an instance of this class. | ## mare.activity Defined in `types/mare.lua`. | | | |---|---| | `mare.activity.capture(provider)` | Synchronously invoke a provider and return its isolated JSON value; raises on yield, cycles, non-JSON values or resource limits. Used by activity registries, public to any plugin. | ## mare.approvals Defined in `types/mare/approvals.lua`. | | | |---|---| | `mare.approvals.check_human(token, binding, arguments, decision)` | Check native human evidence without consuming it. Lua cannot issue evidence. | | `mare.approvals.consume_human(token, binding, arguments, revision, decision)` | Consume native evidence once, after matching all owner/turn/request/snapshot fields. | | `mare.approvals.register_snapshot(binding, action)` | | | `mare.approvals.public_result(result)` | Project a full local result into the closed public audit DTO. No free-form reason, arguments, schema, permissions, amendment, snapshot, or receipt is exposed. | ## mare.clipboard Defined in `types/mare/ui.lua`. | | | |---|---| | `mare.clipboard.copy(text)` | | ## mare.command Defined in `types/mare/config.lua`. | | | |---|---| | `mare.command.alias(short, target)` | `/short` runs `/target ...`. | ## mare.contracts Defined in `types/mare/host/contracts.lua`. | | | |---|---| | `mare.contracts.permitted(service, method, caller)` | Whether the explicit caller (or unrestricted host call when omitted) may call `service.method`. | | `mare.contracts.is_peer(caller)` | Whether the explicit caller is a restricted peer RPC connection (never true for owners or in-process Lua). | | `mare.contracts.allows_session_path(caller)` | Whether the explicit caller may address sessions by filesystem path (local/admin owner only). | | `mare.contracts.validate(service, method, value)` | Check `value` against `service.method`'s result contract without calling anything. | ## mare.crash Defined in `types/mare/store.lua`. | | | |---|---| | `mare.crash.begin(fingerprint)` | Durably mark a request in flight (persisted before it returns); a mark a dead process left counts as one crash. The fingerprint is the stable request id (`llm` uses `"req:" .. id`). | | `mare.crash.finish(fingerprint)` | The attempt ended normally: the entry ends (kept, evictable) and its count is cleared. | | `mare.crash.release(fingerprint)` | The request was refused, not sent (crash limit): the entry ends (evictable) but keeps its count, so the same request stays refused and the refusal is not counted as another crash. | ## mare.crypto Defined in `types/mare/text.lua`. | | | |---|---| | `mare.crypto.sha256(s)` | | | `mare.crypto.random_bytes(n)` | | | `mare.crypto.random_hex(n)` | | | `mare.crypto.uuid()` | | | `mare.crypto.pkce()` | | | `mare.crypto.base64_encode(s)` | | | `mare.crypto.base64_decode(s)` | | | `mare.crypto.base64url_encode(s)` | | | `mare.crypto.base64url_decode(s)` | | ## mare.env Defined in `types/mare.lua`. | | | |---|---| | `mare.env.get(name)` | | | `mare.env.hostname()` | | ## mare.exec Defined in `types/mare/proc.lua`. | | | |---|---| | `mare.exec.run(ctx, fn, ...)` | Run `fn(...)` tagged with `ctx` (an outer context is never replaced: a nested run belongs to the outer call). While a session journal (`mare.store.open`) is open, a new call is admitted only on its durable start — a journal write with `ack = ctx.tool_call_id`; otherwise it raises `EXEC_NOT_DURABLE: <reason>` and `fn` never runs. Each ack admits once. `approval_key` names the frozen call (tools service): in a sub-agent, a call the parent approved is matched by it and escapes the inherited ceiling. lifetime="ephemeral-read-only" skips journal admission only with an explicit confined read-only sandbox blocking all network. Unknown or unsafe lifetimes fail before fn runs. | | `mare.exec.current()` | A detached, read-only view of the calling code's context (nil outside tool calls). `denials` lists refusals so far; changing this view cannot change the active policy. | | `mare.exec.check(op, target)` | Raise if `op` ("write"\|"read"\|"network") on `target` is refused for the calling code. | | `mare.exec.check_mutation(operation)` | Refuse a host-state mutation inside ephemeral-read-only execution. Called before changing options or service state; filesystem/network/process operations also enforce their policies. | | `mare.exec.refuse_unconfinable(what)` | Raise if `what` cannot be confined while a sandbox policy is active. | ## mare.flags Defined in `types/mare/flags.lua`. | | | |---|---| | `mare.flags.register(name, opts)` | Register a CLI flag (`--<name>` / `--<name>=<val>`). | | `mare.flags.get(name)` | Read a registered CLI flag value (CLI override -> default -> nil; nil if unregistered). | | `mare.flags.list()` | List all registered CLI flags and their resolved values. | ## mare.fs Defined in `types/mare/fs.lua`. | | | |---|---| | `mare.fs.resolve(p)` | | | `mare.fs.relative(p)` | `p` without the working directory in front when it lies below it, else `p` as given (Windows: separators, case and `\\?\` folded; canonical forms compared as a fallback). | | `mare.fs.read(p, opts)` | | | `mare.fs.read_window(p, opts)` | Read a 1-based line slice of `p`, returning `{lines, total, size, hash}` or `nil, err`. | | `mare.fs.write(p, data, opts)` | `sync_boundary`: for atomic writes, also sync ancestor entries up to this vouched durable directory. `atomic`: temp file + fsync + rename (keeps an existing file's permissions); `create_new`: fail if the path exists (with atomic: hard-linked into place, never clobbers). | | `mare.fs.realpath(p)` | Canonical path (symlinks resolved), or the absolute path when it doesn't exist yet. | | `mare.fs.resolve_path(path, base)` | Resolve the logical and physical forms of a path, failing if its identity is ambiguous. | | `mare.fs.project_root()` | Current project resource root, or the session working directory when no root is present. | | `mare.fs.compile_path_glob(pattern, base)` | Compile a separator-aware absolute or base-relative path glob. | | `mare.fs.path_within(path, root, conservative)` | | | `mare.fs.exists(p)` | | | `mare.fs.git_dir(p)` | Return the validated Git directory of the worktree at `p` (Git's rules: a `.git` directory or gitfile naming one with a valid HEAD, objects and refs). nil when there is none or the `.git` directory is not valid (discovery goes on upward); nil, "invalid gitfile" for a `.git` file that names no valid Git directory (Git's discovery stops there: not a repository). Inside a tool call, an unreadable metadata path raises like the other fs functions. | | `mare.fs.git_branch(p)` | Synchronously read the current Git branch name (or 7-character detached HEAD commit prefix) by walking upward from `p` (default: working directory) to the nearest validated `.git` directory or gitfile and reading `HEAD`. Returns nil outside a Git repository or at an invalid `.git` file. Inside a tool call, an unreadable metadata path raises like the other fs functions. | | `mare.fs.stat(p, opts)` | | | `mare.fs.identity(p)` | Stable cross-platform file identity (`dev:ino` on Unix; volume/index on Windows) when `p` exists. | | `mare.fs.sniff(p)` | Async bounded content sniff for `p` (`binary`, `"text"`/`"empty"`/`"image"`/`"pdf"`/`"binary"`, and byte `size`). | | `mare.fs.mkdir(p)` | | | `mare.fs.remove(p, recursive)` | | | `mare.fs.rename(a, b)` | | | `mare.fs.list(p, opts)` | | | `mare.fs.walk(dir, opts)` | | | `mare.fs.index(dir, opts)` | An incrementally maintained, gitignore-aware file list (the `@` completion index). | | `mare.fs.watch(path, on_change)` | Watch `path` for policy-filtered filesystem changes, invoking `on_change({ changed_paths, truncated })`. | ## mare.http Defined in `types/mare/net.lua`. | | | |---|---| | `mare.http.request(opts)` | Failures read `transport: …` (retryable), `malformed_response: …` (an unparseable stream, including invalid UTF-8) or `aborted` (cancelled). `idle_timeout_ms`: no bytes at all for this long fails the read (heartbeat comments count as activity); `header_timeout_ms`: wait for the response headers; `fresh`: a new connection instead of a pooled one. Proxies come from HTTP(S)_PROXY / ALL_PROXY / NO_PROXY (SOCKS and PAC are a clear error); custom CAs from MARE_CA_CERTIFICATE, else SSL_CERT_FILE plus SSL_CERT_DIR (a directory of PEM / .crt files). `proxy`: this request's own HTTP(S) proxy (NO_PROXY still applies); `connect_timeout_ms`: its connect timeout (default 30 s). `sse_max_line_bytes` / `sse_max_event_bytes`: `next_event` fails with `malformed_response` once one SSE line, or one event's lines together, exceed this many bytes (default 16 MiB each). `redirect`: `"follow"` (default), `"manual"` (return 3xx without following), or `"same-origin"`. `max_redirects`: maximum redirects allowed (default 10). | | `mare.http.retry_after(headers)` | `retry-after-ms`, or `Retry-After` in seconds or as an HTTP date, in milliseconds. | | `mare.http.listen_once(opts)` | `ports`: the first free one is used; `on_bound(port)` runs once listening (build the redirect URL). | | `mare.http.url_encode(s)` | | | `mare.http.build_url(base, query)` | | | `mare.http.websocket(opts)` | | | `mare.http.serve(opts)` | Start a loopback-only HTTP/1.1 + SSE + WebSocket server. Defaults to `127.0.0.1` and ephemeral port `0`. Rejects non-loopback `host` binds, validates `Host` against loopback names/IPs (and optional `trusted_hosts`) (DNS rebinding protection), and enforces `Sec-Fetch-Site` / `Origin` checks (rejects cross-site browser requests and WebSockets). Token authentication is mandatory by default: when `token` is omitted, uses the persisted 32-byte random runtime token (`<state>/host/token`, `0600`, rotated via `mare token rotate` for new requests/connections); pass `token = false` to explicitly disable authentication, or pass a non-empty string for a custom static token. `<state>/host/` is protected by the `fs_host_protect` sandbox capability (gated before creation/rotation unless `accept_partial = { "fs_host_protect" }` is set). Not protected by `fs_host_protect`: `danger-full-access`, disabled permissions plugin, approved unconfined escalations, custom static tokens, restricted processes launched with a raw Seatbelt profile before token creation, and pre-existing or external-process sandboxes on partial backends. Accepts `Authorization: Bearer <token>`, `x-mare-token`, or browser `GET ?token=<token>` (exchanged via `303 See Other` for an in-memory `HttpOnly; SameSite=Strict` session cookie); WebSocket upgrades also accept `?token=`. `header_read_timeout_ms` sets the HTTP header read timeout (default `30000`, at least 1) to mitigate slowloris. `ws_max_message_bytes` (default `4194304`) and `ws_max_frame_bytes` (default `1048576`) cap WebSocket sizes. `max_concurrency` and `max_connections` must be at least 1 and are clamped to Tokio's `Semaphore::MAX_PERMITS`. `close_grace_ms` sets the WebSocket close grace period in milliseconds (default `5000`, non-negative) before aborting a non-draining handler. `body_stall_ms` bounds how long a request body may stay unread while the client keeps sending, and how long a WebSocket may stay backpressured by a full, unconsumed inbound queue (default `60000`, non-negative); the connection is then cancelled and closed. Cancellation happens early when a disconnect is observable; otherwise the stall timeout is the backstop. `cancel` (optional `mare.Token`) only cancels waiting for the startup `.token.lock` (within the 5000 ms lock acquisition timeout when using the default runtime token); once `mare.http.serve` has started, cancelling it does not stop the server (call `HttpServer:close()` to shut down). | ## mare.image Defined in `types/mare/ui.lua`. | | | |---|---| | `mare.image.load(path, opts)` | Load, downscale (longest side ≤ max_dim) and encode an image file. | | `mare.image.clipboard(opts)` | | | `mare.image.is_image(path)` | | | `mare.image.to_png(data)` | Decode base64-encoded image bytes within safety limits, downscale if oversized, and re-encode as PNG (or JPEG when large). | ## mare.json Defined in `types/mare/text.lua`. | | | |---|---| | `mare.json.encode(v, opts)` | | | `mare.json.decode(s)` | | | `mare.json.decode_unique(s)` | Decode JSON and reject duplicate object members at every depth (after key unescaping). | | `mare.json.decode_lossless(s)` | Preserve null and empty containers from the serde_json parsed value; reject further Lua conversion loss. Raw number precision and duplicate keys may already be lost during parsing. | | `mare.json.encode_strict(v)` | Encode a JSON value; reject functions, non-finite numbers, cycles, sparse arrays and unsupported metatables. | | `mare.json.clone(v)` | Deep-clone a Lua value through strict JSON value representation, preserving `mare.json.null` and empty arrays. | | `mare.json.copy_metadata(source, target)` | Copy JSON schema property-ordering metadata recursively from `source` tables to matching `target` tables. | | `mare.json.array(t)` | | | `mare.json.is_array(t)` | Whether a table carries the JSON array marker (including an empty array). | ## mare.keymap Defined in `types/mare/keymap.lua`. | | | |---|---| | `mare.keymap.set(context, key, action, opts)` | Bind a key (Neovim `vim.keymap.set`). context: "editor" (or a list of contexts). key: "<C-t>", "<M-CR>", "ctrl+t", ... `unique = true` raises when the key is already bound in that context. `priority` (finite number, default 0) breaks ties within the same source layer (`project > user > plugin > default`). `when`: the binding takes the key only while these hold, otherwise the key goes on to the binding below it (then along the lookup chain). Anonymous function actions require a non-empty `desc`. The handle undoes the binding (`handle:remove()` or `mare.keymap.remove(handle)`). `false` masks the caller's layer and all lower contexts along the chain; it accepts no `when` and ignores `unique`. Services delegating on behalf of a caller may pass `owner` and `layer` (`"default"` or `"plugin"`). | | `mare.keymap.set_many(specs, opts)` | Register multiple bindings in one atomic batch. Each item is either `{ context, key_or_keys, action, opts? }` or `{ context?, key?, keys?, action, desc?, unique?, priority?, when? }`. Flushes all changed stacks in a single host update; `handle:remove()` or `mare.keymap.remove(handle)` removes the whole batch. | | `mare.keymap.del(context, key, opts)` | Remove the topmost binding of `key` in `context` in the caller's layer (or `opts.owner` / `opts.layer`); returns whether a binding was removed and the normalized key sequence. | | `mare.keymap.context(name, opts)` | Declare a plugin subcontext (`name` must be `parent .. "." .. seg` with `seg` matching `^[a-z][a-z0-9_-]*$`). `handle:remove()` deletes the context, its descendants, and their bindings. | | `mare.keymap.list(opts)` | Without `opts.snapshot = true`, returns every reachable unmasked binding of each key in each context (optionally filtered by `opts.context`), ordered by source layer, `priority`, and binding order. With `opts.snapshot = true`, returns the full keymap snapshot (`contexts`, `actions`, `bindings`, `conflicts`). | | `mare.keymap.hint(action, context)` | The keys that trigger `action` with focus at `context` (default "editor"), ordered by source layer (`project > user > plugin > default`), then `priority`, then binding order. | | `mare.keymap.actions()` | Registered core and Lua actions (`core = true` for core actions). | | `mare.keymap.action(name, fn, opts)` | A named Lua action, bound by name: `mare.keymap.set("editor", "<M-c>", "copy.last")`. Built-in ones: "copy.last" (copy), "agents" (/agents; bound to ← with `when = "editor_empty"`), "agents.back" / "agents.prev" / "agents.next" (Esc, Alt+←/→ in a sub-agent's view; they decline in views the agents plugin didn't open). `fn(ev)` runs as the key is handled, up to its first yield: returning exactly `false` declines (the key goes on to the binding below, then the editor), anything else takes the key; decide before waiting on anything. An error takes the key and shows a notice. The handle removes it (`ctx.ui:action` does that when the plugin is disposed). | | `mare.keymap.resolve(context, seq, opts)` | Resolve a key or key sequence along `context`'s lookup chain under optional predicate flags. | | `mare.keymap.invoke(action, opts)` | Run a registered Lua action (named or `fn:N`). Returns `true` if handled, `false` if declined, or `nil` if no such Lua action is registered. | | `mare.keymap.is_reserved(key)` | Whether `key` (or any token in a key sequence) is reserved by the core. | | `mare.keymap.remove(handle)` | Remove every binding registered by a handle returned from `set` or `set_many`. | | `mare.keymap.callback(id)` | The Lua function bound under an action id (from `set`), or nil. | ## mare.loader Defined in `types/mare/loader.lua`. | | | |---|---| | `mare.loader.reset(path)` | Drop the whole cache, or one source file's entry. Returns how many entries were removed. | | `mare.loader.prune()` | Drop entries for another mare version or a changed / missing source (also done at most daily on startup). | ## mare.lock Defined in `types/mare/fs.lua`. | | | |---|---| | `mare.lock.file(path, opts)` | Exclusive lock on `path` (created if missing); `cancel` / `timeout_ms` only end the wait. | ## mare.mcp Defined in `types/mare/mcp.lua`. | | | |---|---| | `mare.mcp.connect(spec, cancel)` | | | `mare.mcp.oauth_begin(url, key, opts)` | | | `mare.mcp.logout(key, url)` | | | `mare.mcp.has_credentials(key, url)` | | | `mare.mcp.spill(data, ext)` | | | `mare.mcp.log(server, level, msg)` | | | `mare.mcp.redact(s)` | | ## mare.net.unix Defined in `types/mare/net.lua`. | | | |---|---| | `mare.net.unix.connect(path, opts)` | | | `mare.net.unix.request(path, line, opts)` | One connection, one line out, one line back; `timeout_ms` bounds the whole exchange. | | `mare.net.unix.listen(path, handler, opts)` | Listen on a Unix socket: `handler(conn)` runs (async) once per accepted connection, so several clients can be connected at once. A stale socket file is replaced; one that still answers is refused ("already in use"). The file mode defaults to 0600. | ## mare.peers Defined in `types/mare/net.lua`. | | | |---|---| | `mare.peers.publish(namespace, fields)` | Put `fields` (JSON-serialisable, named) into this process's registry entry as `plugins.<namespace>`, replacing what that namespace held; `nil` removes it. Other namespaces and the core fields are never touched. `namespace`: lowercase letters, digits, `.`, `_`, `-` — by convention the publishing plugin's name (one owner per namespace). Written with the next registry rewrite (at most every 200 ms); kept, unwritten, while the session isn't registered. | | `mare.peers.list()` | Registered sessions on this machine (this one included); dead ones are pruned. | | `mare.peers.self()` | This session's entry, or nil when it isn't registered (headless/--rpc without --peer, or `peer = false`). | | `mare.peers.dir()` | The registry directory. | | `mare.peers.connect(target, opts)` | Open a registered peer. The caller owns the client; close it, e.g. from a ctx:effect cleanup. Clients survive session switches; each message names the session current when it is sent (`from.session_id`, self-reported; none for a message sent while the host is still starting). Default peer privileges never allow arbitrary control. No arbitrary socket path is accepted. | ## mare.plugins Defined in `types/mare/config.lua`, `types/mare/plugins.lua`. | | | |---|---| | `mare.plugins.add(list)` | A package declaration (compatible with lazy.nvim specs). `"owner/repo"`, `"owner/repo:subdir"` or a table; with no version field the newest semver tag is used, else the default branch. A package declared more than once is merged: the last write wins for single values and `opts` (deep merge); `dependencies` and `only` are merged; any `enabled = false` disables it (and the dependencies only it needs); a package only declared `optional = true` is dropped. | | `mare.plugins.status(name)` | The state of plugin `name`; an unknown name gives `defined = false`. | | `mare.plugins.list()` | Every defined plugin, in definition order. | | `mare.plugins.failures()` | What failed at startup or in the latest full /reload: plugins (also those whose definition could not be read) and config files. During a full /reload, returns the failures as they were when the reload started (a half-reloaded tree has no meaningful answer); live again when it ends, before `reload/completed`. | | `mare.plugins.declaring(field, value)` | The plugins whose definition declares `value` in `field` ("tags", "wires", or "providers"): the defined ones in definition order, then the ones turned off by the config (`enabled = false`, `plugins.preset`). Read from the definitions, so a plugin that is off or failed still counts. | | `mare.plugins.report_problem(plugin, key, message)` | Record or replace a non-fatal declaration problem on `plugin` under `(plugin, reporter, key)`. Automatically cleared when either the target plugin or the reporter reloads or unloads. | | `mare.plugins.clear_problem(plugin, key)` | Clear the declaration problem on `plugin` reported by the caller under `key`. | | `mare.plugins.list_installed(opts)` | Package manager for `/plugins`; the same operations as `mare plugin …`. | | `mare.plugins.run(action, name, opts)` | | | `mare.plugins.install(name, opts)` | Install a catalog plugin by short name or sync a declared source. | | `mare.plugins.update(name, opts)` | Update declared packages to their newest allowed revision (`update`). | | `mare.plugins.check(names, opts)` | Fetch and compare revisions without moving checkouts or modifying locks. | | `mare.plugins.uninstall(name, opts)` | Uninstall a catalog plugin by short name or clean an unused source. | | `mare.plugins.manifest(name)` | Read `mare-plugin.toml` for an installed, enabled package. | | `mare.plugins.catalog()` | The plugin catalog with `enabled` / `recommended` for this project. | | `mare.plugins.diagnostics()` | Catalog and installed subplugin manifest problems. | | `mare.plugins.doctor()` | `mare doctor` checks: git and its version, the lock, plugin names defined twice. | | `mare.plugins.watched()` | Files whose change means "/reload to apply" (init.lua, plugins.json, a trusted .mare/init.lua). | | `mare.plugins.set_enabled(name, on, source)` | | | `mare.plugins.fetch_catalog()` | | | `mare.plugins.mare_news()` | | | `mare.plugins.dirs(kind)` | The installed packages' `skills/`, `prompts/`, `themes/` or `types/` directories (or custom paths declared in `mare-plugin.toml`, or package roots when `kind` is omitted), in load order (`context` reads skills and prompts, `theme-default` reads themes). Empty under `--no-user-plugins` (`mare.no_user_plugins`): no package loads, nor its content. | ## mare.policy Defined in `types/mare/config.lua`. | | | |---|---| | `mare.policy.voter(point, fn, opts)` | Vote on a decision point (`tool/before`, `tool/approval`, …) from init.lua, as a plugin's `ctx.policy:voter`: return nil to abstain, `"allow"`, `"ask"`, `"deny"`, or a vote table. Dropped and re-registered on `/reload config`. | ## mare.proc Defined in `types/mare/proc.lua`. | | | |---|---| | `mare.proc.shell(opts)` | Resolve the shell for commands. Unix: `shell_path`, $SHELL (bash/zsh), /bin/bash, bash, sh. Windows (pi's order): `shell_path` → %ProgramFiles%\Git\bin\bash.exe → %ProgramFiles(x86)%\Git\bin\bash.exe → bash.exe on PATH; the error lists every location checked. `model = true`: the default for model commands under the current sandbox — PowerShell inside the Windows default-tier sandbox (Git Bash cannot start there) unless `shell_path` is set. | | `mare.proc.powershell()` | PowerShell 7 (pwsh) or Windows PowerShell with `-NoProfile -NonInteractive -ExecutionPolicy Bypass -Command`; Windows only. | | `mare.proc.wsl_path(p)` | `C:\x\y` → `/mnt/c/x/y` (default WSL mount root only); nil for other paths. | | `mare.proc.windows_path(p)` | `/mnt/c/x/y` → `C:\x\y`; nil outside `/mnt/<drive>`. | | `mare.proc.alive(pid, start_time)` | Whether a process with `pid` currently exists (and matches `start_time` if both are known). | | `mare.proc.start_time(pid)` | Start time token of `pid` (defaults to the current process), or nil when unavailable. | | `mare.proc.spill_write(prefix, path, data, append)` | Write or append to a spill file the caller keeps: `<state>/spill/<prefix>-*.log`, the caller naming its own prefix (`[a-z0-9-]+`, e.g. "bash"). Any other path or prefix is refused. | | `mare.proc.spill_remove(prefix, path)` | Remove a spill file the caller keeps (`<state>/spill/<prefix>-*.log`). | | `mare.proc.env(opts)` | Scrubbed parent environment inherited by spawned children. | | `mare.proc.spawn(opts)` | | | `mare.proc.run(opts)` | `sandbox_failed`/`sandbox_marker` "[sandbox: failed to start (...)]" = the sandbox itself could not start (not a denial); `sandbox_denied`/`denial`/`sandbox_marker` = the sandbox refused the command. | | `mare.proc.manager()` | Create an owner-scoped process manager backing `proc.*`. | | `mare.proc.start(opts)` | Start a long-running process whose output goes to a bounded ring buffer. `spill` additionally receives the complete output. | | `mare.proc.open(url)` | | | `mare.proc.which(name)` | The absolute path of an executable, or nil; starts no process (Neovim `exepath()`). A bare name is looked up in PATH (on Windows with the PATHEXT extensions, so `rg` finds `rg.exe`); a name containing a path separator is a path, relative to the working directory, and is returned only when it is an executable file. Plugins use it to offer a tool only when it is installed. | ## mare.proc.sandbox Defined in `types/mare/proc.lua`. | | | |---|---| | `mare.proc.sandbox.check(op, target, policy, cwd)` | Same rules as a sandboxed spawn. Inside a tool call core already enforces the current policy on `mare.fs`/`proc`/`http`/`net`; this is for asking ahead. | | `mare.proc.sandbox.policy(spec, cwd)` | Normalized policy (resolved roots), nil when the spec means unsandboxed. | | `mare.proc.sandbox.current()` | The session's current policy (enforced inside tool calls), nil = unconfined. | | `mare.proc.sandbox.snapshot_current()` | Capture the current session policy after enforcing the inherited ceiling, revalidating roots and omitting only roots that have disappeared. Refused inside a tool call. | | `mare.proc.sandbox.snapshot_policy(spec)` | Normalize and capture a policy against the host workspace and inherited ceiling, without applying it. Missing roots are reported separately; other validation errors are refused. Refused inside a tool call. | | `mare.proc.sandbox.restore_snapshot(snapshot)` | Restore a captured native snapshot through the host setter. Revalidates the policy and inherited ceiling, reporting only genuinely missing roots; bypasses replaceable Lua setters. Also accepts a normal policy spec with the same normalization as set_current. Refused inside a tool call. The returned snapshot captures the applied policy. | | `mare.proc.sandbox.root_missing(path)` | True only for a genuinely absent root. Permission errors and invalid roots are false; callers must not silently omit them. Refused inside a tool call. | | `mare.proc.sandbox.preflight_protection(spec, cwd)` | Check whether per-workspace protected mounts can be prepared; may briefly create an owned empty mount point. | | `mare.proc.sandbox.generation()` | Changes whenever the current policy changes (approvals are bound to it). | | `mare.proc.sandbox.check_set(spec, cwd)` | Validate a policy spec against the active ceiling and persistent PTY fence without mutating the current session policy. Refused inside a tool call. | | `mare.proc.sandbox.set_current(spec, cwd)` | Replace the current policy (takes effect from the next call); errors on an invalid spec. Prefer `ctx.session:set_sandbox_mode(spec)`, which also logs it in the session. | | `mare.proc.sandbox.intersect(a, b, cwd)` | Per-dimension intersection of two policies (nil = the current policy): each dimension keeps only what both allow. An approval answer narrows the requested policy with this. | | `mare.proc.sandbox.within(path, roots, opts)` | Whether `path` (resolved; a dangling symlink counts as outside) lies under one of `roots`. | | `mare.proc.sandbox.marker(level)` | "[sandbox: file access denied under <level> mode]" | | `mare.proc.sandbox.msys_failure(o)` | Set when a sandboxed command is an MSYS2/Cygwin program (Git Bash) and died with 0xC0000142 under a Windows mechanism: "SANDBOX_MSYS_UNSUPPORTED: …"; nil otherwise. | | `mare.proc.sandbox.capabilities(cwd)` | | ## mare.profile Defined in `types/mare/profile.lua`. | | | |---|---| | `mare.profile.mark(label)` | Add a point to the /profile timeline (e.g. a cache invalidation). | | `mare.profile.report()` | The startup timeline and plugin load times. | | `mare.profile.slow_callbacks()` | Callbacks over `slow_callback_record_ms`, newest last (128 kept). | | `mare.profile.callback_timings(limit)` | Callback time per plugin and event, largest first. | ## mare.projection Defined in `types/mare/text.lua`. | | | |---|---| | `mare.projection.register(value)` | Register nonempty UTF-8 text; reject active duplicates and overlap with reserved references. Keep the lease alive; GC closes it. Close explicitly in a ctx:effect cleanup and on session switches. | | `mare.projection.project(value, opts)` | Copy nested string VALUES, preserving table metatables. Cycles/depth>64 and sensitive/reserved string keys fail closed. Functions/userdata are preserved opaque. Does not rewrite originals. Always returns a fresh copy. Non-UTF-8 string values fail unless opts.lossy (replace with U+FFFD, second result true when replaced) or opts.preserve_invalid (keep the bytes, projecting registered values inside their valid UTF-8 runs); the two are exclusive. Keys must be UTF-8. | | `mare.projection.restore(value, revision)` | Restore only inside an execution context carrying a native projection_authorization, the approved approval_snapshot and matching projection_version. The capability permits only the exact projected arguments accepted by that human response, once. This is not a plaintext getter outside approved execution. Unknown/revoked/malformed references error. The tools service calls this only inside its approved execution context, after persistence and cancellation checks, then validates the restored arguments again. Custom execution services must implement equivalent approval/sandbox boundaries; this primitive alone grants no permission. | | `mare.projection.revision()` | | | `mare.projection.active()` | | | `mare.projection.contains(value)` | | | `mare.projection.subscribe()` | | | `mare.projection.stream()` | | ## mare.prompt Defined in `types/mare/config.lua`. | | | |---|---| | `mare.prompt.section(def)` | Add (or replace) a system-prompt section. | | `mare.prompt.remove(name)` | Remove a system-prompt section by name (global and agent-specific variants). | ## mare.pty Defined in `types/mare/proc.lua`. | | | |---|---| | `mare.pty.capabilities()` | Discover enforced transport budgets and optional platform foreground capabilities. | | `mare.pty.spawn(opts)` | Run a program in a pseudo-terminal (interactive tools). Per-call policy elevations are refused because their authority must not escape into later input calls. While a PTY tree is alive, sandbox policy changes raise PTY_POLICY_BUSY; close/stop terminals before switching policy. Inside a confined tool call (or with `sandbox`) the program is confined like `mare.proc`: Seatbelt / bubblewrap wrap it inside the PTY; Landlock (and bubblewrap's Unix-socket filter) apply in the terminal child before exec; on Windows the sandbox runner owns the ConPTY and bridges it. | ## mare.sandbox Defined in `types/mare/sandbox.lua`. | | | |---|---| | `mare.sandbox.complete()` | Return the opaque host-callback sentinel that ends the current sandbox run successfully. | | `mare.sandbox.new(opts)` | Create a bounded Lua capability VM backed by a dedicated worker process. | | `mare.sandbox.output_ledger(max_bytes)` | Create a bounded JSON output ledger with an exact `max_bytes` budget (4..16777216). | ## mare.schema Defined in `types/mare/schema.lua`. | | | |---|---| | `mare.schema.compile(schema)` | Compile an object-root JSON Schema into a reusable tool argument validator. | | `mare.schema.compile_output(schema)` | Compile a tool output JSON Schema (or clone an existing `OutputSchema`). | | `mare.schema.compile_value(schema)` | Canonical outputs may be any JSON type; does not relax argument-schema validation. | | `mare.schema.redact(schema, value)` | Schema-directed removal, independent from key/pattern-based mare.text.redact. Structural JSON Schema subset: properties, additionalProperties schema, items, allOf/anyOf/oneOf. Annotate a secret node with ["x-mare-secret"]=true. Every union branch is visited conservatively; duplicate paths merge set=true. Object slots include missing ones; record/array slots include only existing entries. JSON null is set=true; Lua nil is unset. Array removals leave JSON null preserving zero-based string indexes in sidecar paths. Does not mutate input. Schema depth 64/nodes 10000; unsupported constructs (including $ref/conditionals) and malformed annotations error rather than silently exposing values. | ## mare.snapshot Defined in `types/mare/fs.lua`. | | | |---|---| | `mare.snapshot.configure(opts)` | | | `mare.snapshot.begin_turn(id)` | | | `mare.snapshot.turns()` | | | `mare.snapshot.content(hash)` | | | `mare.snapshot.restore(turn, opts)` | Restore files touched in `turn` or later to their content before it. Files changed outside mare since are `conflicts` (left alone unless `force`); links now are `refused`; trimmed backups are `missing`. | ## mare.spill Defined in `types/mare/spill.lua`. | | | |---|---| | `mare.spill.save(session_id, text, opts)` | | | `mare.spill.read(spill_id, opts)` | Bounded UTF-8 pagination (max 2000 lines/50KiB). next_byte continues a giant line exactly. Ownership is checked against the active execution context's session. Inside a confined call, `opts.session_id` may only equal the active context session; passing a different session fails with `denied`. | | `mare.spill.delete(spill_id, opts)` | Delete a session-owned spill object. Ownership is checked against the active session. Inside a confined call, `opts.session_id` may only equal the active context session; passing a different session fails with `denied`. | | `mare.spill.save_bytes(session_id, bytes, opts)` | Persist raw bytes (including NUL/non-UTF-8); at most 8 MiB per call. Same spill_ids, owner checks, permission policy, cancellation cleanup and explicit delete as text save. | | `mare.spill.read_bytes(spill_id, opts)` | Read a byte page without text decoding. Cursor is zero-based, beyond EOF is refused. Default limit 1 MiB, maximum 8 MiB. EOF returns empty bytes, more=false. Text read still rejects non-UTF-8; byte read works for both text and binary output. No image/MIME inference. Inside a confined call, `opts.session_id` may only equal the active context session; passing a different session fails with `denied`. | | `mare.spill.new_local(opts)` | Construct an owned local backend, using the same text/binary I/O and permissions. Relative root resolves against the host session cwd, fixed at construction. cleanup_period_days defaults to 30; integer 0 disables cleanup. A one-shot background sweep removes only strictly expired managed private regular files, never follows links, preserves active directories and reports failures as warnings without blocking saves. Maintenance freezes its originating policy and optional cancellation token; it never reads a later wider global policy. Supply the operation token when constructing inside cancelable work; an available execution-context cancel token is inherited by default. Reads never start maintenance. Call dispose from the owning context's ctx:effect cleanup; cached methods then reject calls. Reconstructing the same root permits reading its surviving session-owned spill objects. | ## mare.state Defined in `types/mare/state.lua`. | | | |---|---| | `mare.state.read()` | The whole state (`{}` when missing); nil + error when the file is corrupt. | | `mare.state.update(fn)` | `fn(state)` edits the table in place or returns a replacement; must not yield. Existing JSON nulls are passed as `mare.json.null` so unchanged values survive an update. | | `mare.state.set(key, value)` | Set (nil removes) one key. | | `mare.state.snapshot(request)` | Read one isolated private namespace under <state>/domains, without modifying legacy state.json. Namespace names are 1..128 ASCII letters/digits/._-, first character alphanumeric, never paths or authority. Null and empty object/array identities are preserved; malformed/unknown versions reject. No callbacks, resources or handles survive this call. Caller read restrictions still apply. | | `mare.state.compare_exchange(request, options)` | Atomically replace a namespace at its exact revision, with temp fsync + rename + directory fsync. Conflict performs no write. Deletion requires value=mare.json.null and retains a revision tombstone. Values are strict JSON; functions, arbitrary userdata/metatables, cycles and unsafe numbers reject. Ephemeral-read-only mutation and deny_read contexts reject; no namespace grants permissions. Cancellation/drop during lock wait or before publication rejects; the final check after temp fsync admits the irreversible publication phase (CAS visibility linearizes at rename). After it, cancellation cannot promise rollback. unknown_state means publication may have happened: reread/reopen and reconcile before continuing, never pretend the old value is intact. Plugin unload aborts the owner future; the worker retains only detached JSON and a child cancel token. | ## mare.status Defined in `types/mare/events.lua`. | | | |---|---| | `mare.status.hook(def)` | Run a command when the unified state changes ("status"), on session start/resume/fork/switch ("session") and on exit ("exit", awaited with a timeout). The state goes to stdin as JSON and into MARE_STATE, MARE_MESSAGE, MARE_SESSION_ID, MARE_SESSION_PATH, MARE_CWD, MARE_SESSION_MODEL. "status" runs are coalesced (at most one per throttle_ms, latest state wins) and skipped when state and message are unchanged; a run is killed after timeout_ms; failures are only logged. | ## mare.store Defined in `types/mare/store.lua`. | | | |---|---| | `mare.store.open(path, opts)` | Open a session for writing: a non-blocking flock on `<path>.lock` (re-checked against the inode at that path) first, then strict validation of the current format — all under the lock. Unsupported versions are refused unchanged. Fails with "session locked by another process", "session is already open in this process" (a second open here is refused until the first handle is closed) or "session file is corrupt" (file untouched). A torn final entry is cut before the first append. With a resume checkpoint in the session index (length + mtime), only the part after it is validated when it still holds — an optimization that assumes only mare appends; `mare doctor` parses every session in full. Appends are plain writes; `sync = true` (semantic boundaries) fsyncs, and a failed write or fsync truncates back to before it. `append_batch` writes several entries at once; `checkpoint()` records a checkpoint (also done on close); `close()` invalidates the handle immediately. An active snapshot read retains the session lock until that read and any deferred cleanup finish. `existing = true` (resume): a missing file fails with "session file not found" and nothing is created — a stale path never becomes a new, headerless session. The first ordinary handle becomes the active journal; after opening another ordinary handle, `activate()` selects it when the session switches. Switching or closing the active journal discards its pending acknowledgements; with ordinary handles open but none active, the gate refuses calls. Open unrelated/child transcripts with `auxiliary = true`: they neither activate nor gate execution and cannot acknowledge a call. On the active journal, `append(entry, { ack = tool_call_id })` (also supported by `append_batch`) requires a matching entry with `type = "tool_state"`, `state = "started"`, and `tool_call_id = tool_call_id`; it implies `sync`. The host admits that call into `mare.exec.run` once after the write and fsync succeed. `defer_activation = true` opens an ordinary journal without activating it, even when it is the first. `create_new = true` refuses an existing path and creates atomically. | | `mare.store.read_bound(path, lenient)` | Read a path-bound snapshot (optionally lenient), retaining the identity of the observed source rather than reopening it after selection. Refused inside a tool call. | | `mare.store.read_fork_snapshot(path, expected_session_id)` | Read a strict fork snapshot independent of the source writer/lock, optionally requiring the observed session header identity. Refused inside a tool call. | | `mare.store.read_snapshot(file, revision)` | Read through an independently opened handle verified against the locked writer. An optional revision must belong to this handle and still match its stamp/generation. The native read retains the session lock through deferred cleanup. Refused in tool calls. | | `mare.store.read_tail_snapshot(file)` | Capture a stable tail and revision from the same locked writer observation. A subsequent full read can use its revision to reject source mutation. Refused inside a tool call. | | `mare.store.snapshot_matches(file, revision)` | Check both the exact handle identity and its current journal generation/file stamp. A revision from another file returns false. Refused inside a tool call. | | `mare.store.reserve_staging_attachments(path)` | Exclusively reserve the attachment directory for an unpublished session path. The stage owns cleanup until its owner and every pending write release it. Refused in tool calls and ephemeral read-only sessions. No existing directory is reused or overwritten. | | `mare.store.read_attachment(journal, name, max_bytes)` | Read a session attachment constrained to `<session>.attachments/` without following directory or file symlinks, bounded by `max_bytes` and verified against its SHA-256 name. | | `mare.store.read(path, opts)` | Read all entries, lock-free, up to the end as of the call; an unterminated final entry (still being written, or torn) never counts. Strict: any other unparseable line is an error ("session file is corrupt"). `lenient = true` (read-only views of a damaged file) skips bad lines and returns how many. Never migrates or rewrites the file. The file is stat'ed (inode, length, mtime) before and after; if it changed it is read once more — `stable = false` means it still changed, so the result may be incomplete. | | `mare.store.list(dir)` | | | `mare.store.files(path)` | Every file of a session: the session file, its lock file, attachments, snapshot journal and sub-agent sessions (`<dir>/agents/<run>/` naming it as parent). | | `mare.store.delete(path)` | Delete a session and everything in `files(path)` under its lock: refused ("session locked by another process" / "already open in this process") while it is open. The index is the caller's: `index_append({session_id = session_id, path = path, deleted = true})` (never rebuild it). | | `mare.store.dir(cwd)` | | | `mare.store.read_from_compaction(path)` | Reverse read back to the latest compaction (and the message it keeps from). Strict and read-only like `read`. | | `mare.store.read_tail(path, n)` | | | `mare.store.search(path, query)` | | | `mare.store.index_append(entry)` | After appending to a session file, bring its index row up to date with the file: every field is derived from the file (a catch-up parses only what was appended), `cwd` records where a live writer runs. The row moves to the top when it gained messages; a `name`, `label` or `archive` entry changes its column only. `{session_id, path, deleted = true}`: the session was deleted, drop its row (and its sub-agents'). Multi-process safe. | | `mare.store.index_read(opts)` | Sessions from the index, newest first (by `seq`); built from the session files on first use. When the index can't be opened the session files are scanned instead (slower, logged). `scope`: "all" (default), "cwd" (`cwd`, default `mare.cwd`), "project" (the same `project_root`); `archived`: false (default), true, "any"; `kind`: "session" (default: main sessions and forks), "main", "fork", "agent", "any"; `nonempty`: only sessions with messages; `session_id`, `session_id_prefix`, `parent_session_id`: exact filters; `limit`, `offset`: one page. Returns the page and how many rows match in all. | | `mare.store.index_warn_unsupported(paths)` | | | `mare.store.index_reconcile()` | Make the index agree with the session files: unchanged files are only stat'ed, changed ones caught up, unknown ones added, rows of deleted files dropped (the session plugin runs it in the background at startup). | | `mare.store.index_rebuild()` | Re-derive every row from the session files in one transaction (order and resume checkpoints kept). Returns the row count. | | `mare.store.index_notice()` | Why the index had to be rebuilt in this process (a damaged file or a schema version change), once; nil when it wasn't or the reason was handed out. | | `mare.store.file_contains(path, query)` | | | `mare.store.project_items(entries)` | Project session journal entries to message and tool-call items; control records are omitted. | | `mare.store.search_sessions(opts, execution)` | Cwd-scoped policy-bound history, ONLY in tool execution context. Cwd comes from the call. Directory and each candidate must satisfy frozen read policy; denied metadata is omitted. No host index. Native session/agents-run containers only, never attachments or links. At most 10000 readable files/directories, nesting 32; headers <=64 KiB. Selected raw snapshots <=32 MiB total / 8 MiB each. Exceeding a budget is QUERY_BUDGET_EXCEEDED, never silent omission. Session/time filters run on authorized headers first, so a narrowed retry can fit the budget. Message text literal FTS5 phrase (unicode61), 1..512 chars (or title_query); query syntax remains inert data. Match-count descending, text-length ascending, time descending, stable id/seq tiebreaks; each session returns its strongest event. Pages default to 20 results. Opaque cursor binds corpus revision, query and filters; any observed corpus change rejects old cursors as stale. incomplete marks skipped sources. | | `mare.store.search_events(opts, execution)` | Same authority/bounds/corpus revision as search_sessions; all matching events in one session. seq is the zero-based position in the strict complete-entry snapshot (header is zero). text_offset is a Unicode character offset in the original flattened message text. | | `mare.store.search_items(opts, execution)` | Search semantic message and tool-call items in one session under the same history policy. | | `mare.store.read_event(opts, execution)` | Exact raw event at an opaque event_id from a hit, plus bounded neighbor summaries. before/after each 0..10. Single event >64 KiB is refused inline (QUERY_EVENT_TOO_LARGE); pass offset/max_bytes for UTF-8 bounded chunked reads. Corpus revision changes reject old event ids; missing/other-cwd/unreadable targets share errors. Does not load or switch sessions. No child-agent traversal. No persistent query cache. | | `mare.store.read_item(opts, execution)` | Read a semantic item in one authorized session; event tokens are not item IDs. | | `mare.store.trace_item(opts, execution)` | Trace the journal surface of a semantic item using its session-scoped ID. | | `mare.store.trace_session(opts, execution)` | Genuine persisted/live lineage from authorized V3 header.parent_session_id, never directory inference. Only visible headers enter the projection. An unavailable parent is an anonymous boundary, no hidden parent id/title/path. complete describes the known parent chain, not a global corpus. Max 1000 nodes / descendant depth 32; over-budget/cycles/source changes fail explicitly. | | `mare.store.trace_event(opts, execution)` | Event surface projection and lineage trace (compaction replacement chains, branch summaries, tool call/result links) for one event by event_id or (session_id, seq). | ## mare.stream Defined in `types/mare/stream.lua`. | | | |---|---| | `mare.stream.buffer()` | | | `mare.stream.coalescer()` | | ## mare.subagent Defined in `types/mare/subagent.lua`. | | | |---|---| | `mare.subagent.start(opts)` | Low-level host primitive: start an independent child agent VM + thread directly. Distinct from the `subagent` contract service's `ctx.subagent:start`, which layers agent type lookup, tool ceilings, and session fork snapshots on top of this primitive. Root config `agents.max_active` (default 16) bounds all live descendant threads, including startup/shutdown; `agents.max_depth` (default 4) bounds edges from the root (zero disables children). Descendants cannot override these limits. Admission errors carry structured codes (`subagent.limit_reached`, `subagent.tree_closed`, `subagent.duplicate_name`, `invalid_arguments`). cancel() cancels this child and its descendants. Host shutdown closes admission and waits for all descendant cleanup; cancellation is cooperative, not forced OS-thread termination. The sub-agent's prompt (its VM's agent layer): `persona` replaces the identity (interpolated), `sections` adds or shadows sections ({name, order, text, tag?, raw?, interpolate?, complete?}, text a string) for this sub-agent only, `system` is the whole prompt (verbatim). `params` are the sub-agent's model-parameter selections (its agent layer, above its config and below its own session): on the parent's current model it starts with the parent session's values, `effort` = `params.effort`, `params` wins. The parent's parameter rules (`mare.params{}`, `mare.model{ params = }`) reach it with their Lua functions. In a saved, writable parent session, the host creates and writes a child transcript and assigns its identity. This is a message transcript, not a recoverable tool-state journal: child mode retains its no durable-start/ack gate and no crash-recovery semantics. `run_id` and `seq` are optional grouping metadata, not binding credentials. An ephemeral or read-only parent does not record a child transcript. A direct tool call against an as-yet-unsaved writable parent fails; an ordinary agent turn saves the parent before it starts its tools. | | `mare.subagent.drain_session()` | Close admission for the current session and wait for its children and lifecycle events. | | `mare.subagent.tool_allowed(name)` | Whether the host's inherited tool ceiling permits this tool name. | | `mare.subagent.list()` | List subagents spawned by the current parent session. | | `mare.subagent.get(id)` | Get a subagent by subagent_id or unique name in the current parent session. | | `mare.subagent.wait(id, opts)` | Wait for a subagent to finish (non-consuming; timeout/cancel does not cancel the child). | | `mare.subagent.steer(id, text)` | Steer a running subagent. | | `mare.subagent.cancel(id)` | Cancel a subagent by subagent_id or name. | | `mare.subagent.identity(subagent_id)` | A host-owned binding in the current parent session. For display association only. | | `mare.subagent.uncarried(value)` | What of a config value would not reach a sub-agent's VM: "<function site>: <reason>" for each function inside it that can't be carried (it captures a userdata, a thread or a built-in the globals don't reach). `mare doctor` uses it for the parameter rules. | | `mare.subagent.take_rule(token)` | The sub-agent rule the parent's approval dialog showed and the user chose to remember, once, by the `rule_token` of its `pipeline/approval-decided` event (the permissions plugin persists it). | | `mare.subagent.rule_lift(call, info)` | In a sub-agent sharing its parent's permission configuration (the tools service calls it): lift the inherited ceiling for this allowed call when the parent's rules allow it too. | | `mare.subagent.permission_lift(call)` | Apply host-owned scoped grants to a frozen call's ceiling. No caller-supplied grant is trusted. | | `mare.subagent.permission_commit(call, permissions, scope)` | Commit the intersection of a pending host approval and the effective permissions. No matching pending approval means no grant; turn/session lifetime remains host-owned. | ## mare.task Defined in `types/mare/task.lua`. | | | |---|---| | `mare.task.spawn(fn, ...)` | | | `mare.task.sleep(ms, cancel)` | | | `mare.task.channel(capacity)` | | | `mare.task.token()` | | | `mare.task.select(...)` | Run functions concurrently; abort losing branches and wait for their Lua tasks to finish before returning the first branch's index and results. Cancelling select requests abort of every branch. A losing branch's cancellation or closing error does not replace the winner. Synchronous code and closing hooks can delay cleanup; separately spawned tasks, blocking work, processes and remote side effects may continue after the Lua task ends. | | `mare.task.timeout(ms, fn, ...)` | On timeout, closes the callback's Lua scope before returning false, including in a tool context. Independently spawned work and blocking operations can still outlive the callback. | | `mare.task.now()` | | | `mare.task.call_sync(fn, ...)` | Synchronous call in the same execution context; yielding is an error. | | `mare.task.publish(fn, ...)` | Host-only synchronous publication. A thrown error or yield poisons readiness before returning. Does not roll back callbacks/IO; prepare everything before publishing. | | `mare.task.fail_session(reason)` | Host-only unrecoverable publication diagnostic; blocks future admission until rebuilt. | | `mare.task.session_error()` | Current unrecoverable session publication diagnostic, or nil when healthy. | | `mare.task.spawn_completion(ctx, fn)` | Start a completion task owned by ctx. Registration failure poisons the Host synchronously. Refused in tool contexts, including full-access/inherited tools. | | `mare.task.clock()` | | | `mare.task.id()` | Identifier of the running async task, or nil outside a Tokio task. | | `mare.task.is_token(value)` | | | `mare.task.yield()` | | ## mare.test Defined in `types/mare/test.lua`. | | | |---|---| | `mare.test.host(opts)` | Create an isolated real plugin host (Cordis tree, loader, event bus, and contract admission). Any test host not explicitly disposed is disposed automatically when its test case finishes. | | `mare.test.describe(name, fn)` | Group related spec cases under a named suite (may be nested). | | `mare.test.it(name, fn)` | Define a single spec test case. Cases within the same spec file share an isolated file-level Lua environment (use `before_each` / `after_each` to reset shared state). | | `mare.test.before_each(fn)` | Register a hook that runs before each test case in the current suite and its nested suites. | | `mare.test.after_each(fn)` | Register a hook that runs after each test case in the current suite and its nested suites. | ## mare.test.expect Defined in `types/mare/test.lua`. | | | |---|---| | `mare.test.expect.eq(actual, expected, msg)` | Assert that `actual` equals `expected` (deep structural equality for tables). | | `mare.test.expect.ne(actual, unexpected, msg)` | Assert that `actual` does not equal `unexpected` (deep structural equality for tables). | | `mare.test.expect.truthy(value, msg)` | Assert that `value` is truthy (neither `nil` nor `false`). | | `mare.test.expect.falsy(value, msg)` | Assert that `value` is falsy (`nil` or `false`). | | `mare.test.expect.error(fn, pattern, msg)` | Assert that calling `fn` raises an error, optionally matching Lua pattern `pattern`. | | `mare.test.expect.match(str, pattern, msg)` | Assert that string `str` matches Lua pattern `pattern`. | | `mare.test.expect.snapshot(value, name)` | Assert that `value` matches the stored snapshot beside the spec file (`snapshots/<spec_stem>__<name>.snap`). When `name` is omitted, it is derived from the current test case name. | | `mare.test.expect.settled(host, msg)` | Assert that every loaded plugin in `host` has settled cleanly (all loaded plugins are `"ACTIVE"` with no failures or pending dependencies). | ## mare.text Defined in `types/mare/text.lua`. | | | |---|---| | `mare.text.redact(value)` | Redact credential-looking strings and sensitive keys in tables recursively. | | `mare.text.regex(pattern)` | | | `mare.text.truncate(s, opts)` | | | `mare.text.cut(s, n, opts)` | The first (`keep = "head"`, default) or last `n` units of `s`, never splitting a UTF-8 sequence. `unit = "bytes"` (default): at most `n` bytes, the cut moved inward to a character boundary; `unit = "chars"`: `n` code points (raw bytes when `s` isn't valid UTF-8). | | `mare.text.tokens(s)` | The one token estimate (compaction, /context, providers): a string is bytes / 4; a table is its JSON size with each inline image counted as `image_tokens`, not its base64 payload, plus any wire-declared estimation hints registered via `register_estimate_hint`. | | `mare.text.register_estimate_hint(name, hint)` | Register namespaced (`<namespace>:<id>`) token-estimation hints for a wire format; returns an idempotent disposer function. | | `mare.text.yaml(s)` | Parse the first document of a YAML 1.2 stream (yaml-rust2) into Lua values. | | `mare.text.frontmatter(text)` | A leading `---` YAML block (SKILL.md, prompt templates). BOM and CRLF are normalised; a block that isn't valid YAML is read as `key: value` lines and `warning` says why. | | `mare.text.width(s)` | | | `mare.text.trunc_width(s, w)` | | | `mare.text.sanitize(s)` | | | `mare.text.fuzzy(query, items, limit)` | | | `mare.text.closest(word, candidates)` | Nearest candidate to `word` within a small optimal-string-alignment edit distance, or nil. `candidates` may be a string list or a table whose string keys are candidate names. | | `mare.text.replace(content, old, new, all)` | | | `mare.text.patch_paths(patch, opts)` | Parse patch paths without opening any of the named files. With `opts.resolve = true`, relative paths are resolved literally against cwd (matching `apply_patch`). | | `mare.text.apply_patch(patch, opts)` | | | `mare.text.diff(old, new, opts)` | Unified diff of two texts (`context` lines around each hunk, default 3; `a/<path>` and `b/<path>` headers), with the added and removed line counts (as `diff_stats`) and the longer side's line count (`ui.Diff{unified=, lines=}`) from the same diff. | | `mare.text.diff_stats(old, new)` | | | `mare.text.split_lines(s, from, to)` | Lines of `s` (`\n` or `\r\n` ends one; a final line break adds no empty line) and their count. With `from` only lines from..to (1-based, inclusive, `to` default the last) are returned, so a window of a big text builds only its own strings; `total` counts all. | | `mare.text.is_utf8(s)` | Whether `s` is valid UTF-8 (what strict `utf8.len` accepts), checked in Rust. | | `mare.text.shell_split(cmd)` | POSIX-shell word splitting (nil when quoting is malformed) and whether the command uses compound syntax outside quotes (`;` `&` `\|` `<` `>` newline, `$(…)`, backticks). Command rules must never match a compound command by its first words. | | `mare.text.shell_parse(cmd, opts)` | Parse a shell command into plain-word segments joined by `&&` `\|\|` `;` `\|`. `analyzable = false` (with `reason`) for substitutions, expansions, subshells, redirections other than fixed sinks (`/dev/null`, `2>&1`), `eval`, nested shells beyond one `bash -c '…'` level, syntax errors, unknown syntax or an exhausted budget. `script` is the inner script of a `bash -lc '…'` / `pwsh -Command '…'` wrapper. PowerShell uses a conservative lexer (plain words, `\|`, `;` only). `safe_sinks`: extra fixed redirect targets that keep a command analyzable (e.g. "/dev/stderr"). Each segment's `unwrapped` is for conservative denial/prompt matching, never allow rules. `literal_paths` contains only statically identifiable argv words; it is not a complete inventory of the paths a script can access. | | `mare.text.dangerous(cmd, opts)` | Built-in dangerous-command rules: the rule a command hits ("forced_rm": rm -f/--force or find -delete anywhere, through sudo/env/trap/ bash -c/heredocs/command/exec/nohup/timeout/xargs/find -exec; a script too long to parse or with a syntax error falls back to a plain word scan, so it fails closed; "windows_force_delete": Remove-Item -Force, del /f, rd /s /q — on Windows or for PowerShell), or nil; plus every literal command in the script (argv lists) so plugins can add their own. | | `mare.text.retain(s, opts)` | UTF-8 safe head/tail preview; suffix is kept intact inside both budgets. Errors if it cannot fit. | | `mare.text.decode(bytes, charset, opts)` | Strictly decode at most 5 MB using a declared WHATWG charset (default UTF-8). Unknown charsets and malformed sequences raise an error; no replacement characters. | | `mare.text.html_to_markdown(html, opts)` | Convert HTML on a worker thread, skipping script/style/head/template/noscript and embedded content. Parsed hidden/aria-hidden, hidden inputs and inline display/visibility remove their subtrees. External stylesheets/computed CSS are not evaluated. Hidden/template nodes still count toward work limits. max_tags bounds parse complexity (100000); DOM traversal checks max_nodes (50000) and max_depth (128) before recursive conversion. Ordinary wide pages are supported. Input and output ceilings are 5 MB and 1 MB; truncation preserves UTF-8. | ## mare.time Defined in `types/mare/time.lua`. | | | |---|---| | `mare.time.query(query)` | Synchronous, deterministic, bounded queries. Instants are integer epoch milliseconds in years 0001..9999; explicit local instants reject gaps/folds. Calendar/Cron/RRULE recurrence skips gaps and chooses earlier folds. Exhausted next_ms is mare.json.null (JSON null), never false or zero. RRULE is the bounded two-line DTSTART/RRULE profile: six frequencies, COUNT <=1000, one BYSECOND, <=10080 candidates per period, <=31 effective BYSETPOS selectors; unsupported/duplicate fields, invalid combinations and unsafe integers reject. normalize applies the stricter new-rule authoring profile; next/resolve retain supported historical ineffective BYSETPOS rules. Cron normalization preserves the Vixie star flag. Errors return nil, diagnostic; no work is scheduled. No resource handles to dispose. Synchronous bounded calculation does not accept a cancellation token or yield mid-query. | ## mare.tool Defined in `types/mare/config.lua`. | | | |---|---| | `mare.tool.command(def)` | Register a tool that runs a command template. | | `mare.tool.describe(name, text)` | Override the model-facing description of a tool. | ## mare.tools Defined in `types/mare/config.lua`. | | | |---|---| | `mare.tools.disable(names)` | | ## mare.webserver Defined in `types/mare/webserver.lua`. | | | |---|---| | `mare.webserver.get()` | | | `mare.webserver.list_routes()` | | | `mare.webserver.list_assets()` | | | `mare.webserver.register_route(owner_name, path, opts)` | | | `mare.webserver.register_assets(owner_name, dir, opts)` | | ## mare.workspace Defined in `types/mare/workspace.lua`. | | | |---|---| | `mare.workspace.dirs()` | Return the active workspace directories (primary root first). | | `mare.workspace.check(path, peers)` | Validate a candidate additional workspace directory (existing physical absolute directory, no protected-path or deny_read overlap, within the active sandbox ceiling). Returns the canonical path, or `nil, err`. | | `mare.workspace.set_dirs(dirs)` | Atomically replace the additional workspace directories (the primary root stays first). Validates every candidate root (same rules as `add`) before mutating; rejects all-or-nothing. | | `mare.workspace.add(dir)` | Add a workspace directory (resolved via `mare.fs.resolve`); returns true if newly added. | | `mare.workspace.remove(dir)` | Remove an added workspace directory (the primary root cannot be removed). | | `mare.workspace.contains(p)` | Whether path `p` lies inside any active workspace directory. | ## ui Defined in `types/mare/ui.lua`. Also reachable as `mare.ui.*` (`mare.ui = ui`). | | | |---|---| | `ui.Span(text, style)` | | | `ui.Line(spans)` | | | `ui.Paragraph(x, indent)` | Word-wrapped line; continuation lines get `indent`. | | `ui.Lines(items)` | | | `ui.Markdown(text)` | | | `ui.Code(code, lang)` | | | `ui.Diff(t)` | `{old=, new=, path=}` diffs two texts (3 lines of context); `{unified=}` renders an existing unified diff, with `path` (highlighting for every row instead of the `+++` headers) and `lines` (the longer side's line count, for the gutter width) it renders a 3-line-context `mare.text.diff` exactly like `{old=, new=, path=}` of the same texts. | | `ui.Indent(first, child, rest)` | | | `ui.Gap(n)` | | | `ui.Spinner(label)` | | | `ui.Frames(frames, ms, still)` | A frame animation the core plays by wall-clock time (`still` under reduce_motion). | | `ui.Row(items)` | Nodes side by side on one row (the first line of each). | | `ui.Clip(child, max, tail)` | | | `ui.Block(child, opts)` | Bordered panel: title in the top border, footer (`3 of 42`) in the bottom one. `border_style` is a named style (MareBorder / MareBorderActive / MareBorderSearch); the charset follows `mare.o.border` unless `border` is given. | | `ui.List(items, opts)` | Virtually scrolled list: only `height` rows around `selected` (1-based) are drawn; inside a Block it gets a scrollbar. Selection = full-width MareSelection when focused, bold otherwise. | | `ui.Split(left, right, opts)` | Two panes (list + preview); stacked when narrower than `stack_below` (default 84) columns. | | `ui.Segments(list, side)` | Status capsules (Yazi): Powerline caps with a Nerd Font, padded background otherwise. | | `ui.Gauge(frac, width)` | | | `ui.icon(name)` | Glyph for the active icon set (`mare.o.icons`): file, dir, command, branch, model, jobs, workflow, info, warn, error, sep_left, sep_right. Sets live in `ui.icons[set][name]`. | | `ui.detect_icons(caps)` | The icon set for `icons = "auto"`; `caps` defaults to `mare.ui.caps()` (`emoji_wide = false` → "ascii"). | | `ui.color_depth()` | Terminal color depth: "truecolor" \| "256" \| "16" \| "none" (env MARE_COLOR overrides; NO_COLOR gives "none"). | | `ui.set_color_mode(option)` | Recompute and apply the terminal color depth from `option` (or `mare.o.terminal.color`), environment variables, and probed capabilities, returning the active depth. | | `ui.KeyHints:render(hints)` | The status bar while an overlay is open. | | `ui.Tabs:render(names, active, title)` | A panel's views as its border title (`Running │ All`). | | `ui.Select:frame(s)` | The frame of a list overlay; the core adds the rows, the search text and the count. | | `ui.Confirm:render(c)` | The yes / no dialog, drawn `c.width` cells wide (normally a ui.Block). | | `ui.Logo:lines()` | | | `ui.Logo:render(info)` | | | `ui.Logo:compact(info)` | | | `ui.icon_set()` | | | `ui.set_theme_data(opts)` | Update interface-shell theme & glyph data (omitted fields stay unchanged; `glyphs = false` restores the built-in spinner glyphs). | | `ui.Working:render(info)` | | | `ui.image(opts)` | An image node: the terminal's protocol (Kitty / iTerm2 / sixel) or a one-line placeholder; fitted into max_rows × max_cols cells (defaults 16 × 80). | | `ui.filetype_style(path)` | Named style for a path by file type (Yazi filetype; rules in `ui.filetypes`). | | `ui.file_icon(path)` | | | `ui.Checklist(items)` | | | `ui.connected()` | | | `ui.can_respond()` | Whether this frontend currently has an interactive responder (including RPC UI hosts). | | `ui.display_path(path, max_width)` | A directory for display: home as `~`, longer than `max_width` cells → `…/last/components` (the rule the welcome line, the status bar and the trust question share). 0/nil = no limit. | | `ui.width()` | | | `ui.height()` | | | `ui.push(kind, t)` | Push a transcript block; returns its id. kind: "user"\|"assistant"\|"reasoning"\|"tool"\|"info"\|"error"\|... | | `ui.update(id, t)` | | | `ui.append(id, text)` | Streaming append (fast path). | | `ui.finish(id)` | Mark a block finished: it is committed to terminal scrollback in order. | | `ui.remove(id)` | | | `ui.print(node)` | | | `ui.set_widget(id, slot, node, order)` | | | `ui.set_status(id, align, node, order, keep)` | | | `ui.working(label, detail, opts)` | | | `ui.notify(text, level, opts)` | | | `ui.notification_history()` | Recent TUI notifications, oldest first (up to 200 entries). | | `ui.select(t)` | Items may carry a `preview` node (shown in a pane next to the list); `tabs` gives tabbed views (switch with Tab or [ ]); `kind = "confirm"` draws a centered [Y]es [N]o dialog. `body` (a string or a list of lines) is shown above the options (e.g. the trust overlay). `multi = true` returns an array of checked 1-based indices in the active tab: Space toggles the highlighted item and Enter confirms. While typing a search, Space is part of the filter; move to a result to resume toggling. Esc clears search before cancelling. `accept_label` changes the accept hint (an empty string hides it); `allow_search = false` disables searching. `keys` adds action keys (shown in the hint bar): pressed while not searching they return the highlighted item plus that key (e.g. `w` = write to file in /copy's picker); `"ctrl+d"` keys also work while searching (so letters can always search). An item with `header = true` is a group heading: shown, never selected, hidden while searching. The search is fuzzy; `re:<regex>` and `"exact phrase"` (case-insensitive) narrow it. `vim = true`: j/k (with a count prefix), g/G and h/l (tabs) move when typed before a search; ←/→ switch tabs anyway. `on_highlight(index, tab) -> node\|nil` builds the preview of the highlighted item lazily. `title_right` (a string, drawn muted, or a `ui.Line`) ends the top border, e.g. the current sort and filter; a narrow box shortens it, then leaves it out (the title always wins). `split = { ratio, min }`: on a wide terminal (84 columns and more) with a preview pane, the list takes `ratio` of the popup (default 0.4), at least `min` columns (default 24); the preview keeps at least 20. The 4th result is the search text then (re-open a picker after an action without losing it). A `filter` given up front opens in searching mode: the first Esc clears the search, the next one closes the select. `on_open(sel)` is called once the select is open with its handle: `sel:update(items)` replaces the items in place while the user is in it (an index that caught up, a list still loading), keeping the search text, the searching state and the highlighted item — found again by the item's `item_id`, else by its label. The index the select returns refers to the latest items. Dismissal returns `nil, "cancelled"`; Ctrl+C returns `nil, "interrupted"`. A `cancel` token returns `nil, "cancelled"`. When no UI responder is available, returns `nil, "unavailable"`. Ctrl+C cannot be declared in `keys`. | | `ui.approve(t)` | Dedicated trusted human approval prompt: native code renders the title, bound arguments, and fixed choice/key mapping, returning the chosen decision and a one-time native receipt. | | `ui.input(t)` | Returns `nil, "interrupted"` for Ctrl+C, `nil, "unavailable"` when no UI responder is available, or `nil, "cancelled"` for other dismissals and `cancel`. | | `ui.editor(t)` | Returns `nil, "interrupted"` for Ctrl+C, `nil, "unavailable"` when no UI responder is available, or `nil, "cancelled"` for other dismissals and `cancel`. | | `ui.questions(t)` | Returns `{ answers = {}, dismissed = true, reason = "cancelled"\|"interrupted" }` when dismissed, `nil, "cancelled"` when cancelled via `cancel`, or `nil, "unavailable"` when no UI responder is available. | | `ui.overlay(title, node, opts)` | | | `ui.transcript(title, node, opts)` | Full-screen transcript view (Ctrl+T style) showing `node`. Calling it again with the same title while open refreshes it in place (keeps the scroll position, follows the end). `opts.keys`: the view's own keys for its header, e.g. `{ { action = "agents.back", label = "list" }, { action = { "agents.prev", "agents.next" }, label = "agent" } }` → `Esc list · Alt+←/Alt+→ agent · ↑/↓ PgUp/PgDn …`: the keys bound to those transcript-layer actions now (an action without a key is left out), so a rebind changes the header. | | `ui.transcript_title()` | Title of the plugin transcript view while it's open, else nil. | | `ui.transcript_close(title)` | Close the plugin transcript view (e.g. Esc in a child's view going back to a list); with `title`, only while it shows that title. The Ctrl+T transcript is left alone. Commands keep their order: `ui.transcript_close(t); ui.select{…}` opens the list on the main screen. | | `ui.set_editor(text, opts)` | `keep_draft = true`: leave a non-empty input alone (the user's draft wins; /tree, /fork, /undo). `prepend = true` restores before any newer draft. `images` contains attachment blocks in marker order; colliding image markers are remapped while preserving the newer draft. | | `ui.get_editor()` | | | `ui.editor_state()` | | | `ui.editor_cursor()` | | | `ui.set_editor_cursor(row, col)` | | | `ui.editor_selection()` | | | `ui.set_editor_selection(anchor, head)` | | | `ui.editor_insert(text)` | | | `ui.editor_replace(range, text)` | | | `ui.flag(name, value)` | Frontend display switch: "show_reasoning" (full reasoning instead of "Thought for N s"), "expand_all" (the Ctrl+O compact/expanded view). | | `ui.set_queued(n)` | How many messages wait in the agent queue (with an empty input, ↑ emits `input/queue-select` and Enter emits `input/queue-menu`). | | `ui.set_queue_mode(mode)` | The queue editing state the key handler routes by: 0 nothing selected, 1 a queued message selected (↑/↓ emit `input/queue-move`, Enter `input/queue-edit`, Delete `input/queue-remove`, Esc `input/queue-cancel`), 2 one being edited (Esc emits `input/queue-cancel`). | | `ui.editor_hint(text)` | | | `ui.keymap()` | The input's key bindings, `{ key = action }` (each key's topmost binding; `mare.keymap.set` changes them). | | `ui.normalize_key(key)` | The canonical name of a key or key sequence ("<C-t>" -> "ctrl+t", "<C-x>g" -> "ctrl+x g"). | | `ui.theme(colors)` | | | `ui.clear()` | | | `ui.exit(opts)` | Leave mare. Without `force`, an exit guard (`ui.exit_guard`) gets to ask first. | | `ui.exit_guard(on)` | While on, a user's exit (quit keys, /exit) emits `app/exit-requested` instead of quitting; the guard's owner calls `ui.exit{ force = true }` once confirmed (the jobs plugin does this while background jobs run). | | `ui.render_text(node, width)` | | | `ui.style(name, spec)` | Set (or with one argument, read) a named style. | | `ui.styles()` | | | `ui.theme_style(name, spec)` | Set a theme default (not recorded as an explicit override; themes use this). | | `ui.style_overrides()` | Explicit `mare.ui.style` calls, which win over any theme. | | `ui.reset_style(name, spec)` | Drop the explicit override of `name` and restore `spec` as its default. | | `ui.override(name, fn)` | Wrap or replace `select`, `input`, `confirm`, or `notify`; layers stack (`next` delegates down) and `release()` removes this layer while preserving lower ones. | | `ui.confirm(prompt, default, opts)` | Returns true for Yes, false for No, or nil and the dismissal reason (`"cancelled"`, `"interrupted"`, or `"unavailable"`). | | `ui.editor_config(t)` | | | `ui.renderer(kind, r)` | Register a renderer. kind: "tool:<name>", "message:user", "message:assistant", "message:reasoning". | | `ui.get_renderer(kind)` | The topmost renderer registered for `kind`, or nil. | | `ui.entry_renderer(kind, r)` | | | `ui.get_entry_renderer(kind)` | | | `ui.markdown_transform(fn, opts)` | | | `ui.has_markdown_transforms(message_type)` | | | `ui.transform_markdown(text, context)` | | | `ui.UserMessage:render(text)` | | | `ui.TurnEnd:render(info)` | | | `ui.AssistantMessage:marker()` | | | `ui.Reasoning:render(text, secs)` | | | `ui.Reasoning:expanded(text, secs)` | | | `ui.Notice:render(text, level)` | | | `ui.ToolCall:verb(name, state)` | The tool's verb for `state`: present while running, past when done; nil when it has none. | | `ui.ToolCall:header(summary, state, source)` | | | `ui.ToolCall:body(node)` | | | `ui.ToolCall:result_text(text, is_error, expanded)` | | | `ui.ToolCall:render(call, result, expanded, info)` | | | `ui.ToolCall:running(label)` | The head of a running call: a spinner, or a steady pending dot when `still` is set. | | `ui.ToolCall:has_diff(node)` | Whether `node` is, or holds, a diff (edit / write / apply_patch results). | | `ui.status(id, spec)` | Register or update a status bar segment; returns a release function. | | `ui.status_redraw(id)` | Redraw one registered status segment (`id`) or all of them (`nil`). | | `ui.Editor:apply()` | | | `ui.EditorChrome:render(s)` | | | `ui.NoticeCard:render(p)` | | | `ui.CompletionPopup:render(p)` | | | `ui.WhichKey:render(p)` | | | `ui.HelpModal:frame(s)` | | | `ui.InfoModal:frame(s)` | | | `ui.InputModal:frame(s)` | Secret inputs use a protected core frame and do not call this method. | | `ui.SelectRow:render(item)` | | | `ui.notify_os(text, opts)` | Desktop notification (OSC 9 / 777 / kitty 99, tmux & screen passthrough, BEL fallback); returns false when suppressed. | | `ui.set_title(text)` | Set the terminal window title (OSC 2); no-op without a TUI. | | `ui.focused()` | | | `ui.caps()` | Terminal capabilities: static table + startup probe (DECRQM 2026/2027, XTGETTCAP, kitty keyboard, cursor position) + the `terminal_caps` option + `ui/caps` listeners. `width_method` is the width rule ("unicode" = grapheme clusters, "wcwidth" = code point by code point; set it through `terminal_caps` or `MARE_WIDTH_METHOD`); `emoji_wide = false` switches `icons = "auto"` to the ASCII set. | | `ui.slow_frames()` | Frames that took longer than 16ms, newest last (128 kept): {at_ms, ms, what}. | | `ui.syntax_theme(document, validate_only)` | Validate and select a tmTheme XML document; nil restores background-based syntax defaults. Invalid or >1 MiB documents throw without changing the active document. | | `ui.markdown_blocks(text)` | Native Markdown parser boundaries, shared by live/replayed code presentation. Indented code and inline code are not fenced blocks. This function does not invoke renderers or IO. | | `ui.PresentedMarkdown(text, blocks)` | Pure cached presentation node. Invalid/duplicate block offsets are rejected; absent offsets render the original code card. Images use the existing frontend image protocol. The caller must retain source fallback when an artifact or image capability is absent. | | `ui.validate_node(node)` | Validate conversion to a cached frontend node. Returns false for nil/unsupported empty descriptors, throws for invalid typed fields; performs no rendering or filesystem IO. | | `ui.snapshot_node(node)` | Bounded immutable component-description copy, preserving binary image bytes. No callbacks, userdata or cycles; <=64 nesting levels/50000 entries/32MiB content. Does not render or do IO. | | `ui.node_to_wire(node)` | Existing component descriptions as JSON-safe wire values. Images require bytes (<=8MiB each), become canonical padded base64 `data`, and omit local paths. Plain text must be UTF-8. Empty component arrays retain their array identity. No closures, handles or terminal IO. | | `ui.node_from_wire(wire)` | Decode that same description into Lua component tables. Image data is strictly bounded canonical base64; incoming raw bytes/local image paths are refused. No image validity claim. | | `ui.image_id()` | Allocate a nonzero native image occurrence id (fails on exhaustion). ui.image allocates once when omitted. Keep the id with that logical component across redraws; create a distinct id per occurrence even for identical pixels. Content encoding caches remain shared. Caller scope/document disposal removes components; ids are not authorization or durable artifact handles. Wire ids belong to the source frontend namespace; node_from_wire allocates fresh local ids, so keep the decoded description across redraws. | | `ui.set_layout(layout, opts)` | Configure the stacked region layout (`ui.layout`). Errors on invalid region names, missing `editor`/`status`, duplicate regions, or invalid region options, keeping the previous layout. Pass `{ persist = false }` to apply the layout without writing `mare.o.ui.layout`. | | `ui.set_viewport(width, height)` | Set the frontend viewport dimensions (each in `1..=10000`). Returns `true` if either dimension changed. | | `ui.set_ambiwidth(mode)` | Set the width rule for East Asian ambiguous characters (`"single"` or `"double"`). | | `ui.layout_revision()` | Opaque process layout revision; changes on theme/style/width-rule writes. Pure observation, not a session identity. Used to coalesce presentation invalidation without polling or IO. | | `ui.image_resolver(namespace, load)` | Register a scoped, asynchronous image-byte resolver (64 namespaces maximum). Callback executes in a fresh ephemeral read-only execution. Native workers queue at most 16 pending requests per resolver; reads settle within 30s. Disposal cancels loads and evicts that registration's materialized bytes. Re-registration has a new identity. | | `ui.image_resource(namespace, key, width, height)` | Create a small immutable resource description without reading storage. key must include the storage owner/session_epoch; the resolver must enforce actual storage authorization. Wire descriptions omit native resolver identity and rebind only to a local namespace. | | `ui.image_cache_info()` | | ## ui.Confirm Defined in `types/mare/ui.lua`. Also reachable as `mare.ui.*` (`mare.ui = ui`). | | | |---|---| | `ui.Confirm.label(s)` | | ## ui.TurnEnd Defined in `types/mare/ui.lua`. Also reachable as `mare.ui.*` (`mare.ui = ui`). | | | |---|---| | `ui.TurnEnd.duration(secs)` | `secs` as "42s" or "3m 05s". | | `ui.TurnEnd.tokens(n)` | A token count as "512", "1.2k" or "3.4M". | ## ui.completion Defined in `types/mare/ui.lua`. Also reachable as `mare.ui.*` (`mare.ui = ui`). | | | |---|---| | `ui.completion.register(spec)` | | | `ui.completion.collect(ev)` | | | `ui.completion.list()` | | ================================================================================ Title: Plugins Section: Extend URL: https://signalridge.github.io/mare/en/extend/plugins/ Markdown: https://signalridge.github.io/mare/raw/en/extend/plugins.md Source: docs/en/extend/plugins.md ================================================================================ # Plugins What a mare plugin is: where plugins load from, the fields of a plugin definition, lifecycle, turning built-ins on and off, and how failures are contained. ## What a plugin is A plugin is a Lua file that returns one table. The table describes the plugin; its `apply` function does the work. ```lua -- ~/.config/mare/plugins/hello.lua return { name = "hello", inject = { "commands" }, config_schema = { greeting = { type = "string", default = "hello", desc = "what to say" } }, apply = function(ctx, cfg) ctx.commands:register("hello", { description = "Say hello", run = function() ui.notify(cfg.greeting) end, }) end, } ``` The top level of the file may define local constants and helpers using whitelisted standard-library names (`string`, `table`, `math`, `pairs`, and similar) and return the plugin definition table. Reading non-whitelisted globals (such as `mare` or `require`) or writing globals is an error that names the offending line. Put runtime work in `apply`. [Writing a plugin](https://signalridge.github.io/mare/en/extend/writing-a-plugin/) builds a complete one step by step. ## Where plugins load from mare collects plugin sources in this order. A later source has higher precedence. | Order | Origin | Location | |---|---|---| | 1 | `builtin` | Compiled into mare in release builds; debug builds read `crates/mare-plugin/preset/plugins/` from disk. A read-only copy is in the runtime directory (`mare runtime`). | | 2 | `package` | `plugins/` of each installed [package](https://signalridge.github.io/mare/en/configure/packages/), honouring its `only` list. | | 3 | `user` | `~/.config/mare/plugins/` | | 4 | `project` | `<project>/.mare/plugins/`, trusted projects only. | In a directory, `name.lua` and `name/init.lua` are plugins. Entries whose names start with `_` or `.` are ignored. Two plugins cannot share a name silently. A higher-precedence origin can replace a lower-precedence definition with the same name by setting `override = true`; without it, the later definition is refused and the error names both fixes (add `override = true`, or rename your plugin). If two definitions in the **same** origin share a name, both are refused and any lower-origin definition stays active — adding `override = true` does not resolve same-origin duplicates. Turning the earlier one off is no way around it: `enabled = false` closes the whole name, every source included. `/plugins` shows replaced plugins as `overrides built-in <name>`. A whole plugin definition can live in `<name>.lua` or `<name>/init.lua` (include `lua/` when it needs private modules) with `override = true`; placing a single helper module file alone does not shadow a plugin (for targeted test stubs, use `package.preload`). `--clean` loads built-in plugins only. ## Modules and `require` Every plugin — built-in and third-party alike — uses the same open `require` loader with owner-partitioned caches: 1. **Resolution order**: `package.loaded[name]` (global overrides and core modules) → `package.preload[name]` → the caller plugin's own `lua/` directory → core modules (`cordis*`, `mare_kernel*`, `mare_lib*`, `mare.test`) → other plugins by module root segment. 2. **Code is open, state goes through services**: cross-plugin `require` is for stateless helper code; runtime state and capabilities must go through Cordis services and events (`inject`/`provide`/`ctx:get`/`ctx.bus`). Call cross-plugin `require` inside `apply` (not at top-level definition load time) so all plugin `lua/` roots are indexed and dependency tracking records the edge for hot-reload. Modules run in their **provider's** environment, so any global written by a cross-plugin-required module stays in the provider's environment, not the caller's. 3. **Observable guarantees**: - Same-named modules in different plugins (e.g. `alpha/lua/util.lua` and `beta/lua/util.lua`) are cached in separate owner partitions and never collide. - If two plugins provide the same cross-plugin module root, cross-plugin `require` fails with an ambiguity error naming all providers (a plugin's own `lua/` still resolves locally first). - `mare_lib*` is owned by `core` (one shared instance per VM; reloading a plugin never evicts it). - Reloading a provider clears only its own module partition and automatically reloads plugins that `require`d its modules after the provider has rebuilt. - Overriding a built-in requires a full plugin replacement (`override = true`) or `package.preload`; public modules are declared with `---@meta <name>` in `types/`. ## The definition table | Field | Type | Meaning | |---|---|---| | `name` | string | Plugin name. Defaults to the file name. | | `inject` | string list | Services this plugin needs. It waits, without starting, until every one is provided. | | `provide` | string list | Services it provides (a `mare.Service`, see [Services and events](https://signalridge.github.io/mare/en/extend/services-and-events/)). Two enabled plugins cannot declare the same one: the later in load order is refused, and the error names both files. | | `contracts` | table | Method lists for new services it defines. See [Services and events](https://signalridge.github.io/mare/en/extend/services-and-events/). | | `config_schema` | table | The plugin's options, one entry each: `{ type, default, desc, choices?, min?, max?, fields?, items?, values?, variants?, on_invalid?, apply? }`. It gives the defaults `apply` receives as `cfg` and the checks every entry point runs (init.lua, `--set`, `MARE_*`, runtime `mare.plugin` writes). An invalid value is reported and keeps the default. `type = "union", variants = {…}` takes a value matching one form exactly. `on_invalid = "fail"` keeps the plugin from starting instead of falling back to the default (for a restrictive setting such as an approval policy). A runtime write is first offered to the owner on `option/apply` (an error there, such as a failed save, fails the write and nothing changes), then announced on `option/changed`. Users set options with `mare.plugin(name, {...})`. | | `config_api` | table | Functions that become `mare.<name>` in `init.lua`. See below. | | `apply` | function | `apply(ctx, cfg)`. Runs at start and after each reload. May yield. | | `required` | boolean | If it fails to start, every model request is refused until a full `/reload` succeeds. | | `override` | boolean | May replace a same-name plugin from an earlier source. | | `tags` | string list | Kind of plugin, read without running it. `"provider"` marks a model provider. | | `wires` | string list | The wire formats it registers with the `llm` service. | | `providers` | string list | The LLM provider names it registers with the `llm` service (read even when disabled, for status and attribution). | `cfg` is a merged copy of the `config_schema` defaults and whatever the user set in `plugins.<name>`, with tables merged recursively. `mare.plugin("hello", { greeting = "hi" })` changes `cfg.greeting`; an unknown key or a wrong type produces a warning with a "did you mean" hint, so declare every option in `config_schema`. ### Config functions `config_api` lets a plugin add functions to the configuration language. The key is a dotted path; the function receives the config table first. ```lua config_api = { ["greeting.set"] = function(C, text) C.greeting = text end, }, ``` After the plugin is installed, `init.lua` can call `mare.greeting.set("hi")`, and `apply` reads `mare.config.greeting`. The built-in `tools` plugin uses this for `mare.tool.command`. ### Provider packs Vendors are data, protocols are code, and names are only identifiers. A third-party plugin can ship OpenAI-compatible (or Responses-compatible) vendors as pure data entries without writing `stream` or `endpoint` callbacks, deriving `providers` from the same top-level table so declarations never drift: ```lua local PRESETS = { acme = { label = "Acme AI", wire = "openai-chat", dialect = "deepseek", base_url = "https://api.acme.example/v1", api_key_env = "ACME_API_KEY", key_prefixes = { "acme-" }, models_dev = false, default_model = "acme-v1", models = { { model_id = "acme-v1", context_window = 128000, max_output = 8192 }, }, }, } local NAMES = {} for name in pairs(PRESETS) do NAMES[#NAMES + 1] = name end table.sort(NAMES) return { name = "vendor-acme", inject = { "llm" }, tags = { "provider" }, providers = NAMES, apply = function(ctx) for _, name in ipairs(NAMES) do local entry = table.copy(PRESETS[name]) entry.provider = name ctx.llm:register_provider(entry) end end, } ``` Users can overlay any field of `acme` (such as `base_url`, `default_model`, `models`, or `wire_api`) with `mare.provider("acme", { ... })`, and unloading or disabling `vendor-acme` cleanly withdraws its providers and parameter rules. ## Lifecycle ![mare plugin lifecycle, override, and reload flow](https://signalridge.github.io/mare/assets/diagrams/plugin-lifecycle.svg) 1. mare reads every definition. A file that cannot be read is reported and skipped. 2. Plugins start in dependency order: a plugin waits until every service in its `inject` is provided, so the providers start first, then the rest in source order. A missing provider leaves its dependents waiting; plugins in a dependency cycle are rejected with `not loaded: dependency cycle`. 3. For each plugin, mare builds `cfg` and calls `apply(ctx, cfg)`. 4. Everything registered through `ctx` belongs to the plugin: listeners, services, timers, tasks, tools, commands, key bindings, status segments, and every `ctx:effect`. 5. On a reload or at exit, mare disposes the plugin, which withdraws all of that, and for a reload applies it again. The plugins that inject a service it provides restart with it. See [Runtime guarantees](https://signalridge.github.io/mare/en/extend/runtime-guarantees/) for what mare promises about this lifecycle, each promise pinned by a test. `ctx` has these methods and fields: | Member | Does | |---|---| | `ctx.<service>` | A service named in `inject`, for example `ctx.tools`. | | `ctx:get(name)` | A service by name, or `nil` while nobody provides it. For a service the plugin can run without. | | `ctx:inject({ name, ... }, fn)` | Run `fn(ctx)` while the named services are provided. What it registers is withdrawn when one goes away, and `fn` runs again when they are back. | | `ctx:on(event, fn, opts)`, `ctx:once(event, fn)` | Listen to an event. `opts.prepend = true` puts the listener first. Returns a function that removes it. | | `ctx.bus:emit`, `:emit_checked`, `:bail`, `:waterfall`, `:waterfall_checked` | Dispatch events (`inject = { "bus" }`). See [Services and events](https://signalridge.github.io/mare/en/extend/services-and-events/). | | `ctx.policy:voter`, `:rewriter`, `:decide` | Vote on, rewrite and ask decision points (`inject = { "policy" }`). | | `ctx:plugin(Class)` | Provide a service: `Class` is a `mare.Service` subclass. | | `ctx:effect(fn)` | Run `fn` now; the function it returns runs when the plugin goes away. | | `ctx:spawn(fn)` | Run a background task, cancelled on dispose (`inject = { "task" }`). | | `ctx:after(ms, fn)`, `ctx:every(ms, fn)` | Timers, cancelled on dispose (`inject = { "task" }`). | | `ctx.logger:warn(...)`, `ctx.logger:error(...)` | Write to the log under the plugin's name. An error is also recorded as the plugin's problem and sent as `kernel/error`. | | `ctx.kernel:reload(name)`, `:plugins()`, `:problems()` | Reload one plugin, or all; the plugin list and recorded failures (`inject = { "kernel" }`). | A plugin that is applied is also described by `mare.plugins.status(name)` and `mare.plugins.list()`. `mare.plugins.failures()` returns what failed at startup or in the last full reload. ## Turn built-ins on and off A single plugin, of any origin: ```lua mare.plugin("update-check", { enabled = false }) ``` A name is one slot across every source: `enabled = false` turns off the built-in and any package, user or project plugin of that name. Values from every layer are compared leaf by leaf, so a trusted project's `false` beats your `true`, and `--set plugins.<name>.enabled=…` beats both. The minimal plugin set is a preset: ```lua mare.setup { plugins = { preset = "minimal" } } mare.plugin("jobs", { enabled = true }) -- add back what you need ``` `minimal` turns off every built-in tagged neither `minimal` nor `provider`. The tagged `minimal` plugins are `agent`, `agent-approvals`, `approval-review-model`, `approvals`, `baseline`, `commands`, `context`, `conversations`, `fs`, `keymap-default`, `llm`, `permissions`, `session`, `statusline`, `theme-default`, `tools`, `ui`, and `webserver`, plus every built-in `provider` plugin (`provider-anthropic`, `provider-google`, `provider-openai`, `provider-openai-compat`, `provider-opencode-go`, and in debug or `faux`-enabled builds, `provider-faux`). A plugin that replaced a built-in with `override = true`, and every package, user or project plugin, is not affected. An explicit `enabled` in any layer beats the preset. An unknown preset name is a configuration error: it is reported and no preset applies (`--strict-config` refuses to start). `preset` is reserved, so no plugin can be named so. The built-in plugins, by area: | Area | Plugins | |---|---| | Core | `agent`, `baseline`, `cells`, `compact`, `context`, `conversations`, `fs`, `jobs`, `llm`, `mcp`, `message`, `proc`, `query`, `query-disk`, `session`, `spill`, `subagent`, `terminal`, `tools`, `tools-apply-patch`, `web`, `web-fetch-http`, `webserver` | | Providers | `provider-anthropic`, `provider-google`, `provider-openai`, `provider-openai-compat`, `provider-opencode-go`, `provider-faux` (debug builds or release builds compiled with the `faux` feature only) | | Safety | `permissions`, `approvals`, `approval-review-model`, `agent-approvals`, `repeat-guard` | | Interface | `ui`, `statusline`, `theme-default`, `keymap-default`, `commands`, `copy`, `images`, `file-ref`, `shell-mode`, `agents`, `review`, `changes`, `notify`, `usage`, `status` | | Housekeeping | `plugins`, `profile`, `lua-console`, `update-check`, `onboarding`, `user-config` | ## Inspect and reload `/plugins` lists every plugin with a filled dot when it is active, its origin, any override, and below that every recorded problem with its traceback. `mare doctor` includes plugin names defined twice. | Command | Does | |---|---| | `/reload` | Full host reload: re-runs `init.lua`, installs new packages, starts new plugins, unloads removed ones, reloads the rest, and emits `reload/completed`. | | `/reload config` | Re-runs `init.lua`, diffs plugin options, syncs enable/disable state, and retries pending items. | | `/reload <name>` | Replaces the named plugin definition in place (keeps the old definition if the new one fails to load). | A model request holds a lease from assembly to the end of streaming, so a reload cannot replace plugins under it. It is refused while a request is active; run it again afterwards. A plugin whose new definition fails to load keeps running on the old one. In a debug build, built-in plugin sources are read from `crates/mare-plugin/preset/plugins/` on every start, so editing one and running `/reload` is enough. In a release build, `MARE_DEV_PLUGINS=<dir>` makes mare read each built-in from `<dir>/<name>.lua` when that file exists. ## When a plugin fails Failures stay inside the plugin that caused them. | What fails | What happens | |---|---| | Definition cannot load (syntax error, forbidden top-level access) | The plugin is skipped. mare warns `requests continue without it`, and the TUI status line shows `plugin <name> failed · /reload`. | | `apply` raises an error | The plugin does not start. The error is recorded; other plugins start normally. | | A service in `inject` is not provided | The plugin waits, and starts once a provider appears. `/reload` reports what it waits for. | | A listener, task or timer raises an error | The error is reported as a notice and as a `kernel/error` event. The plugin keeps running. | | A voter raises an error or runs out of time | It counts as a `deny`. | | Lua runs without yielding for too long | The watchdog aborts the callback. | A failure blocks every model request, with the reason shown, when the plugin provides one of the essential services (`agent`, `llm`, `tools`, `permissions`, `approvals`, `session`), declares `required = true`, or comes from a required package (`required = true`). The block lifts when a full `/reload` succeeds. Failures in optional plugins or optional packages report a warning and let requests continue. The watchdog limit is `watchdog_ms`, 10000 by default. It is read before `init.lua` runs, so set it on the command line or in the environment: `mare --set watchdog_ms=20000` or `MARE_WATCHDOG_MS=20000`. A `pcall` around the runaway code does not swallow the abort. ================================================================================ Title: Plugin runtime guarantees Section: Extend URL: https://signalridge.github.io/mare/en/extend/runtime-guarantees/ Markdown: https://signalridge.github.io/mare/raw/en/extend/runtime-guarantees.md Source: docs/en/extend/runtime-guarantees.md ================================================================================ # Plugin runtime guarantees What mare promises a plugin author about lifecycle, services, registrations, reloads and cleanup. A plugin can rely on each of these; a change that breaks one is a breaking change. Behaviour not listed here is still documented in [Plugins](https://signalridge.github.io/mare/en/extend/plugins/) and [Services and events](https://signalridge.github.io/mare/en/extend/services-and-events/), but it is not part of this list. Each promise has a key. To find the tests for a promise, search for its key: `rg 'guarantee: effects-dispose-in-reverse-start-order'`. ## Dependencies and waiting | Key | Promise | |---|---| | `inject-waits-instead-of-failing` | A plugin whose `inject` names a service nobody provides is not a failure: it waits (PENDING), the host reports what it waits for, and it starts as soon as a provider appears. | | `inject-cycle-refused-and-the-rest-starts` | Plugins that inject services only each other provide are refused before they run; the problem names the cycle, and every plugin outside the cycle starts normally. | | `dependents-stop-before-their-provider-and-restart-on-the-new-one` | When a provider is reloaded or replaced, the plugins that inject its service are disposed before it and started again on the new provider, never left on the old one. | | `dependent-waits-while-its-provider-is-gone` | When a provider goes away, its dependents are disposed (their cleanups run) and wait; that is not a failure, and they start again when a provider comes back. | | `provider-outlives-dependents-in-flight-cleanup` | A provider's disposal waits for the cleanups its dependents are still running, so a dependent's cleanup can still call the service it was started on. | ## Services | Key | Promise | |---|---| | `one-provider-per-service-name` | A service name has one provider. A second definition that declares the same name in `provide` is refused before it runs, the error names both files, and the first keeps the service. | | `no-fallback-when-a-provider-leaves` | A provide into a taken name at run time is refused with `already_provided` and the holder keeps answering; when the holder goes away nothing falls back, and the name has no provider until a plugin provides it again. | | `undeclared-raw-provide-refused` | A declared service is provided only through `ctx:plugin` with a `mare.Service` class, so its contract checks every call; a raw `ctx:provide` under a declared name is refused. | | `host-methods-stay-with-the-host` | A method the host implements in a service contract cannot be implemented or replaced by a plugin. | ## Ownership of registrations | Key | Promise | |---|---| | `ctx-registrations-withdrawn-on-dispose` | Everything registered through a plugin's `ctx` (listeners, services, timers, tasks, tools, commands, key bindings, status segments, effects) is withdrawn when the plugin is disposed. | | `registration-withdrawn-on-caller-unload` | A registration made through another plugin's service belongs to the caller: it is withdrawn when the caller goes away, its release is idempotent, and an explicit release is not released again. | | `release-after-provider-is-gone-does-nothing` | When the provider went away first, the release its former caller still holds does nothing and never calls into the unloaded provider. | | `no-registration-escapes-an-unload` | A registration made from a cleanup while the plugin unloads does not outlive the plugin: it never runs afterwards. | | `shared-cleanup-runs-once-per-registration` | One cleanup function registered by two plugins is two registrations: disposing one plugin runs it once and leaves the other's in place. | ## Cleanup | Key | Promise | |---|---| | `effects-dispose-in-reverse-start-order` | A plugin's cleanups start last-in first-out, each exactly once. Put cleanups whose order matters into one effect. | | `cleanup-error-does-not-stop-the-rest` | A cleanup that raises does not stop the others; its error is reported once. | | `yielding-cleanups-run-concurrently` | Cleanups that yield (wait on a timer, a process, the network) run concurrently: one does not wait for another to finish, and the unload ends when all of them have. | | `turning-a-plugin-off-waits-for-its-cleanup` | Turning a plugin off waits for its cleanup, asynchronous parts included, before the reload reports done. | ## Failures and rollback | Key | Promise | |---|---| | `failed-apply-rolled-back-before-it-is-reported` | When `apply` raises, what it provided and registered is gone and its cleanups have run before the failure is reported. | | `failed-reload-keeps-the-old-definition-serving` | When a reload's new definition fails in `apply`, the previous definition runs again as a fresh instance (its earlier in-memory state is not restored), its dependents are applied again, and the failure is reported. A full `/reload` keeps such a plugin running. | | `broken-definition-reload-changes-nothing` | A reload whose new definition cannot be read or fails validation before `apply` leaves the running instance untouched. | | `dependents-put-back-with-their-provider` | When a provider and its dependents all fail on their new definitions in one reload, each is put back on its previous definition, dependents after their provider. | | `handler-error-reported-and-plugin-keeps-running` | A listener, task or timer that raises is reported every time (`kernel/error`, a notice) and the plugin stays loaded; its latest error stays in the problems until a full `/reload`. | ## Reload | Key | Promise | |---|---| | `config-change-restarts-only-its-plugin` | Changing one plugin's options restarts that plugin only. | | `rejected-config-keeps-the-previous-one` | A plugin config that its schema rejects keeps the previous config running; a corrected edit applies. | | `cancelled-reload-waits-for-disposal` | A reload cancelled while a cleanup is running does not leave a half-disposed plugin: retrying waits for that disposal first. | | `full-reload-keeps-startup-and-session` | A full `/reload` restarts every plugin without replaying startup (no second `app/ready`, no second `session/start`) and keeps the session the user is in. | | `reload-rereads-plugin-modules` | Reloading a plugin drops the modules it `require`d, so edited module files are read again. | ## Shutdown and stuck plugins | Key | Promise | |---|---| | `shutdown-is-bounded-and-names-unfinished-cleanups` | Exit waits for plugin cleanups up to `shutdown_grace_ms`. Past the deadline it stops waiting, and names the plugins still unloading, also those whose unload began before the exit; the other plugins have unloaded. | | `unload-stall-reported-with-effect-labels` | A plugin still unloading after `stall_ms` (default 10 s, 0 turns it off) is reported with the labels (`ctx:effect(fn, label)`) of the effects it held when its dispose began, once per stall, in `/plugins tree`, `mare plugin tree --json`, the log and a `kernel/stalled` notice. The labels are a snapshot taken when the unload starts: they name every cleanup that started, not only the one still running. A restart caused by a config change does not go through dispose, so its report carries no labels. | | `load-stall-reported-without-abort` | A plugin whose `apply` has not returned after `stall_ms` is reported the same way; nothing is aborted or isolated, and the reload that started it keeps waiting. | | `pending-stall-reported-as-waiting` | A plugin left waiting for a service after `stall_ms` is reported with the services it waits for. It stays PENDING: the report adds no problem line and never turns the wait into a failure. | ================================================================================ Title: Services and events Section: Extend URL: https://signalridge.github.io/mare/en/extend/services-and-events/ Markdown: https://signalridge.github.io/mare/raw/en/extend/services-and-events.md Source: docs/en/extend/services-and-events.md ================================================================================ # Services and events How plugins talk to each other: providing and replacing services, the event dispatch styles, policy and rewrite events, built-in services and main events. ## Services ### Use a service Name the services you need in `inject`. They are then available as `ctx.<name>`, or through `ctx:get(name)`. Call methods with a colon. ```lua return { name = "show-model", inject = { "llm", "commands" }, apply = function(ctx) ctx.commands:register("which-model", { description = "Show the current model", run = function() local m = ctx.llm:current() ui.notify(m and m.ref or "no model") end, }) end, } ``` `ctx.llm` reaches the current provider on every read. When that provider is reloaded or replaced, the plugins that inject it restart with it. A service the plugin can run without stays out of `inject`. `ctx:get(name)` returns it, or `nil` while nobody provides it. To register something into it, use `ctx:inject({ name }, fn)`: `fn(ctx)` runs while the service is provided, what it registers through that `ctx` is withdrawn when the service goes away, and `fn` runs again for the next provider. The built-in `profile` plugin adds `/profile` this way. ```lua return { name = "show-model", inject = { "llm" }, apply = function(ctx) -- /which-model exists while the commands service does ctx:inject({ "commands" }, function(sub) sub.commands:register("which-model", { description = "Show the current model", run = function() local m = ctx.llm:current() ui.notify(m and m.ref or "no model") end, }) end) end, } ``` ### Provide a service Declare the name in `provide` and its methods in `contracts`, then provide it in `apply` with a `mare.Service` class: the constructor names the service, each method of the contract is a method of the class, and `ctx:plugin(Class)` provides it. Inside a method, `self.ctx` is the calling plugin's `ctx`, so what a method registers as an effect of `self.ctx` belongs to the caller and is withdrawn when the caller goes away. The built-in `commands` service registers commands this way. ```lua -- ~/.config/mare/plugins/greeter.lua return { name = "greeter", provide = { "greeter" }, contracts = { greeter = { required = { "greet", "remember" } } }, apply = function(ctx) local known = {} local Greeter = require("cordis").class("Greeter", mare.Service) function Greeter:constructor(c) Greeter.super.constructor(self, c, "greeter") end function Greeter:greet(who) return known[who] and ("hello again, " .. who) or ("hello " .. who) end -- remembered until the calling plugin goes away function Greeter:remember(who) return self.ctx:effect(function() known[who] = true return function() known[who] = nil end end) end ctx:plugin(Greeter) end, } ``` ```lua -- ~/.config/mare/plugins/greeter-user.lua return { name = "greeter-user", inject = { "greeter" }, apply = function(ctx) ctx.greeter:remember("world") ui.notify(ctx.greeter:greet("world")) -- hello again, world end, } ``` A service is checked against its contract before it is published. With no contract, or a required method missing, it is refused: the service is not provided, and the reason is recorded as the plugin's problem. A contract for a name the built-ins already define cannot be redeclared. A contract can also describe each method, which publishes it to callers outside Lua. Instead of the `required` list, give `methods`: per method a `doc`, `params` and `result` JSON Schemas, the positional `order`, and `expose = "both"`. The kernel checks arguments and results against the schemas and derives the JSON adapter from the contract, and the method becomes the RPC method `service.method`. ### Replace a built-in service A service has one provider. A second plugin that declares the same name in `provide` is refused before it runs, the error names both files, and the first keeps the service. Nothing falls back: when the provider goes away, the service is gone until a plugin provides it again. To replace a built-in service, turn its plugin off with `mare.plugin("status", { enabled = false })` in `init.lua` (this closes the name for every source, yours included), and provide the service from your own plugin, implementing every required method of its contract. ```lua -- ~/.config/mare/plugins/my-status.lua return { name = "my-status", provide = { "status" }, apply = function(ctx) local Status = require("cordis").class("Status", mare.Service) function Status:constructor(c) Status.super.constructor(self, c, "status") end function Status:get() return { state = "idle", message = "", cwd = mare.cwd, pid = mare.pid, seq = 0, session = {} } end ctx:plugin(Status) end, } ``` Or give your plugin the same name as the built-in plugin and set `override = true`; it then also inherits responsibility for the services of the plugin it replaces. If a replacement of an essential service fails to start, requests are blocked rather than run without it. To change behaviour without replacing a service, prefer an event listener, or change one piece through its own API: `ctx.tools:shadow(name, def)` re-registers a modified copy of a tool, and the UI components can be wrapped (see [Appearance](https://signalridge.github.io/mare/en/configure/ui/)). ### Built-in services | Service | Provided by | What it does | |---|---|---| | `agent` | `agent` | Runs the agent loop: `prompt` (with `follow_up` delivery), `steer`, `cancel`, `activity` (`agent:activity().busy`), `messages`. | | `llm` | `llm` | Provider registry, model catalog, login, and parameters: `current`, `set_model`, `resolve`, `recent`, `cycle_param`, `login`, `logout`, `auth_keys`. | | `session` | `session` | The session tree on disk: `info`, `create`, `load`, `fork`, `close`, `list`, `entries`, `record`, `records`. | | `context` | `context` | System prompt assembly: `section`, `suppress`, `variable`, `system_prompt`, `skills`, `templates`. | | `compact` | `compact` | Staged context compaction: `run`, `register_stage`, `measure`, `threshold`. | | `tools` | `tools` | The tool registry and the one guarded execution path: `register`, `shadow`, `command`, `get`, `list`, `execute`, `disable`, `enable`. | | `permissions` | `permissions` | Sandbox and approval presets: `preset`, `request`, `grants`. | | `approvals` | `approvals` | Independent approval policy and reviewers: `policy`, `set`, `request`, `register_reviewer`. | | `commands` | `commands` | Slash commands: `register` (with `alias_of`), `run`, `list`, `get`. | | `ui` | `ui` | Plugin-scoped interface pieces: `widget`, `status`, `invalidate`, `key`, `action`, `renderer`, `style`. | | `theme` | `theme-default` | Themes: `list`, `get`, `register`, `select`, `preview`, `cancel_preview`, `register_override`. | | `jobs` | `jobs` | Background processes: `start`, `track`, `get`, `list`, `background`, `cancel` (exposed to models as the `job_kill` tool), `read`. | | `usage` | `usage` | Token and cost totals: `totals`, `context_tokens`, `cost_text`, `rate_limits`. | | `status` | `status` | The unified agent state: `get`. | | `mcp` | `mcp` | MCP servers: `status`. | | `changes` | `changes` | Per-turn file changes and rewind: `turns`, `diffs`, `rewind`. | | `review` | `review` | Code review: `run`, `viewer`. | | `images`, `copy`, `plugins`, `update-check`, `spill` | the plugin of the same name | Image display, clipboard copy, package catalog UI, update check, result storage. | The Lua type files in the runtime directory (`mare runtime`) give the full signatures; the [Lua API](https://signalridge.github.io/mare/en/extend/lua-api/) page is generated from them. ### Session provider contract The `session` service splits lifecycle orchestration from session storage so custom `session` providers work identically across TUI, CLI, and multi-session RPC/web/ACP hosts: - **Host-provided lifecycle methods**: `session.create`, `session.load`, `session.fork`, and `session.close` are provided by the host orchestrator (`provider = "host"` in the `session` contract). The orchestrator owns project confinement, `request_id` idempotency receipts, `expected_epoch` checks, and runtime lifecycle for Lua, slash-command, and RPC callers alike. A custom `session` provider must not implement these four methods. - **Startup arguments (`mare.args`) in multi-runtime hosts**: When a multi-runtime host (`mare --rpc`, web, ACP) creates, loads, or forks a session, the orchestrator spawns a dedicated runtime and populates `mare.args` before `app/ready`: - `session_id`: pre-assigned session ID to adopt when starting a new or forked session. - `resume`: path or selector of an existing session to load on startup. - `fork_session` (boolean, with optional `fork_before_entry`): fork from the resumed source instead of opening it in place. - `name`: initial session name. - `fork_images` (optional map, when `prepare_fork` returns in-memory images): pre-verified image payloads for a fork; the provider reads and clears `mare.args.fork_images` during startup. - If startup loading or forking fails, record the error in `session:info().resume_error` so the orchestrator can close and roll back the runtime cleanly. - **Lua-only provider hooks (`expose = "lua"`)**: - `session.switch(opts)`: called by the orchestrator on **single-runtime** hosts to switch the active session in place (`opts.kind = "new" | "load" | "fork"`, with optional `cwd`, `name`, `session_id`, `path`, `before_item_id`, `id`) and return the new live session snapshot. Providers coordinate host identity, session-only trust revocation, and bound-call guards via `ctx.kernel:begin_session_switch` / `commit` (`handle:commit(session_id)` automatically marks an active session export call as committed). If a custom provider omits `switch`, single-runtime lifecycle calls fail with `unavailable`. - `session.prepare_fork()`: called by the orchestrator on a live source runtime before a multi-runtime fork to drain side requests, flush the journal, and return `{ path, images? }` (or `nil` if nothing is persisted). Omitting `prepare_fork` causes live multi-runtime forks to fail with `unavailable`. - **`session.close` under single- vs multi-runtime capacity**: - **Multi-runtime hosts**: shuts down and unloads the target session's runtime, releases its lock, and returns `{}`. - **Single-runtime hosts**: closing the bound session (by exact ID, path, or unique prefix of at least 4 characters) switches the VM in place to a fresh empty session via `session.switch({ kind = "new" })` and releases the prior session's lock, returning `{}` without exiting the host or restarting plugins/MCP servers. Closing an already-unloaded session returns `{}`; ambiguous prefixes fail with `invalid_arguments`, unknown IDs with `unknown_session`, stale `expected_epoch` with `stale_session`, and active turns with `busy`. ## Events ### Listening `ctx:on(event, fn, opts)` subscribes for the plugin's lifetime. Listeners run in registration order; `opts.prepend = true` puts one first. It returns a function that unsubscribes. `ctx:once(event, fn)` is removed after its first call. In `init.lua` use `mare.on(event, fn)`, the same kind of listener; to vote on a decision point such as `tool/before`, use `mare.policy.voter(point, fn, opts)`. ```lua ctx:on("model/changed", function(ev) ui.notify("model is now " .. ev.ref) end) ``` A waterfall listener receives `(payload, ev)`. Calling `ev.next(payload)` (or `ev(payload)`) invokes the rest of the chain with that value (`ev.next()` forwards the current value) and returns their result; whatever the listener returns becomes the result. A listener that omits `ev.next` ends the chain there. ```lua ctx:on("context/system", function(payload, ev) payload.text = payload.text .. "\nAnswer in English." return ev.next(payload) end) ``` ### How an event is dispatched The producer chooses the dispatch style. It decides what your return value means. | Style | Producer calls | Listeners | Your return value | |---|---|---|---| | Notify | `ctx.bus:emit` | All, in order. | Ignored. An error is reported and the rest still run. | | Checked notify | `ctx.bus:emit_checked` | All, in order. | An error stops the dispatch and reaches the producer. | | Bail | `ctx.bus:bail` | In order, until one returns non-`nil`. | The first non-`nil` value is the result. | | Waterfall | `ctx.bus:waterfall`, `ctx.bus:waterfall_checked` | The first registered is outermost; each calls `next` for the rest. | The value passed to `next` goes on; the outermost listener's return value is the result. `waterfall_checked` gives the producer the error of a listener that raised. | | Policy | `ctx.policy:decide(point, args, opts)` | Voters, in order. | A vote. See below. With `opts.require_explicit_approval`, no voters or only `nil` votes give an `unavailable` deny. | | Rewrite | `ctx.policy:rewrite(point, call)` | Rewriters, in order. | `nil` to keep the arguments, or a new arguments table. Returns the rewritten arguments directly, or raises `policy.rewrite_refused`. | Plugins emit their own events with the same calls (`inject = { "bus" }`). Every emitted event must be declared in a contract (`contracts.<root>.events`); use `name/verb` names and keep them unique to your plugin. Each declared event carries an `expose` reach with three levels: - `expose = "process"`: strictly in-process. Never enters the external event log and cannot be observed or hooked over RPC, regardless of `include`. - `expose = "lua"` (default): visible to in-process Lua plugins, not emitted on the default public RPC/JSON stream. A primary RPC connection's `include` / hook subscription can opt in, so `"lua"` is not a confidentiality boundary. - `expose = "both"`: emitted on both in-process Lua and the default public RPC/JSON event streams. There is no separate local channel. ### Policy events A decision point asks plugins to allow or refuse something. It fails closed. - A voter returns `nil` (no objection), `"allow"`, `"deny"`, `"ask"`, or a table `{ decision = "deny", reason = "..." }`. Unknown fields or decisions make the vote invalid, and an invalid vote is a deny. - The first `deny` ends the dispatch and is final. Otherwise `ask` beats `allow`. - A voter that raises an error, or does not answer within its timeout, counts as a `deny`. The default timeout is 30 seconds. Set `timeout_ms` in the voter's options to change it; `0` removes the limit, which a voter that waits for a person needs. - `slot = "name"` gives a stateful check one decision slot. Only the first registered voter of that slot runs. - Votes never rewrite anything. Arguments are frozen before voting. ```lua ctx.policy:voter("tool/before", function(call, info) local command = call.name == "bash" and call.arguments.command or "" if command:find("rm%s+%-rf%s+/%s*$") then return { decision = "deny", reason = "refusing rm -rf /" } end end) ``` A plugin votes with the policy service's `voter`, as above (`inject = { "policy" }`); a listener of a decision point (`ctx:on`) is not a voter. In `init.lua` the same is `mare.policy.voter(point, fn, opts)`. Rewriting happens earlier, in the `tool/rewrite` chain. Each rewriter gets a copy of the call with the arguments so far and returns `nil` or a new arguments table. An error, a timeout or a non-table result fails the rewrite, and the call is refused. ```lua ctx.policy:rewriter("tool/rewrite", function(call) if call.name == "bash" then local args = {} for k, v in pairs(call.arguments) do args[k] = v end args.command = (args.command or ""):gsub("^%s+", "") return args end end) ``` The decision points are `tool/before`, `tool/approval`, `net/approval`, `request/ready` and `permission/verdict`, plus `fs/edit-intent` and `fs/write-intent` before edit tools write. ### Main events ![mare single turn data flow](https://signalridge.github.io/mare/assets/diagrams/turn-dataflow.svg) Public stream and protocol events are generated from the registry in [Event reference](https://signalridge.github.io/mare/en/reference/events/). Below are representative in-process lifecycle and hook events; payloads are Lua tables, and the comments in the runtime directory's `types/mare/events.lua` document the rest. | Event | Style | Payload and meaning | |---|---|---| | `app/ready` | notify | The UI is ready. | | `app/shutdown` | notify | Clean exit; listeners are awaited. | | `session/started` | notify | `{ session_id, path, resumed }` | | `session/closed` | notify | `{ session_id, cwd, reason, path? }` (`session_id`, `cwd`, and `reason` are required; `path` is optional), emitted only when a root host session retires (child hosts do not emit it), before dependent observers tear down. | | `agent/step-ready` | policy | `{ id, step, cancel, turn_id }` before each model request; a deny stops the run. | | `agent/step-committed` | notify | `{ step_id, step, turn_id }` after a step's participant state was committed. | | `turn/completed` | notify | `{ turn_id, status, termination_reason, cancellation_cause?, text, structured, usage, error, ... }` when a turn finishes (`cancellation_cause` is `"user"`, `"parent"`, `"hook"`, or `"disposed"` when `termination_reason` is `"interrupted"`). | | `agent/settled` | notify | `{ turn_id, busy }`, after every `turn/completed` listener of that run returned; `busy` is true while another run or an outer `turn/completed` dispatch is still in progress. | | `agent/turn-stopping` | bail | Return a string or `{ message, source? }` to keep the loop going (`source` marks the continuation with `source` and `notification = true`). | | `request/prepare` | checked notify | `{ model, cancel }`, before the first request of a prompt. An error stops the request. | | `request/ready` | policy | A deny stops the request: shown as `not sent: <reason>`. | | `input/submit` | notify | The user submitted input. | | `input/transform` | waterfall | Change the input before it is sent. | | `context/transform` | waterfall | Change the messages before the request. | | `request/build` | waterfall checked | Change the outbound request; an error aborts the request before provider I/O. | | `context/system` | waterfall | `{ text, model }`; mutate `payload.text` and return `ev.next(payload)`. | | `tool/rewrite` | rewrite | Change a call's arguments before voting. | | `tool/before` | policy | `(call, { side_effect, idempotent, unconfined })` | | `tool/approval` | policy | Answers an `ask` with `{ decision = "allow" }`, `{ decision = "allow", grant = "allow_session" }` (or `"allow_amend"` with `amendment`), `{ decision = "deny" }` or `{ decision = "deny", abort = true }`. | | `tool/after` | waterfall | Runs after the tool executes (`result.sandbox_denials` lists refusals), before `tool/result`. | | `tool/result` | waterfall checked | Runs after `tool/after` and before default truncation; an error in a listener produces an error tool result. | | `provider/request` | waterfall | `{ provider, url, headers, body, model }` before it is sent. | | `llm/usage` | notify | Usage after every provider request (`usage.cache_write_1h?` subset of `cache_write`, `usage.cost?`). | | `compact/before` | bail | `false` cancels a compaction. | | `option/changed` | notify | `{ name, value }` after `mare.o.<name> = value` or a reload. | | `option/apply` | checked | `{ name = "plugins.<p>.<path>", value }` for a runtime plugin option write, before it is announced: the owner applies it, and an error fails the write and puts everything back. | | `theme/changed` | notify | A theme snapshot. | | `theme/palette` | waterfall | Adjust a flavor's palette before styles are built. | | `ui/caps` | waterfall | Add or override terminal capabilities. | | `ui/commit-before` | waterfall | `{ lines }` about to enter the scrollback. | | `plugins/completed` | notify | `{ action, name?, status }` after a package operation. | | `reload/completed` | notify | `{ added, removed, replaced, reloaded, notices }` after `/reload`. | | `kernel/reloaded` | notify | Plugins were reloaded. | | `kernel/error` | notify | `{ message, plugin, event, what, error }`: a listener, task, timer or dispose hook failed. | External programs can subscribe to events over RPC; see [RPC](https://signalridge.github.io/mare/en/integrate/rpc/). Declare contract events with `expose = "both"` to publish your own events to the public stream. ================================================================================ Title: Writing a plugin Section: Extend URL: https://signalridge.github.io/mare/en/extend/writing-a-plugin/ Markdown: https://signalridge.github.io/mare/raw/en/extend/writing-a-plugin.md Source: docs/en/extend/writing-a-plugin.md ================================================================================ # Writing a plugin Build a small mare plugin step by step: a tool, a slash command, an event listener, a config option and a status-line segment, then test and publish it. Read [Plugins](https://signalridge.github.io/mare/en/extend/plugins/) first for the definition fields. ## Do you need a plugin? A tool that runs a command does not need one. Declare it in `init.lua`: ```lua mare.tool.command { name = "grep", description = "Search file contents with ripgrep.", command = { "rg", "--line-number", "--no-heading", "--regexp={pattern}", "--", "{path}" }, params = { pattern = { type = "string", required = true }, path = { type = "string", default = "." }, }, readonly = true, } ``` Each `{name}` in `command` is filled from the model's arguments. Without `readonly = true`, mare treats the command as having side effects. Use a plugin when you need Lua logic, events, commands or interface pieces. ## Step 1: the skeleton Create `~/.config/mare/plugins/tally.lua`: ```lua return { name = "tally", inject = { "tools", "commands", "ui" }, apply = function(ctx, cfg) ctx.commands:register("tally", { description = "Show how many tool calls the current turn has made", run = function() ui.notify("tally is loaded") end, }) end, } ``` Start mare, or run `/reload` in a running session, then type `/tally`. A notice appears. `/plugins` lists `tally` with the origin `user`. `inject` names the services the plugin uses. Each one is then a field of `ctx`: `ctx.commands`, `ctx.tools`, `ctx.ui`. `ui` without `ctx.` is the global namespace for building nodes and notices. ## Step 2: a tool Register a tool with `ctx.tools:register(name, def)`. This one counts lines, words and characters in text the model passes in. ```lua ctx.tools:register("text_stats", { snippet = "Count lines and words in a piece of text", description = "Count the lines, words and characters of the given text.", parameters = { type = "object", properties = { text = { type = "string", description = "The text to measure" } }, required = { "text" }, }, side_effect = "read", summary = function(args) return ("TextStats(%d chars)"):format(#(args.text or "")) end, execute = function(args) local text = args.text or "" local _, lines = text:gsub("\n", "\n") local words = 0 for _ in text:gmatch("%S+") do words = words + 1 end return { content = ("lines: %d\nwords: %d\nchars: %d"):format(lines + 1, words, #text) } end, }) ``` The tool goes through the same pipeline as the built-in ones: `tool/rewrite`, the argument check, the `tool/before` vote, approval, then `execute`. When the plugin is disposed the tool is withdrawn. Fields of a tool definition: | Field | Meaning | |---|---| | `description`, `parameters` | What the model sees. `parameters` is a JSON Schema object. Either may be a function of `(model, mode)`. | | `execute(args, tctx)` | Runs the call. May yield. Returns a result table or a string. | | `snippet`, `guidelines` | One line, and extra rules, for the system prompt. | | `summary(args)` | The header shown in the transcript, such as `Read(src/main.rs)`. | | `render(args, result, expanded)` | A custom node for the result. | | `readonly` | No side effects. Consecutive read-only calls run in parallel. | | `side_effect` | `"read"`, `"write"` (local files only) or `"external"`. Defaults to `"read"` when `readonly`, else `"external"`. | | `idempotent` | Safe to run twice. A non-idempotent call that crashed mid-way resumes as outcome unknown, never replayed. | | `unconfined` | Runs outside this process, so the local sandbox cannot confine it. | | `enabled(model, edit_mode)` | Return `false` to hide the tool for a model. | | `timeout_ms` | Time limit for the call. | `tctx` carries `cancel` (a token to pass to blocking calls), `update(partial)` for progress, `cwd` and `tool_call_id`. A result table has `content` (a string, or a list of content blocks), and optionally `is_error`, `details`, `display` (a node), `no_truncate` and `max_line_chars`. ## Step 3: an event listener Count finished tool calls on `item/completed`, and reset at the start of each turn: ```lua local calls = 0 ctx:on("turn/started", function() calls = 0 end) ctx:on("item/completed", function(data) if data.item and data.item.type == "tool_call" then calls = calls + 1 end end) ``` Listeners are removed when the plugin is disposed. Change the `/tally` command to report the number: ```lua run = function() ui.notify(("%d tool call(s) in this turn"):format(calls)) end, ``` See [Services and events](https://signalridge.github.io/mare/en/extend/services-and-events/) for the event names and what a return value does. ## Step 4: a configuration option Declare each option in `config_schema`. Its defaults, with what the user set, arrive as `cfg`; a value of the wrong type or out of range is reported and keeps the default. ```lua config_schema = { warn_after = { type = "integer", default = 25, min = 1, desc = "notify when one turn makes more tool calls than this" }, show_in_status = { type = "boolean", default = true, desc = "show the count in the status line" }, }, ``` Use it in the listener: ```lua ctx:on("item/completed", function(data) if data.item and data.item.type == "tool_call" then calls = calls + 1 if calls == cfg.warn_after + 1 then ui.notify(("tally: more than %d tool calls in this turn"):format(cfg.warn_after), "warning") end end end) ``` Users change it in `init.lua`. A key you did not declare produces a warning with a suggestion. ```lua mare.plugin("tally", { warn_after = 10 }) ``` `/reload config` reloads the plugin when its options change. ## Step 5: a status-line segment `ctx.ui:status(id, def)` adds a segment. `render` returns a node, or `nil` to hide it. Call `ctx.ui:invalidate(id)` when the content changes. mare draws only when asked. ```lua if cfg.show_in_status then ctx.ui:status("tally", { align = "right", order = 20, render = function() if calls == 0 then return nil end return ui.Line({ ui.Span(("calls: %d"):format(calls)):hl("MareDim") }) end, }) end ``` Add `ctx.ui:invalidate("tally")` after each change to `calls`. `ctx.ui:widget(id, { slot = "above-editor", render = function(width, max_height) ... end })` draws a block above or below the input instead. The snippets above all go inside `apply`, in order, with `local calls = 0` at the top. Keep `inject` and `config_schema` beside `apply` in the returned table. The result is one file of about 55 lines. ## Test it - **Reload.** Edit the file, then run `/reload tally` for this plugin or `/reload` for everything. A plugin that fails to load keeps its previous version running. - **Check the state.** `/plugins` shows whether it is active and prints the error with a traceback if it failed. Failures also appear in the status line as `plugin tally failed · /reload`. - **Lua console.** `/lua` runs Lua in the running session, for example `/lua mare.plugins.status("tally")` or `/lua mare.o.border`. Without code it opens a prompt that accepts several lines. It exists in the TUI only and cannot be reached over RPC. - **Log.** `ctx.logger:warn("...")` writes to the log under `~/.local/state/mare/log/`. `/debug` shows recent lines. - **Without the TUI.** Load the plugin in a headless session and read stderr. A definition that does not load is reported as `mare: warning: plugin ...`: ```sh printf '%s\n' \ '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocol_version":"3.0","client":{"name":"t"},"capabilities":{}}}' \ '{"jsonrpc":"2.0","id":2,"method":"shutdown","params":{}}' | mare --rpc >/dev/null ``` Use `MARE_HOME=$(mktemp -d)` in front to test against an empty configuration. ### Automated tests with `mare test` `mare test` discovers every `*_spec.lua` file under the given paths (or the current directory, skipping `.git`, `target`, `node_modules`, and `snapshots`) and runs them in mare's built-in `mare.test` harness (`require("mare.test")`). Use `t.host()` to spin up an isolated real plugin host (the same Cordis lifecycle tree, loader, event bus, and contract admission as production mare — with optional `builtins` or contract-checked fake services via `host:provide(name, impl, opts?)`). Save `tests/tally_spec.lua` alongside `plugins/tally.lua`: ```lua local t = require("mare.test") t.describe("tally", function() t.it("counts lines, words, and chars via text_stats", function() local host = t.host({ builtins = { "tools", "commands", "ui" } }) local plugin = dofile("plugins/tally.lua") host:load(plugin, { warn_after = 25, show_in_status = false }) t.expect.settled(host) t.expect.eq(host:state("tally"), "ACTIVE") local tool = assert(host:get("tools"):get("text_stats")) local res = tool.execute({ text = "alpha beta\ngamma" }) t.expect.eq(res.content, "lines: 2\nwords: 3\nchars: 16") t.expect.snapshot(res.content, "text_stats_sample") host:dispose() t.expect.eq(host:get("tools"), nil) end) end) ``` Because `host` runs the real plugin lifecycle, the same fixture can test missing dependencies (`host:state(name) == "PENDING"` until `host:provide(...)` satisfies them), contract guards on fake services, cleanup on `host:dispose()`, and failed-reload rollback via `host:reload(name, def, cfg)`. Any test host not disposed explicitly is disposed automatically when its `t.it` case ends. Because `tests/tally_spec.lua` includes a snapshot assertion, generate and review the baseline snapshot once with `-u`, then run ordinary checks from the plugin repository root: ```sh mare test -u tests/tally_spec.lua # create or update snapshots/*.snap on the first run (inspect the file before committing) mare test # discover and run all *_spec.lua files against saved snapshots mare test tests/tally_spec.lua # run a single spec file mare test -f "text_stats" # filter cases by substring ``` `expect.snapshot(value, name?)` writes `<spec_dir>/snapshots/<spec_stem>__<name>.snap`. Without `-u` (`--update-snapshots`), a mismatch fails the case and writes a `.snap.new` file for inspection. Exit codes are `0` (all passed), `1` (test failures), and `2` (usage, discovery, or syntax/load errors). If you work on a built-in plugin in a checkout of the mare repository, `just run` starts a debug build that reads `crates/mare-plugin/preset/plugins/*.lua` from disk on every start. Edit the file and `/reload`; nothing is recompiled. ## Publish it as a package A package is a git repository. Put the plugin in `plugins/`: ``` mare-tally/ plugins/tally.lua mare-plugin.toml # optional ``` ```toml # mare-plugin.toml name = "mare-tally" description = "Count tool calls per turn" version = "0.1.0" requires = ">=0.1" # a mare older than this will not load the package ``` Push it and tag a release with a semver tag: ```sh git tag v0.1.0 && git push --tags ``` Anyone installs it by declaring it in `init.lua` and running `mare plugin sync`. The options go under the plugin name: ```lua mare.plugins.add { { "you/mare-tally", opts = { tally = { warn_after = 10 } } }, } ``` A repository can hold several plugins, and a user can load some of them with `only = { "tally" }`. A package may also ship `skills/`, `prompts/`, `themes/` and `types/` (Lua type definitions). See [Packages](https://signalridge.github.io/mare/en/configure/packages/). ================================================================================ Title: ACP server Section: Integrate URL: https://signalridge.github.io/mare/en/integrate/acp/ Markdown: https://signalridge.github.io/mare/raw/en/integrate/acp.md Source: docs/en/integrate/acp.md ================================================================================ # ACP server `mare acp` runs mare as an Agent Client Protocol server over stdio, so an editor that speaks ACP can start it and chat with it in a panel. This page shows how to register mare, what the server implements, and where it stops short of the full protocol. ## Register mare in an editor An ACP client starts the agent as a subprocess and talks JSON-RPC over its stdin and stdout. Every client needs the same two things, a command and its arguments: ```json { "command": "mare", "args": ["acp"] } ``` Where that block goes depends on the editor. Look for its setting for custom or external ACP agents and enter `mare` as the command and `acp` as the argument. Make sure `mare` is on the `PATH` the editor sees; if it is not, give the full path. `mare acp` waits for protocol messages on stdin and prints nothing until it gets one. `mare acp --help` lists its options. ## Options `mare acp` accepts a subset of the startup options. Add them to `args`: | Option | Effect | |---|---| | `-m`, `--model <MODEL>` | Model, for example `openai/gpt-6.1-terra`. | | `--agent <NAME>` | Use a registered agent type for the initial session. | | `-e`, `--effort <EFFORT>` | Reasoning effort. | | `--tools <TOOLS>` | Enable only these tools (comma separated). | | `--exclude-tools <TOOLS>` | Exclude these tools (repeatable or comma separated; supports `*`). | | `--append-system-prompt <TEXT>` | Append text to the system prompt. | | `--name <NAME>` | Name the session. | | `--set <KEY=VALUE>` | Override a config value, such as `--set plugins.permissions.preset=read-only`. | | `--strict-config` | Refuse to start when configuration warnings occur. | | `--trust`, `--no-trust` | Override saved project trust for this run (saves nothing). | | `--approve-mcps` | Approve project and `$MARE_MCP_CONFIG` MCP servers without prompting. | | `--clean` | No user or project config, no user plugins, no packages. | | `--startuptime <FILE>` | Write startup timing data to a file. | | `-C`, `--cwd <CWD>` | Default working directory. | For example, a read-only server pinned to one model: ```json { "command": "mare", "args": ["acp", "--model", "openai/gpt-6.1-terra", "--set", "plugins.permissions.preset=read-only"] } ``` The session flags (`-c`, `-r`, `--no-session`) and `--permission` are not options of `mare acp`. Use `--set plugins.permissions.preset=...` instead; the values are `read-only`, `auto` and `full-access` (see [Permissions](https://signalridge.github.io/mare/en/use/permissions/)). ## What is implemented The server implements these messages: | Message | Kind | Behavior | |---|---|---| | `initialize` | request | Returns the lower of the client's requested protocol version and the server's `ProtocolVersion::LATEST`; advertises HTTP MCP, image and embedded-context prompts, `loadSession`, and session list, resume and close. | | `authenticate` | request | The server does not require authentication and returns an empty success response. | | `session/new` | request | Starts a new mare session in the `cwd` the client sends and returns its id. | | `session/load` | request | Reopens a saved, inactive session in its original `cwd` and replays its history via `session/update` before responding. For compacted sessions, only the compacted context is replayed. | | `session/resume` | request | Reopens a saved, inactive session in its original `cwd`. | | `session/list` | request | Lists saved, inactive sessions, optionally filtered by `cwd`. | | `session/close` | request | Closes an active session. | | `session/set_config_option` | request | Changes a session's model or reasoning effort. | | `session/prompt` | request | Runs one turn and returns the stop reason when it ends. | | `session/cancel` | notification | Aborts the running turn of that session. | | `session/request_permission` | server request | Asks the client to approve a tool or network operation. Options are `allow-once`, `reject-once`, and `allow-always` when offered. | Each `session/new` creates a separate mare host for the given `cwd`, so several sessions in different folders can run side by side. Project trust is decided per session workspace: ACP honors explicit `--trust` and `--no-trust` flags first, then falls back to the saved decision in `trust.json` or `MARE_TRUST_DEFAULT` (see [Permissions](https://signalridge.github.io/mare/en/use/permissions/)). ACP never prompts interactively for project trust. Until a folder is trusted, its project plugins, skills and prompts do not load. Record a decision once with `mare trust` in that folder, or pass `--trust` / `--no-trust` explicitly. The `mcpServers` supplied with `session/new`, `session/load`, or `session/resume` are accepted for HTTP(S) and stdio transports; stdio commands must be absolute paths. SSE transport is not supported. See [MCP](https://signalridge.github.io/mare/en/use/mcp/) for mare's own MCP configuration. ### Prompts Prompts accept text blocks, embedded text resources, resource links and images in their original order. Resource links are represented as text, and adjacent text is joined with a blank line. Audio and embedded binary resources are refused. Image blocks are refused with an invalid-params error when the session's current model does not declare image input. `initialize` advertises image support for the connection because the model is selected per session and can change; image support is checked for each prompt containing images, since mare cannot decide this flag from a model at initialization before a session host exists. A turn ends with one of these stop reasons: | Stop reason | When | |---|---| | `end_turn` | The turn finished. | | `cancelled` | `session/cancel` aborted it. | | `max_tokens` | The last assistant message stopped because of length. | | `max_turn_requests` | The turn reached `agent.max_turns`. | | `refusal` | The provider refused or filtered the response. | A provider error or persistence failure is returned as a JSON-RPC internal error, never as a successful `end_turn`. An unknown session id returns JSON-RPC error `-32002` (Resource not found). ### Streaming updates While a turn runs, mare sends `session/update` notifications: | ACP update | From | |---|---| | `agent_message_chunk` | Assistant text deltas. | | `agent_thought_chunk` | Reasoning deltas. | | `tool_call` | A tool call starting. `status` is `in_progress`, `title` is the tool name plus its `path` or `command` argument, `rawInput` is the arguments. | | `tool_call_update` | A tool call finishing. `status` is `completed` or `failed`, and the content is the tool's text output. | | `usage_update` | Emitted when `usage/changed` reports `last_context` and a positive `context_window`, carrying `used` and `size`. | The `kind` of a tool call is derived from kernel tool metadata (`execute` when `command_tool` is set, `read` / `edit` from `side_effect`, and `other` otherwise or when metadata is unavailable during history replay). ## Limitations - **No session modes.** The server does not advertise ACP session modes and does not implement `session/set_mode`. - **Additional directories on `session/new` only.** `session/new` accepts `additionalDirectories` (existing physical directories outside `cwd`, revalidated on resume); a nonempty `additionalDirectories` is refused on `session/load` and `session/resume`. - **No audio prompts.** Audio blocks and embedded binary resources are refused. - **No client file or terminal methods.** mare reads and writes files and runs commands itself. It does not call the editor's `fs/*` or `terminal/*` methods. - **No authentication required.** `initialize` returns no auth methods, and `authenticate` returns an empty success response. For programmatic control with approvals, host tools and the full session API, use the [RPC](https://signalridge.github.io/mare/en/integrate/rpc/) interface. ================================================================================ Title: JSON event stream Section: Integrate URL: https://signalridge.github.io/mare/en/integrate/json-stream/ Markdown: https://signalridge.github.io/mare/raw/en/integrate/json-stream.md Source: docs/en/integrate/json-stream.md ================================================================================ # JSON event stream `mare --json` runs one prompt headless and writes one JSON record per line to stdout. The stream starts with a `session` record, carries the public agent events as the run proceeds, and ends with a `settled` record that holds the final text and the exit code. This page is the contract a script can rely on. ## Run it ```sh mare --json "Run the tests and fix any failures" ``` `--json` is shorthand for `--mode json`. The prompt is an argument, or stdin when you pass `-` or no argument and stdin is a pipe. Every record is a single line `{"type": ..., "data": ...}`. Only records go to stdout. Warnings and denied approvals go to stderr. This is what a run that never starts looks like. A bad argument still ends with a `settled` record, so a reader always gets an outcome: ```json {"type":"session","data":{"protocol_version":"3.0","cwd":"/work/app"}} {"type":"turn.failed","data":{"error":{"code":"invalid_arguments","message":"unexpected argument '--bogus' found"}}} {"type":"settled","data":{"text":"","error":{"code":"invalid_arguments","message":"unexpected argument '--bogus' found"},"exit_code":2,"reason":"usage"}} ``` ## Records Each line has two keys: | Key | Meaning | |---|---| | `type` | `session`, an event name, `lagged`, `dropped`, `turn.failed` or `settled`. | | `data` | The record payload, always an object. | Readers should ignore keys they do not know. New fields are added without notice and do not change the meaning of existing ones. ### `session` Always the first line. | Field | Meaning | |---|---| | `protocol_version` | The protocol version, `major.minor`. | | `session_id` | Session id. With `--no-session` it is a temporary id that cannot be resumed. | | `path` | Session file. Absent with `--no-session`. | | `cwd` | Working directory of the run. | | `model` | Model reference, when known. | | `ephemeral` | `true` with `--no-session`: no session transcript is saved, the run cannot be resumed, and there is no crash recovery. Other writes (runtime files, snapshots, tool output) can still happen. | Use `session_id` to continue the conversation later with `mare -p --resume <session_id> "..."` (see [Sessions](https://signalridge.github.io/mare/en/use/sessions/)). ### Event records Between `session` and `settled`, `type` is the name of a public agent event and `data` is its payload. Event names have the form `area/name`; the full generated list of built-in public events (with delivery class, ignorability, payload fields, and examples) is in the [Event reference](https://signalridge.github.io/mare/en/reference/events/). Internal plugin events never appear. To publish custom plugin events on the public stream, declare them in a service contract with `expose = "both"`. Over RPC, the primary connection can also opt into additional JSON kernel events with `events.subscribe { session_id: "...", include: [...] }` (or `{ scope: "all", include: [...] }`). Built-in events are checked against their schemas before delivery. Payloads must be plain JSON. A plugin event that uses a reserved name (`session`, `turn.failed`, `settled`, `lagged`, `dropped`) fails the run with a stream error. Print the payload schemas with `mare rpc schema`; the stream's own records are under its `headless` key. When a tool call finishes, `item/completed` carries an item with `item.type == "tool_call"`, `tool_call_id`, `name`, `message`, `result_status` (`"success"`, `"error"`, `"denied"`, `"cancelled"` or `"persist_failed"`), and `execution_status`. Those statuses do not say whether side effects happened. ### Item level and deltas By default the stream omits `ignorable` delta and advisory events (such as `item/delta`, which fires per chunk of text, reasoning, or tool output) and delivers lifecycle boundaries and completed items (`turn/*`, `step/*`, `item/started`, `item/completed`). Add `--stream-deltas` to include ignorable events such as `item/delta`: ```sh mare --json --stream-deltas "Explain src/main.rs" | jq -r 'select(.type=="item/delta" and .data.kind=="text") | .data.delta' ``` ### `lagged` and `dropped` `{"type":"lagged","data":{"from_seq":A,"to_seq":B}}` reports a contiguous sequence range skipped because the reader was slower than mare, and `{"type":"dropped","data":{"count":N}}` counts unretained `lossy` or refused events omitted under pressure. Events with `delivery = "required"` (`turn/*`, `step/*`, `item/started`, `item/delta`, `item/completed`, `subagent/*`) wait for room instead of being dropped silently. ### `turn.failed` When the run ends with an error, `{"type":"turn.failed","data":{"error":{"code":"...","message":"..."}}}` (with optional `data`) is written just before `settled`. ### `settled` Always the last line. Nothing follows it. | Field | Meaning | |---|---| | `text` | The final assistant text. | | `usage` | Token counts, plus `cost` when the usage plugin reported one. | | `error` | Structured error object `{code, message, data?}`, when the run failed. | | `exit_code` | The process exit code. | | `reason` | Why the run ended. | `reason` and `exit_code` pair up like this (see [Exit codes](https://signalridge.github.io/mare/en/reference/exit-codes/)): | `reason` | `exit_code` | Meaning | |---|---|---| | `completed` | 0 | The turn finished. | | `error` | 1 | A provider, tool or runtime error, or the process got SIGTERM or SIGHUP. | | `usage` | 2 | Bad arguments or configuration; the run never started. | | `approval_unavailable` | 3 | An approval was answered with "deny and stop" (`abort`) and the turn was stopped. An approval nobody could answer is only denied and the run can still complete with `0`. | | `max_turns` | 4 | `--max-turns` was reached. | | `timeout` | 4 | `--timeout` was reached. | | `save_failed` | 5 | Session persistence failed; unsaved records were quarantined under `<state>/quarantine/`. | | `interrupted` | 130 | SIGINT. | ## Guarantees - The first record is `session` and the last is `settled`, except when stdout closes or output stops being delivered (below). - Records are written by one writer, in order, and each one is flushed before the next is admitted. - Event order is the order the agent produced them. `lagged` markers keep their place in the sequence. - `settled.exit_code` equals the process exit code. - If the reader goes away (`mare --json ... | head`), mare stops the turn instead of spending tokens for nobody, and exits with 141. - `--timeout` covers output delivery as well as agent work. If a reader blocks forever, the stream can end without a `settled` record, with a message on stderr and a non-zero exit code. Treat a missing `settled` as a failed run. - The first SIGINT cancels the turn and still writes `settled` with `interrupted`. A second one exits at once with code 130 and no `settled`. ## jq Print the final text, then exit with mare's code (Bash): ```sh mare --json "List the TODOs in src/" \ | tee run.jsonl \ | jq -r 'select(.type == "settled") | .data.text' code=${PIPESTATUS[0]} exit "$code" ``` Follow tool calls as they finish: ```sh mare --json "Update the changelog" \ | jq -r 'select(.type == "item/completed" and .data.item.type == "tool_call") | "tool: \(.data.item.name)"' ``` Show only the outcome: ```sh mare --json "Run the linter" | jq -c 'select(.type == "settled") | .data | {reason, exit_code, usage}' ``` ## A script This Python script runs a prompt, prints the session id and each finished tool call, and exits with the run's own exit code. It fails loudly when the stream ends without `settled`. ```python import json import subprocess import sys proc = subprocess.Popen( ["mare", "--json", *sys.argv[1:]], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, text=True, ) settled = None for line in proc.stdout: record = json.loads(line) kind, data = record["type"], record["data"] if kind == "session": print("session", data.get("session_id"), data["cwd"]) elif kind == "item/completed" and (data.get("item") or {}).get("type") == "tool_call": print("tool", data["item"].get("name")) elif kind == "settled": settled = data code = proc.wait() if settled is None: sys.exit(f"stream ended without a settled record (exit code {code})") print(settled["reason"], settled["text"][:200]) sys.exit(settled["exit_code"]) ``` Run it as `python3 run.py "Fix the failing test"`. For two-way control (approvals, host tools, steering a running turn) use the [RPC](https://signalridge.github.io/mare/en/integrate/rpc/) interface instead. ================================================================================ Title: RPC Section: Integrate URL: https://signalridge.github.io/mare/en/integrate/rpc/ Markdown: https://signalridge.github.io/mare/raw/en/integrate/rpc.md Source: docs/en/integrate/rpc.md ================================================================================ # RPC `mare --rpc` is mare's full bidirectional programmatic interface over JSON-RPC 2.0 on stdin and stdout (alongside [headless mode](https://signalridge.github.io/mare/en/use/headless/), [ACP](https://signalridge.github.io/mare/en/integrate/acp/), and the [web listener](https://signalridge.github.io/mare/en/use/web/)), letting any program that can start a process and read lines drive sessions, register tools and hooks, and answer approvals without a language-specific SDK. This page covers the transport, the handshake, the method groups, the callbacks mare sends back, and the peer socket. ## Start the server ```sh mare --rpc --no-session ``` `--mode rpc` is the same thing. Every message is one JSON object on one line. stdout carries protocol messages only; logs go to the log file (see [Files](https://signalridge.github.io/mare/en/reference/files/)). The process serves one host over stdin and stdout: there is no port and no authentication, because only the parent process holds the pipe. Closing stdin (or a read error) ends the session, cancels the active turn and exits with code 0. For one-shot prompts use headless mode instead (see [Headless mode](https://signalridge.github.io/mare/en/use/headless/)). Print the JSON Schemas for the protocol with: ```sh mare rpc schema > mare-rpc.schema.json ``` The output is a catalog, not a schema for one whole message. Its top-level keys are `envelope`, `methods`, `events`, `callbacks`, `notifications`, `client_notifications`, `errors`, `headless`, `ui_image_resource`, and `ui_output_image_key`, plus `protocol_version` (`events` merges native protocol events with events declared in built-in service contracts). Entries point at each other with `$ref`, so resolve them against the complete catalog. Field names and catalog keys use `snake_case` consistently across the protocol (`protocol_version`, `callback_timeout_ms`, `turn_id`, `session_id`, `registration_id`, events, and contract service methods). ## A minimal client This Python client starts mare, runs the handshake, subscribes to events, sends one prompt and waits for the answer. It uses the standard library only. A runnable version with CLI flags is in [`examples/rpc`](https://github.com/signalridge/mare/blob/main/examples/rpc/README.md). ```python import json import subprocess proc = subprocess.Popen( ["mare", "--rpc", "--no-session"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, bufsize=1, ) next_id = 0 def send(msg): msg["jsonrpc"] = "2.0" proc.stdin.write(json.dumps(msg) + "\n") proc.stdin.flush() def handle(msg): """Notifications and callbacks that arrive while we wait for a response.""" method = msg["method"] if method == "event": print("event", msg["params"]["type"]) elif method == "approval.request": send({"id": msg["id"], "result": {"decision": "deny"}}) elif "id" in msg: # a callback we did not declare support for send({"id": msg["id"], "error": {"code": -32601, "message": "not supported"}}) def call(method, params=None): global next_id next_id += 1 rid = next_id send({"id": rid, "method": method, "params": params or {}}) for line in proc.stdout: msg = json.loads(line) if "method" in msg: handle(msg) elif msg.get("id") == rid: if "error" in msg: raise RuntimeError(msg["error"]) return msg["result"] raise RuntimeError("mare closed stdout") call("initialize", { "protocol_version": "3.0", "client": {"name": "demo", "version": "0.1"}, "capabilities": {"approvals": True}, }) session = call("session.create") sid = session["session_id"] call("events.subscribe", {"session_id": sid}) started = call("agent.prompt", {"session_id": sid, "input": "Summarize this repository"}) result = call("agent.wait", {"session_id": sid, "turn_id": started["turn_id"]}) print(result.get("text", "")) call("shutdown") proc.wait() ``` Requests from mare (callbacks) carry an `id` and a `method`; your client must answer each one. Notifications have a `method` and no `id`. The loop above handles both while it waits for its own response. ## Handshake `initialize` must be the first request and runs at most once per connection. Any other request except `shutdown` fails with `-32600` until an `initialize` has succeeded on the connection. Use `connection.set_capabilities` to change capabilities later on the same connection. ```json {"jsonrpc":"2.0","id":1,"method":"initialize","params":{ "protocol_version":"3.0", "client":{"name":"my-host","version":"1.0"}, "capabilities":{"callbacks":true,"ui":true,"approvals":true,"elicitation":false}, "callback_timeout_ms":30000, "approval_timeout_ms":120000}} ``` | Param | Meaning | |---|---| | `protocol_version` | Required `major.minor`. Missing, null, non-string, malformed, or different major fails with `invalid_arguments` / `unsupported_version` (and lets you retry `initialize`). | | `client` | `{name, version?}`, informational. | | `capabilities` | The callbacks you answer: `callbacks` (`callback.call` for tools, hooks, services, providers, web and renderers), `ui`, `approvals`, `elicitation`. All default to `false`. mare never sends a callback you did not declare. | | `callback_timeout_ms` | Deadline for ordinary callbacks (ms). Default 30000, clamped to `1..=3600000`. | | `approval_timeout_ms` | Deadline for human approvals. Without it an approval waits with no deadline. | The result has `protocol_version`, `server` (`{name, version}`), `capabilities`, and (when the process opened a session at startup) `session` (whose `session_id` and `session_epoch` identify the startup session): | Field | Meaning | |---|---| | `methods` | Host-to-mare methods this connection may call. | | `callbacks` | The subset of your declared capabilities that is active. `ui`, `approvals` and `elicitation` are `false` on a peer connection. | | `session` | Optional startup session snapshot opened by the process. Pass `session.session_id` as `session_id` on session-scoped calls. | Minor versions add optional fields, methods and events. Removing or renaming something bumps the major version. There is no `2.x` compatibility layer in `3.0`. ## Host to mare methods | Group | Methods | |---|---| | Sessions | `session.create`, `session.load` `{session_id?, path?}`, `session.get` `{session_id}`, `session.fork` `{session_id, before_item_id?}`, `session.list`, `session.list_items` `{session_id}`, `session.add_record`, `session.list_records`, `session.archive`, `session.unarchive`, `session.delete`, `session.rewind`, `session.search`, `session.snapshot`, `session.close` | | Prompting | `agent.prompt` `{session_id, input}`, `agent.wait` `{session_id, turn_id?}`, `agent.steer` `{session_id, input}`, `agent.cancel` `{session_id}`, `agent.continue` `{session_id}`, `agent.get` `{session_id}`, `agent.list_messages` `{session_id}`, `agent.list_queue` / `agent.update_queued` / `agent.delete_queued`, `compact.run` `{session_id, instructions?}` | | State | `state.snapshot`, `state.compare_exchange`, `status.get`, `llm.list_models`, `flags.list`, `flags.get`, `workspace.get` `{cwd}`, `workspace.set_trust` `{cwd, trusted, save?}`, `permissions.get` `{session_id}`, `permissions.list` `{session_id}`, `permissions.set` `{session_id, name, confirm?}`, `commands.run` `{line, input?, session_id?}` | | Options | `options.get` `{session_id, keys?, describe?}`, `options.set` `{session_id, values}`, `config.describe` `{keys?}` | | Extension | `events.list`, `events.subscribe` `{session_id?, scope?, session_epoch?, last_seq?, include?, exclude?}`, `baseline.read`, `tools.register` `{name, description, parameters, callbacks: ["execute"], side_effect?, scope?, session_id?, ...}`, `hooks.subscribe` `{event, session_id?, scope?, callbacks: ["handle"], ...}` | | Services | `services.list`, `services.register`, `registrations.release` `{registration_id}`; every remote contract method directly as `service.method` (`theme.*`, `llm.*`, `permissions.*`, `usage.get`, `web.*`, `ui.*`; see `mare rpc schema`) | | Output recovery | `spill.list_backends`, `spill.save`, `spill.read`, `spill.delete` | | Lifecycle | `initialize`, `shutdown` | | Peer | `peer.info`, `peer.message` (see [Peer sockets](https://signalridge.github.io/mare/en/integrate/rpc/#peer-sockets)) | ### Prompting `agent.prompt` takes `{session_id, input, when_busy?, request_id?, output_schema?}` and returns `{status, turn_id?, input_id?, duplicate?}`. `input` is text or an array of content parts. When busy, the default is to queue; set `when_busy: "reject"` to reject instead. Call `agent.wait` with `{session_id, turn_id}` for the turn snapshot, or follow `event` notifications. Use `agent.steer` to supply input to a running turn and `agent.cancel` to cancel it. A `request_id` allows idempotent retries within a session. #### Safe retries (`agent.prompt` and `agent.steer`) An error reply does not always mean nothing happened. Group the error by `error.data.code`: - **Rejected before commit:** nothing was queued, no turn started, no message was recorded, and the `request_id` was not remembered, so fix the cause (or reconnect) and send the request again: `parse_error`, `invalid_request`, `method_not_found`, `overloaded`, `denied`, `invalid_arguments`, `unknown_session`, `unsupported`, `request_id_conflict`, `busy`, `agent.rejected`, `agent.no_active_turn`, `agent.turn_mismatch`. - **Indeterminate:** the input may already be committed: `internal`, `cancelled`, `stale_session`, `unavailable`, `invalid_result`, `persist_failed`, `timed_out`, `disconnected`, any other code, and a connection that closes before the reply arrives. `request_id_conflict` leaves the original request and its result untouched. `busy` and `agent.rejected` come only from `agent.prompt`; `agent.no_active_turn` and `agent.turn_mismatch` come only from `agent.steer`. After an indeterminate failure, send the same request again with the same `request_id`: a committed `agent.prompt` replies with its original `turn_id` or `input_id`, and a committed `agent.steer` with its original `input_id`, plus `duplicate: true`, instead of running twice. This holds when the frontend routes the input elsewhere (for example into a focused side conversation), and a resend that arrives while the first request is still running waits for its outcome. Without a `request_id`, check `agent.list_queue` and `agent.list_messages` before sending again. ### Options `options.get` redacts sensitive values (credentials, provider keys and headers), the same as `/config`. With `describe: true` it returns, for each key, `{effective, default?, source?, description?, type?, deprecated?, sensitive, redacted}`. `options.set {session_id: "...", values: {model: "...", effort: "..."}}` is the RPC form of setting `mare.o.<name>`. On the primary connection's default session, committed `options.set` writes also update runtime defaults replayed only on `session.create` (as runtime writes, never elevated to the `cli` config layer); `session.load` and `session.fork` do not replay `options.set` defaults and instead restore the target session's recorded state. See [Options](https://signalridge.github.io/mare/en/configure/options/). ### Host tools ```json {"jsonrpc":"2.0","id":2,"method":"tools.register","params":{ "name":"lookup", "description":"Look up a ticket", "side_effect":"read", "parameters":{"type":"object","properties":{"ticket_id":{"type":"string"}},"required":["ticket_id"]}, "callbacks":["execute"]}} ``` Each `tools.register` call registers one tool owned by the connection and returns `{registration_id}` (pass optional `scope: "all"|"session"` and `session_id` to target a single session). `name`, `description`, `parameters`, and `callbacks: ["execute"]` are required; classify side effects with `side_effect` (`"read"`, `"write"`, or `"external"`). Remote tools always run unconfined outside the local sandbox. You need `capabilities.callbacks: true`; mare invokes registered tools through `callback.call` with `callback: "execute"` and `arguments: {args, ctx: {tool_call_id?, idempotency_key?, cwd?}}`, expecting a string or `{content, is_error?, terminate?, details?}`. While in flight, stream partial progress with `callback.update {id, partial}` using the `callback.call` JSON-RPC request `id`. Release a registration with `registrations.release {registration_id}` (which returns `{}`); registrations a connection holds are also removed when it disconnects. ### Hooks `hooks.subscribe {event, prepend?, timeout_ms?, scope?, session_id?, callbacks: ["handle"]}` requires `capabilities.callbacks: true` and returns `{registration_id}` (release via `registrations.release`). `prepend: true` puts the listener before earlier listeners. Do not pass a `mode` parameter to `hooks.subscribe`: the kernel infers the dispatch mode from `event` (`emit` for `agent/queue` and `status/changed`; `serial` for `request/prepare`; `waterfall` for `request/build`, `tool/result`, and `tool/rewrite`; `policy` for decision points such as `request/ready`, `tool/before`, `tool/approval`, and `net/approval`) and passes it in `callback.call` (`callback: "handle"`, `arguments: {event, mode, args}`). ### Services and output recovery With `capabilities.callbacks: true`, a host may register a service through `services.register {name, methods, scope?, session_id?}` and receive `{registration_id, name}` (release via `registrations.release`). Service names use lowercase letters, digits, `_` and `-` and cannot collide with protocol roots. For a service that already has a contract (and whose methods can all cross the wire), omit `parameters`, `result`, `order`, `expose`, `access`, and `scope` (or repeat them verbatim). For a new service, declare `parameters`, `result`, optional `order`, `doc`, `optional`, `expose` (`"both"` default, or `"lua"`), `access` (`"primary"` default, `"peer"`, or `"peer_default"`), and `scope` (`"host"` default, `"workspace"`, or `"session"`). `services.list` returns visible remote contract methods; invoke them directly as `service.method`. Recoverable tool output is stored per session through `spill.list_backends {}`, `spill.save {session_id, content|data_base64, backend?}` (returns `{spill_id, size}`; base64 bytes are capped at 8 MiB decoded), `spill.read {session_id, spill_id, encoding?, offset?, limit?}` (`encoding: "text"|"base64"`, returns `{content|data_base64, next_offset?, size?}`), and `spill.delete {session_id, spill_id}`. Spill IDs are bound to their owning session and never accept or expose host filesystem paths. ## Callbacks from mare mare sends these as requests. Answer each with a result or an error. | Callback | Params | Result | |---|---|---| | `callback.call` | `{registration_id, callback, session_id?, turn_id?, tool_call_id?, caller_id?, arguments}` | Declared return value for the registration: for tools `{content, is_error?, terminate?}` (when every result of a batch sets `terminate: true`, the run stops unless `agent/turn-stopping` continues); for hooks `null`, `{"next":true}`, or `{"value":...}`; for registered services/providers/web/renderers their declared JSON result | | `approval.request` | `{session_id, turn_id?, kind: "tool"\|"network", approval_id?, tool_call_id?, tool?, arguments, command?, diff?, host?, cwd, reason?, side_effect?, unconfined, proposed_amendment?, requested_permissions?, scope?}` | `{decision, permissions?, scope?, amendment?, reason?}` | | `mcp.elicitation` | `{session_id, turn_id?, server, request_id?, mode?, message, requested_schema?, url?, elicitation_id?, _meta?}` | `{action, content?}` | | `ui.select` | `{title, body?, items: [{label, detail?}], selected?}` | `{index}` (`null` = cancelled) | | `ui.input` | `{title, placeholder?, secret?}` | `{text}` (`null` = cancelled) | | `ui.confirm` | `{prompt, default?}` | `{confirmed}` | | `ui.editor` | `{title, prefill}` | `{text}` (`null` = cancelled) | | `ui.questions` | `{questions}` | `{answers}` | For a long-running `callback.call` (such as a host tool or registered provider stream), send client-to-mare `callback.update` notifications `{id, partial}`, where `id` is the pending `callback.call` request `id` and `partial` is a JSON value (for tools an object such as `{"output": "..."}`). ### Approvals `approval.request` is sent only to the primary connection that declared `capabilities.approvals`. The `decision` values are: | Decision | Effect | |---|---| | `allow` | Run it once. | | `allow_session` | Run it; the permissions plugin remembers the grant for the session. | | `allow_amend` | Run it and pass `amendment` to the permissions plugin to persist as a rule. | | `deny` | Refuse. | | `abort` | Refuse and end the current turn. | No answer, an invalid answer, a timeout or a disconnect counts as `deny`. A decision value mare does not know is rejected and treated as `deny`. Network access needs an explicit affirmative answer; listeners that abstain do not grant it. ### Hook answers For `waterfall`, reply `{"next":true}` to continue unchanged, `{"next":true,"value":...}` to rewrite and pass to the next listener, or `{"value":...}` to short-circuit; `{}` is `invalid_result`. For `tool/rewrite`, `value` is the call object with its `arguments` field, for example `{"value":{"id":"call-1","name":"tool","arguments":{"key":"new"}}}`. For `policy`, put the decision in `value`, for example `{"value":{"decision":"allow"}}` (also `ask` or `deny`, with optional vote fields). An absent value abstains; an unknown decision or field, other invalid answers, timeouts, disconnects, or withdrawal of `capabilities.callbacks` deny. The first deny stops dispatch. ### Cancellation and timeouts mare sends `$/cancel_request {id}` when a callback is no longer active (and accepts `$/cancel_request {id}` from the client to cancel a cooperative in-flight request). Dismiss its UI and ignore any later answer. Ordinary callbacks time out after `callback_timeout_ms`. On a timeout or disconnect: | Callback class | Result | |---|---| | Host tools | A tool error. | | Policy hooks and `approval.request` | `deny`. | | `serial` and `waterfall` hooks | The error propagates to the dispatch. | | UI calls | Cancelled. | ## Notifications | Notification | Params | Notes | |---|---|---| | `event` | `{type, data, session_id?, session_epoch?, seq, turn_id?}` | `turn_id` matches the `agent.prompt` result. `seq` increments contiguously per `(session_id, session_epoch)`. | | `snapshot` | `{session_id?, session_epoch, seq, baseline_id, retained, parts}` | Sent immediately after `events.subscribe` when `mode = "baseline"`, and immediately after `lagged` for an evicted cursor. | | `lagged` | `{from_seq, to_seq}` | Evicted cursor gap before the host cuts and sends a fresh `snapshot`. | | `dropped` | `{count}` | Count of unretained `lossy` or refused events omitted from the stream. | | `event` (`status/changed`) | `{type: "status/changed", data: {state, message, session, seq}}` | `state` is `idle`, `working` or `blocked`. Delivered as an `event` notification only when selected by `events.subscribe` (not sent as a standalone notification). Ignore a `seq` lower than the last one you saw. | | `fs/changed` | `{watch_id, changed_paths, truncated?}` | Policy-filtered filesystem changes for active `fs.watch` subscriptions (`truncated: true` above 8192 entries). | | `ui.notify` | `{text, ...}` | A message for the user. | | `ui/select-updated`, `ui/select-closed`, `ui/component-updated` | see [RPC reference](https://signalridge.github.io/mare/en/reference/rpc/) | Incremental updates to an open `ui.select` modal or attached UI component. | | `stream.failed` | `{error}` | The event stream is incomplete and the connection will close. | | `$/cancel_request` | `{id}` | A callback or cooperative request was cancelled. | | `peer.message_status` | see below | Peer sockets only. | By default `event` carries the same public events as `mare --json` (see [JSON event stream](https://signalridge.github.io/mare/en/integrate/json-stream/)), including contract events declared with `expose = "both"`. `events.subscribe {session_id: "...", include: [...]}` (or `{scope: "all", include: [...]}` on the primary connection) opts into more JSON kernel events by name or `prefix*`. Process-local and provider-private events are never delivered. ### Resuming and baselines When `events.subscribe` answers `mode = "baseline"` (or after `lagged` + a new `snapshot` at `seq = S`), apply `snapshot.retained` and reconcile state in this order: 1. **Buffer live events** (`seq >= S + 1`) arriving while baseline pages are fetched. 2. **Page each part** in `snapshot.parts` (`"entries"`, `"active_items"`) via `baseline.read { baseline_id, part, cursor? }` until `next_cursor` is omitted. If any call fails with JSON-RPC error `error.data.code = "baseline.stale"` (idle >= 60 s, epoch change, superseded, or completed), re-subscribe to obtain a fresh baseline. (`baseline.unknown_part` and `baseline.item_too_large` report an invalid part name or an oversized item.) 3. **Apply buffered events** after reading the baseline, checking that any `item/delta.offset` (or block content offset) equals your local length; on mismatch, rebuild cleanly by calling `events.subscribe` without `last_seq`. ## Errors Every error has `error.data.code`, a name from one vocabulary shared with Lua error values; `error.data.data` carries that code's additional data. The number only groups them: the five standard JSON-RPC numbers, `-32800` for cancellation and `-32000` for everything else. A service's own codes are `<service>.<name>`, declared by its contract and listed by `services.list`; an undeclared or unencodable error is `internal` with a bounded message. The full list is in the [RPC reference](https://signalridge.github.io/mare/en/reference/rpc/#error-codes). | `data.code` | Number | Meaning | |---|---|---| | `parse_error` | `-32700` | Parse error. | | `invalid_request` | `-32600` | Invalid request: also a call before `initialize`, a duplicate in-flight id, or a line over the size limit. | | `method_not_found` | `-32601` | Unknown method, or a method not allowed on a peer socket. | | `invalid_arguments` | `-32602` | Invalid params. | | `internal` | `-32603` | Internal error; the message is bounded and carries no raw error value. | | `cancelled` | `-32800` | Cancelled (`$/cancel_request`, owner release, shutdown). | | `overloaded` | `-32000` | More than 256 requests in flight. | | `busy` | `-32000` | A per-connection limit or the peer inbound queue is full. | | `unsupported_version` | `-32000` | Unsupported protocol version. | | `request_id_conflict` | `-32000` | A `agent.prompt` `request_id` was reused with different content. | | `unsupported` | `-32000` | Unsupported capability or media input; `data.data.capability` names it. | | `timed_out`, `disconnected`, `denied` | `-32000` | Service call timeout, callback disconnect, refusal for this connection. A remote implementation's error without a structured code is `internal`. | ## Limits - A request line may be 64 MiB. A longer line is skipped and answered with `-32600`. - Per connection, at most 4096 selected events and 64 MiB of serialized event records are admitted, and the output queue holds at most 4096 lines and 64 MiB. A record or line over its budget fails that connection. - Selected events are fixed when admitted. A change to `events.subscribe` applies to later events. - A response is queued after events that were already admitted. - If an event cannot be encoded or delivered, mare sends `stream.failed` while output is still writable. If it is not, EOF or a truncated line is the signal. - A failed or closed stdout cancels the active turn. A failed peer does not cancel the shared session. ## Peer sockets Outbound peer clients are constructed in Lua through `mare.peers` (owned by the `peers` plugin contract; idle waiting uses `status/changed`). Each message identifies the session current at send time in `from.session_id`. An interactive session also listens on `<state>/peers/<pid>.sock`, and `--rpc` or headless runs do too when started with `--peer`. Other programs of the same user can talk to it. The socket speaks a least-privilege subset of this protocol: - The socket is mode 0600 in a 0700 directory (if the directory is a symlink or owned by another user, the session does not listen). On accept, mare verifies the connecting user id (Linux `SO_PEERCRED`, macOS `getpeereid`) and disconnects other users. On Windows the transport is a named pipe whose DACL admits only the current user's SID and SYSTEM (rejecting remote clients), with a random 128-bit pipe name written to the endpoint file at the socket path and verified by clients before use. - A peer may call `initialize`, `peer.info`, `status.get`, `peer.message`, `events.subscribe` (explicitly `status/changed` only), and `shutdown` (which ends only that connection). Everything else fails with `-32601` (or `denied` for broader `events.subscribe` filters). - To allow more, list exact method names (such as `"events.subscribe"` for the full event stream) in the `peer` option; wildcards and prefixes are not accepted: ```lua mare.setup { peer = { name = "main", allow = { "agent.prompt", "tools.register", "events.subscribe" } }, } ``` `peer = false` turns the socket off. Primary-only methods (`options.set`, `commands.run`, `hooks.subscribe`, and other `access = "primary"` operations) are never grantable to peers. A peer never takes over the UI or approvals. Request lines on the peer socket are limited to 1 MiB, and at most 32 inbound messages wait for the user at once. | Method | Params | Result | |---|---|---| | `peer.info` | `{}` | `{name, pid, cwd, version, allowed}` | | `status.get` | `{}` | The unified status, the same shape as `status/changed`. | | `peer.message` | `{from: {name?, pid?, cwd?, session_id?}, text, queue_only?, policy?}` | `{message_id, status}` | What the sender says about itself in `from` and `policy` is shown to the receiving user and never grants anything. An empty `text` fails with `-32602`, and where peer credentials report the connecting process, a `from.pid` or registered `from.name` that disagrees with it is also refused with `-32602`. A message is held until the receiving user accepts or rejects it, and the answer arrives as a `peer.message_status {message_id, status}` notification with `delivered` or `rejected` (without a UI it is rejected). A delivered message reaches the agent as a follow-up inside a data boundary that marks it as coming from another session. Running sessions register in `<state>/peers/<pid>.json` with `{name, pid, cwd, socket, mode, started, status, plugins?}`, where `plugins` stores optional opaque namespaces published via `mare.peers.publish(namespace, fields)` (rewritten at most every 200 ms; entries and sockets are removed on exit and dead entries are pruned when listed). ### Send a message from the shell ```sh mare peer send --to main "tests are green on the integration branch" printf 'see the diff in /tmp/x.patch' | mare peer send --to main ``` `--to` takes a socket path or a registered session name. Without it, mare uses `$MARE_PEER_SOCKET`, which tools and hooks started by a mare session inherit. The command prints the resulting status (`held`, `delivered` or `handled`) and exits 0 when the receiver accepted the message. Text comes from the arguments, or from stdin when there are none. The plugin manager emits the in-process Lua event `plugins/completed { action, name?, status }`. See [Services and events](https://signalridge.github.io/mare/en/extend/services-and-events/) for its payload. ================================================================================ Title: CLI Section: Reference URL: https://signalridge.github.io/mare/en/reference/cli/ Markdown: https://signalridge.github.io/mare/raw/en/reference/cli.md Source: docs/en/reference/cli.md ================================================================================ # CLI Every `mare` command and flag, as printed by `--help`. > This page is generated from the code by `scripts/gen_docs.py`. Do not edit it by hand. ## mare ```text Agent harness (Rust core, Lua plugins) Usage: mare [OPTIONS] [PROMPT]... [COMMAND] Commands: plugin Manage plugins acp Run as an Agent Client Protocol server over stdio trust Trust (or revoke trust for) a directory (default: current project root, git worktree root, or cwd) session Sessions: create, list, fork, archive, unarchive, or delete saved sessions runtime Print the runtime directory (read-only copies of builtin plugins and types) init Create a default ~/.config/mare/init.lua and .luarc.json doctor Check config, credentials, connectivity and plugins login Log in to a provider; `mare login status` lists every provider logout Remove a provider's stored credentials (all of them; tokens are revoked first) model Model catalogue: `mare model refresh` re-reads every logged-in provider's model list completion Print a shell completion script: `mare completion zsh > ~/.zfunc/_mare` mcp MCP servers: list, list-tools, enable, disable, login peer Talk to mare sessions over their peer sockets rpc RPC protocol helpers sandbox Windows enhanced sandbox: install, remove or inspect test Run Lua *_spec.lua tests using the mare.test harness (cases in the same spec file share an isolated file-level Lua environment) token Host runtime authentication token management web Host HTTP/WebSocket listener helpers help Print this message or the help of the given subcommand(s) Arguments: [PROMPT]... Initial prompt (interactive) or the prompt to run (with -p) Options: -p, --print Headless: run the prompt, print the final answer, exit --mode <MODE> Output mode: text (default), json (event stream), rpc (stdin/stdout JSON lines) [possible values: text, json, rpc] --json Shorthand for --mode json --stream-deltas With --json: also emit the streaming deltas (`item/delta`); without it the stream is item level (starts, messages, tool calls, usage) --output-schema <FILE> JSON Schema file that the final assistant output must conform to (headless runs: -p / --json) --rpc Bidirectional JSON-RPC 2.0 over stdin/stdout (same as --mode rpc; `mare rpc schema`) -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --add-dir <DIR> Add an extra directory to the workspace (repeatable; existing absolute physical directories only) --append-system-prompt <TEXT> Append text to the system prompt -c, --continue Continue the most recent session in this directory (with --all: in any directory) -r, --resume [<RESUME>] Resume a session: its id (or an unambiguous prefix), its name, -N (the Nth most recent) or a file path; without a value opens the picker --all With -c / --resume: look at sessions of every directory, not just this one --fork-session With -c / --resume: continue in a copy (a new session), leaving the original as it was --session-id <ID> Use this id for the new session (8-64 letters, digits, - or _; e.g. a UUID) --name <NAME> Name the session (also `mare session new --name …`) --no-session Do not persist this session --max-turns <N> Stop after this many model turns in one prompt (headless exit code 4) --timeout <DURATION> Stop the run after this long, e.g. 90s, 5m, 1h (headless exit code 4) --permission <PERMISSION> Permission preset for this session: read-only | auto | full-access [possible values: read-only, auto, full-access] --approval-policy <APPROVAL_POLICY> Independent approval policy; never rejects requests without prompting [possible values: ask, never, untrusted] --yolo Shorthand for --permission full-access --peer Headless / --rpc: also serve RPC on this session's peer socket and register it (interactive sessions always do unless `peer = false`) --web Enable the host HTTP/WebSocket RPC listener --web-listen <ADDR> Bind address (`HOST:PORT`) for the host HTTP/WebSocket RPC listener (`--web`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help -V, --version Print version ``` ## mare plugin ```text Manage plugins Usage: mare plugin [OPTIONS] <COMMAND> Commands: list List declared and installed plugins tree Print the composed runtime plugin tree sync Install plugins declared in init.lua (respects mare-lock.json) update Update plugins to their latest revision and rewrite mare-lock.json check Check for updates without moving checkouts or changing the lock restore Restore plugins to the commits recorded in mare-lock.json clean Remove checkouts that are no longer declared install Install one or more catalog plugins uninstall Uninstall one or more catalog plugins help Print this message or the help of the given subcommand(s) Options: -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ### mare plugin list ```text List declared and installed plugins Usage: mare plugin list [OPTIONS] Options: --json Print the list as JSON -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ### mare plugin tree ```text Print the composed runtime plugin tree Usage: mare plugin tree [OPTIONS] Options: --json Print the tree as JSON -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ### mare plugin sync ```text Install plugins declared in init.lua (respects mare-lock.json) Usage: mare plugin sync [OPTIONS] Options: -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ### mare plugin update ```text Update plugins to their latest revision and rewrite mare-lock.json Usage: mare plugin update [OPTIONS] [NAME] Arguments: [NAME] Options: --stash Save local changes and untracked files in git stash before updating -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ### mare plugin check ```text Check for updates without moving checkouts or changing the lock Usage: mare plugin check [OPTIONS] [NAMES]... Arguments: [NAMES]... Options: --json Print structured results as JSON -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ### mare plugin restore ```text Restore plugins to the commits recorded in mare-lock.json Usage: mare plugin restore [OPTIONS] [NAME] Arguments: [NAME] Options: --repair Rebuild a missing or corrupt lock from clean installed checkouts -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ### mare plugin clean ```text Remove checkouts that are no longer declared Usage: mare plugin clean [OPTIONS] Options: --force Allow removal of ignored files and saved git stashes -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ### mare plugin install ```text Install one or more catalog plugins Usage: mare plugin install [OPTIONS] <NAMES>... Arguments: <NAMES>... Options: -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ### mare plugin uninstall ```text Uninstall one or more catalog plugins Usage: mare plugin uninstall [OPTIONS] <NAMES>... Arguments: <NAMES>... Options: -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ## mare acp ```text Run as an Agent Client Protocol server over stdio Usage: mare acp [OPTIONS] Options: -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ## mare trust ```text Trust (or revoke trust for) a directory (default: current project root, git worktree root, or cwd) Usage: mare trust [OPTIONS] [DIR] Arguments: [DIR] Options: --revoke -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ## mare session ```text Sessions: create, list, fork, archive, unarchive, or delete saved sessions Usage: mare session [OPTIONS] <COMMAND> Commands: new Create an empty session in this directory and print its id list List saved sessions (newest first; current directory by default) fork Fork a saved session (by id, prefix, name, or path) and print the new session id archive Archive a saved session (by id, prefix, name, or path) unarchive Restore an archived session (by id, prefix, name, or path) delete Permanently delete a saved session (by id, prefix, name, or path) help Print this message or the help of the given subcommand(s) Options: -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ### mare session new ```text Create an empty session in this directory and print its id Usage: mare session new [OPTIONS] Options: -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ### mare session list ```text List saved sessions (newest first; current directory by default) Usage: mare session list [OPTIONS] Options: --all Include sessions from every workspace --archived List archived sessions instead of active ones --limit <N> Maximum number of sessions to show --json Print JSON matching RPC `session.list` -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ### mare session fork ```text Fork a saved session (by id, prefix, name, or path) and print the new session id Usage: mare session fork [OPTIONS] <SESSION> Arguments: <SESSION> Session id, unique prefix, name, or path Options: -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ### mare session archive ```text Archive a saved session (by id, prefix, name, or path) Usage: mare session archive [OPTIONS] <SESSION> Arguments: <SESSION> Session id, unique prefix, name, or path Options: -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ### mare session unarchive ```text Restore an archived session (by id, prefix, name, or path) Usage: mare session unarchive [OPTIONS] <SESSION> Arguments: <SESSION> Session id, unique prefix, name, or path Options: -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ### mare session delete ```text Permanently delete a saved session (by id, prefix, name, or path) Usage: mare session delete [OPTIONS] <SESSION> Arguments: <SESSION> Session id, unique prefix, name, or path Options: --yes Skip the interactive confirmation prompt (required when stdin is not a TTY) -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ## mare runtime ```text Print the runtime directory (read-only copies of builtin plugins and types) Usage: mare runtime [OPTIONS] Options: -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ## mare init ```text Create a default ~/.config/mare/init.lua and .luarc.json Usage: mare init [OPTIONS] Options: -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ## mare doctor ```text Check config, credentials, connectivity and plugins Usage: mare doctor [OPTIONS] Options: --fix Safe fixes only: create missing directories, tighten permissions (0700 / 0600) --json Print the checks as one JSON document -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ## mare login ```text Log in to a provider; `mare login status` lists every provider Usage: mare login [OPTIONS] [PROVIDER] Arguments: [PROVIDER] provider name, or `status` Options: --with-api-key Read an API key from stdin: `printenv OPENAI_API_KEY | mare login openai --with-api-key` --device-auth Sign in with a device code (no browser here, e.g. over SSH) --oauth Sign in using browser OAuth -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ## mare logout ```text Remove a provider's stored credentials (all of them; tokens are revoked first) Usage: mare logout [OPTIONS] [PROVIDER] Arguments: [PROVIDER] Options: -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ## mare model ```text Model catalogue: `mare model refresh` re-reads every logged-in provider's model list Usage: mare model [OPTIONS] <COMMAND> Commands: refresh Fetch the model lists (and models.dev metadata) now help Print this message or the help of the given subcommand(s) Options: -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ### mare model refresh ```text Fetch the model lists (and models.dev metadata) now Usage: mare model refresh [OPTIONS] Options: -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ## mare completion ```text Print a shell completion script: `mare completion zsh > ~/.zfunc/_mare` Usage: mare completion [OPTIONS] <SHELL> Arguments: <SHELL> [possible values: bash, elvish, fish, powershell, zsh] Options: -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ## mare mcp ```text MCP servers: list, list-tools, enable, disable, login Usage: mare mcp [OPTIONS] <COMMAND> Commands: list Connect to every enabled server and print its state, tools and errors (exit 1 on problems) list-tools Print a server's tools with their input schemas enable Enable a server in this project (kept in the state directory, not the config file) disable Disable a server in this project login Log in to an OAuth server in the browser help Print this message or the help of the given subcommand(s) Options: -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ### mare mcp list ```text Connect to every enabled server and print its state, tools and errors (exit 1 on problems) Usage: mare mcp list [OPTIONS] Options: -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ### mare mcp list-tools ```text Print a server's tools with their input schemas Usage: mare mcp list-tools [OPTIONS] <SERVER> Arguments: <SERVER> Options: -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ### mare mcp enable ```text Enable a server in this project (kept in the state directory, not the config file) Usage: mare mcp enable [OPTIONS] <SERVER> Arguments: <SERVER> Options: -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ### mare mcp disable ```text Disable a server in this project Usage: mare mcp disable [OPTIONS] <SERVER> Arguments: <SERVER> Options: -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ### mare mcp login ```text Log in to an OAuth server in the browser Usage: mare mcp login [OPTIONS] <SERVER> Arguments: <SERVER> Options: -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ## mare peer ```text Talk to mare sessions over their peer sockets Usage: mare peer [OPTIONS] <COMMAND> Commands: send Send a message to a session: by default the one this process runs under ($MARE_PEER_SOCKET, set for tools and hooks); held until its user confirms help Print this message or the help of the given subcommand(s) Options: -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ### mare peer send ```text Send a message to a session: by default the one this process runs under ($MARE_PEER_SOCKET, set for tools and hooks); held until its user confirms Usage: mare peer send [OPTIONS] [TEXT]... Arguments: [TEXT]... the message (read from stdin when omitted) Options: --to <TO> a session's socket path or registered name (default: $MARE_PEER_SOCKET) -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ## mare rpc ```text RPC protocol helpers Usage: mare rpc [OPTIONS] <COMMAND> Commands: schema Print the JSON Schema of the RPC protocol help Print this message or the help of the given subcommand(s) Options: -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ### mare rpc schema ```text Print the JSON Schema of the RPC protocol Usage: mare rpc schema [OPTIONS] Options: -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ## mare sandbox ```text Windows enhanced sandbox: install, remove or inspect Usage: mare sandbox [OPTIONS] <COMMAND> Commands: setup Install the enhanced tier (elevates once): sandbox accounts, deny-read ACLs, WFP filters status Show the installed setup and run the self-test help Print this message or the help of the given subcommand(s) Options: -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ### mare sandbox setup ```text Install the enhanced tier (elevates once): sandbox accounts, deny-read ACLs, WFP filters Usage: mare sandbox setup [OPTIONS] Options: --remove Undo everything setup installed --deny-read <PATH> Extra path that sandboxed commands must not read (repeatable; also `sandbox.deny_read`) --no-default-deny-read Don't apply the built-in deny-read list (credentials, browser profiles) -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ### mare sandbox status ```text Show the installed setup and run the self-test Usage: mare sandbox status [OPTIONS] Options: --require-full Exit non-zero unless all sandbox isolation capabilities are fully enforced -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ## mare test ```text Run Lua *_spec.lua tests using the mare.test harness (cases in the same spec file share an isolated file-level Lua environment) Usage: mare test [OPTIONS] [PATH]... Arguments: [PATH]... Spec files or directories to run (default: current directory) Options: -f, --filter <PATTERN> Only run test cases whose full name contains this substring -u, --update-snapshots Update snapshot files directly instead of failing or writing .snap.new -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ## mare token ```text Host runtime authentication token management Usage: mare token [OPTIONS] <COMMAND> Commands: rotate Generate a new 32-byte host token (0600) and immediately invalidate the previous token help Print this message or the help of the given subcommand(s) Options: -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ### mare token rotate ```text Generate a new 32-byte host token (0600) and immediately invalidate the previous token Usage: mare token rotate [OPTIONS] Options: --accept-partial <ACCEPT_PARTIAL> Accept missing sandbox protection explicitly (e.g. fs_host_protect) -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ## mare web ```text Host HTTP/WebSocket listener helpers Usage: mare web [OPTIONS] <COMMAND> Commands: url Print the authenticated login URL for the running host webserver help Print this message or the help of the given subcommand(s) Options: -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ### mare web url ```text Print the authenticated login URL for the running host webserver Usage: mare web url [OPTIONS] Options: -m, --model <MODEL> Model, e.g. openai/gpt-6.1-terra --agent <NAME> Use a registered agent type for the initial session -e, --effort <EFFORT> Reasoning effort (off, minimal, low, medium, high, xhigh, max) --tools <TOOLS> Only enable these tools (comma separated), e.g. --tools read,bash --exclude-tools <TOOLS> Exclude these tools (repeatable or comma separated; supports `*`), e.g. --exclude-tools bash,write --append-system-prompt <TEXT> Append text to the system prompt --name <NAME> Name the session (also `mare session new --name …`) --set <KEY=VALUE> Override config values: --set plugins.tools.edit_mode=replace --strict-config Refuse to start (exit code 2) when the configuration has warnings (unknown options, type errors, unparseable MARE_* values) or init.lua errors instead of continuing --trust Trust this project for this run (load its plugins, skills, prompts, system prompt); overrides the saved decision and saves nothing --no-trust Don't trust this project for this run, whatever was saved --approve-mcps Approve the project's and $MARE_MCP_CONFIG's MCP servers (remembered by name and configuration hash) without asking — for headless runs --clean Like `nvim --clean`: no user/project config, user plugins, or packages --startuptime <FILE> Write startup timing to a file (like Neovim's --startuptime) --profile-startup Start the TUI, quit once it is ready, and print how long each startup stage took -C, --cwd <CWD> Working directory -h, --help Print help ``` ================================================================================ Title: Environment variables Section: Reference URL: https://signalridge.github.io/mare/en/reference/environment/ Markdown: https://signalridge.github.io/mare/raw/en/reference/environment.md Source: docs/en/reference/environment.md ================================================================================ # Environment variables Every environment variable mare reads, grouped by what it controls, and the variables mare sets for the commands it starts. For `MARE_<OPTION>` configuration variables, the environment wins over `init.lua`, while command-line flags win over the environment (other sections note their own precedence, such as provider credentials). > This reference page is maintained by hand (not generated by `scripts/gen_docs.py`). ## Directories mare uses XDG-style locations on every platform, including Windows and macOS. See [Files](https://signalridge.github.io/mare/en/reference/files/) for what lives in each directory. | Variable | Effect | |---|---| | `MARE_HOME` | Root for all four directories. Config, state, data and cache become `config`, `state`, `data` and `cache` below it. Wins over the `XDG_*` variables. Useful for throwaway runs and tests. | | `XDG_CONFIG_HOME` | Config directory is `$XDG_CONFIG_HOME/mare`. Default `~/.config/mare`. | | `XDG_STATE_HOME` | State directory is `$XDG_STATE_HOME/mare`. Default `~/.local/state/mare`. | | `XDG_DATA_HOME` | Data directory is `$XDG_DATA_HOME/mare`. Default `~/.local/share/mare`. | | `XDG_CACHE_HOME` | Cache directory is `$XDG_CACHE_HOME/mare`. Default `~/.cache/mare`. | | `HOME`, `USERPROFILE` | The home directory behind the defaults above and behind `~` in paths. `USERPROFILE` is the Windows fallback. | Empty values count as unset. ## Configuration Config layers apply in this order, later ones winning: option defaults, `state.json`, user `init.lua`, project `.mare/init.lua`, the `MARE_<OPTION>` variables below, and finally command-line flags (`--set`, `-m`, `-e`). | Variable | Effect | |---|---| | `MARE_<OPTION>` | Sets the core option of the same name, upper-cased: `MARE_THEME`, `MARE_BORDER`, `MARE_REDUCE_MOTION`, `MARE_UPDATE_CHECK`, and so on. Every core option has one (see [Options](https://signalridge.github.io/mare/en/configure/options/)). The value is parsed as JSON and used as a string when it is not JSON: `MARE_REDUCE_MOTION=true`, `MARE_PERF='{"highlight_cache":64}'`. A value that starts with `{`, `[` or `"` but does not parse is ignored with a warning. | | `MARE_MODEL`, `MARE_EFFORT` | The model and reasoning effort for this invocation. `MARE_EFFORT` applies to this invocation only. | | `MARE_TRUST_DEFAULT` | Default project trust when nothing is recorded: `ask`, `trust` or `distrust` (`always` and `never` are accepted too). | | `MARE_WATCHDOG_MS` | Per-callback limit in milliseconds for Lua code that never yields. Default 10000. The watchdog starts before `init.lua`, so it can only be set here or with `--set watchdog_ms=...`. | | `MARE_LUA_MEMORY_MB` | Memory limit in MiB for the Lua VM. The VM is created before `init.lua`, so it only takes effect here or with `--set lua_memory_mb=...`. | | `MARE_APPROVAL_POLICY` | Overrides the `approvals` plugin's `policy` option (`ask`, `never`, `untrusted`, or JSON for granular policies). | | `MARE_WEB_SEARCH_PROVIDER`, `MARE_WEB_FETCH_PROVIDER` | Override the `web` plugin's `search_provider` and `fetch_provider` options. | | `MARE_MCP_CONFIG` | Path of an extra MCP configuration file. Its servers start only after approval (`--approve-mcps` approves them without asking). | | `MARE_DEV_PLUGINS` | A directory of built-in plugin sources to load from disk instead of the copies embedded in the binary. For working on mare itself. | Invalid `MARE_<OPTION>` values are reported at startup; `--strict-config` turns those warnings into a refusal to start. ## Provider credentials A provider reads its key from, in order: the `api_key` option in `init.lua`, the credentials stored by `mare login`, then these variables. See [Models](https://signalridge.github.io/mare/en/use/models/). | Variable | Provider | |---|---| | `OPENAI_API_KEY` | OpenAI | | `ANTHROPIC_API_KEY` | Anthropic | | `GEMINI_API_KEY`, `GOOGLE_API_KEY` | Google (`GEMINI_API_KEY` is checked first) | | `OPENCODE_API_KEY` | opencode Go | | `DEEPSEEK_API_KEY` | DeepSeek | | `MOONSHOT_API_KEY` | Moonshot (`kimi`) | | `KIMI_API_KEY` | Kimi Code (`kimi-code`) | | `OPENROUTER_API_KEY` | OpenRouter | An OpenAI-compatible provider you define can name its own variable with `api_key_env`. An `api_key` option that is the name of an environment variable is read from that variable. MCP server configuration can also pull values from the environment: `${VAR}`, `${env:VAR}` and `${VAR:-default}` in strings, `bearer_token_env_var`, and `env_http_headers`. ## Network and certificates | Variable | Effect | |---|---| | `HTTPS_PROXY`, `HTTP_PROXY`, `ALL_PROXY` (either case) | HTTP and HTTPS proxy for mare's own requests. Commands started by mare inherit them unchanged, except in a sandbox that restricts the network: there mare sets the proxy variables to its own local filtering proxy and clears `NO_PROXY`. SOCKS proxies and PAC files are not supported and fail with an error instead of connecting directly. | | `NO_PROXY` (either case) | Hosts that bypass the proxy. When a proxy is set and `NO_PROXY` is not, commands mare starts get `NO_PROXY=localhost,127.0.0.1,::1`. | | `MARE_CA_CERTIFICATE` | A PEM bundle of extra trusted CA certificates. When set it is the only custom source. | | `SSL_CERT_FILE` | A PEM bundle, used when `MARE_CA_CERTIFICATE` is not set. | | `SSL_CERT_DIR` | A directory list (`:`-separated, `;` on Windows) of PEM or `.crt` files, added to the above. | Certificates are added to the system roots; mare bundles none. A named file that cannot be read, or that contains no certificate, is an error. With `transport = "auto"`, OpenAI requests use HTTP instead of a WebSocket when `HTTPS_PROXY` or `ALL_PROXY` (either case) is set, because the WebSocket client does not go through HTTP proxies. ## Terminal and display | Variable | Effect | |---|---| | `NO_COLOR` | Any non-empty value turns colors off. | | `MARE_COLOR` | Forces the color depth: `truecolor`, `256` or `16`. Overridden by `NO_COLOR`. | | `COLORTERM` | `truecolor` or `24bit` selects true color. | | `TERM` | `256` in the name selects 256 colors. `dumb` switches the interface to plain line-by-line output. `linux` with a non-UTF-8 locale selects ASCII icons. | | `TERM_PROGRAM`, `TERM_PROGRAM_VERSION` | Identify the terminal for color depth, icon set, width rules and image protocol. | | `COLUMNS` | Width fallback in plain (`TERM=dumb`) mode. | | `MARE_NERD_FONT`, `NERD_FONT` | `1` selects the Nerd Font icon set. | | `LC_ALL`, `LC_CTYPE`, `LANG` | The first one set decides whether the locale is UTF-8. | | `MARE_WIDTH_METHOD` | Forces how character width is measured: `unicode` or `wcwidth`. | | `MARE_NO_TERM_PROBE` | When set, skips all startup terminal queries, including background color and capability probes. | | `MARE_NO_OSC11` | When set, skips only the OSC 11 background-color query; other capability probes still run. | mare also recognizes a terminal from variables it sets, to pick key, image and clipboard behavior: `KITTY_WINDOW_ID`, `GHOSTTY_RESOURCES_DIR`, `WEZTERM_EXECUTABLE`, `WEZTERM_PANE`, `ALACRITTY_WINDOW_ID`, `ALACRITTY_SOCKET`, `WT_SESSION`, `KONSOLE_VERSION`, `VTE_VERSION`, `VSCODE_INJECTION`, `ITERM_SESSION_ID`, `WARP_SESSION_ID`, and the multiplexer markers `TMUX`, `TMUX_PANE`, `STY` and `ZELLIJ`. You do not set these yourself. Clipboard copy also looks at `SSH_TTY`, `SSH_CONNECTION` and `WSL_DISTRO_NAME` to choose between native and OSC 52 copy. ## Editor, shell and login | Variable | Effect | |---|---| | `VISUAL`, `EDITOR` | The external editor, used after the `editor` option and in that order. The fallback is `vi`. The value may include arguments, such as `code --wait`. | | `SHELL` | The shell for the bash tool when the `tools` plugin's `shell` option is not set: `$SHELL` if it is bash or zsh, otherwise `bash`. | | `SSH_CONNECTION`, `SSH_TTY` | When either is set, `mare login` assumes there is no local browser and offers the device-code flow first. MCP OAuth login asks you to paste the redirected address. | | `DISPLAY`, `WAYLAND_DISPLAY` | On Linux, when both are empty `mare login` assumes there is no browser. | ## Logging and diagnostics | Variable | Effect | |---|---| | `MARE_LOG` | Log filter for `<state>/log/mare.log`. A level (`debug`, `trace`) or per-module filters (`mare_binding=trace`). Default `info`. | | `MARE_NO_HARDENING` | `1` skips the startup hardening: no core dumps, no debugger attach, and `LD_*` / `DYLD_*` variables removed from mare and its commands. | | `MARE_FRAME_LOG` | A file path. mare writes one render time in microseconds per line while the TUI runs. | | `MARE_SANDBOX_BACKEND` | `none` turns off the OS sandbox backend; `landlock` forces the Landlock backend on Linux. | | `MARE_SANDBOX_CAPS` | Comma-separated sandbox capabilities (for example `fs_write,net_block`) that narrow what the detected backend is allowed to claim. | | `MARE_SANDBOX_DIR` | Windows: the enhanced sandbox directory. Default `%ProgramData%\mare\sandbox`. | | `MARE_SANDBOX_HELPER` | Windows: the executable that serves as the sandbox runner, instead of `mare` itself. | | `MARE_UPDATE_SNAPSHOTS` | Controls snapshot updates for `mare test` (`always` updates snapshot files directly, equivalent to `--update-snapshots`). | | `MARE_PROFILE_LUA_EVERY` | Lua instruction sampling interval for startup profiling (`--profile-startup` / `--startuptime`); positive integer, default `1000000`. | | `MARE_VALIDATE_RECORDS` | `1` enables strict session storage record validation in release builds. | | `MARE_FAUX_SCRIPT` | A file holding a JSON array that scripts the `faux` test provider (available only in debug builds or builds compiled with the `faux` feature; release binaries omit it). | ## Commands started by mare Commands run by the `bash` tool and other tools start from your environment with two changes. A hook command such as `notify.cmd` gets only the first change (the credential scrub), not the additions below. Credential-shaped names are removed. Any variable whose name contains `KEY`, `PASSWORD`, `SECRET` or `TOKEN` (any case) is dropped, and so is every `MARE_*` variable. Adjust this for the `bash` tool and `mare.tool.command` tools with the `env` option of the `tools` plugin: `include`, `exclude`, and `set` all apply to both: ```lua mare.plugin("tools", { env = { include = { "GH_TOKEN" }, -- keep a name the scrub would drop exclude = { "AWS_PROFILE" }, -- drop a name it would keep set = { PAGER = "less" }, -- set a value for every tool command }, }) ``` Then mare adds these for tool commands: | Variable | Value | |---|---| | `TERM` | `dumb` | | `PAGER`, `GIT_PAGER`, `GH_PAGER` | `cat` | | `NO_COLOR` | `1` | | `LANG`, `LC_CTYPE` | `C.UTF-8` (`en_US.UTF-8` on macOS), only when none of `LANG`, `LC_ALL`, `LC_CTYPE` is set. Not set on Windows. | | `MARE_CWD` | The session's working directory. | | `MARE_SESSION_ID` | The session id. | | `MARE_SESSION_MODEL`, `MARE_SESSION_EFFORT` | The current model reference and effort. They are named `MARE_SESSION_*` so a nested mare does not read them as config. | | `MARE_PEER_SOCKET` | This session's peer socket, when it has one. `mare peer send` uses it. | The `status` plugin's command (see [Services and events](https://signalridge.github.io/mare/en/extend/services-and-events/)) also receives `MARE_STATE`, `MARE_MESSAGE`, `MARE_SESSION_ID`, `MARE_SESSION_PATH`, `MARE_CWD`, `MARE_SESSION_MODEL` and `MARE_PEER_SOCKET`. While the TUI is open, mare also sets `SUDO_ASKPASS`, `MARE_ASKPASS_SOCK` and `MARE_ASKPASS_TOKEN` for commands, so `sudo` password prompts reach the TUI's masked input box instead of failing for lack of a terminal. ================================================================================ Title: Event reference Section: Reference URL: https://signalridge.github.io/mare/en/reference/events/ Markdown: https://signalridge.github.io/mare/raw/en/reference/events.md Source: docs/en/reference/events.md ================================================================================ # Event reference Built-in public protocol and contract events, with their payload schemas. See [JSON event stream](https://signalridge.github.io/mare/en/integrate/json-stream/) and [Services and events](https://signalridge.github.io/mare/en/extend/services-and-events/) for usage. > This page is generated from the code by `scripts/gen_docs.py`. Do not edit it by hand. Protocol version: **3.0** ## turn ### `turn/started` Agent turn started. | Mode | Delivery | Ignorable | Retain | On error | |---|---|---|---|---| | `emit` | `required` | no | no | `continue` | | Field | Type | Required | Description | |---|---|---|---| | `turn_id` | `string` | yes | | | `trigger` | `string` | yes | | | `input_item_ids` | `string[] \| null` | | | | `text` | `string \| null` | | | | `source` | `string \| null` | | | | `truncated` | `boolean \| null` | | | **Example** ```json { "turn_id": "t-1", "trigger": "prompt" } ``` ### `turn/completed` Agent turn completed after run-end durability confirmation. | Mode | Delivery | Ignorable | Retain | On error | |---|---|---|---|---| | `emit` | `required` | no | no | `continue` | | Field | Type | Required | Description | |---|---|---|---| | `turn_id` | `string` | yes | | | `status` | `TurnStatus` | yes | | | `termination_reason` | `AgentTerminationReason \| null` | | | | `cancellation_cause` | `CancellationCause \| null` | | Origin of cancellation when `termination_reason` is `interrupted`. | | `text` | `string \| null` | | | | `structured` | `any` | | | | `usage` | `object \| null` | | | | `error` | `EventError \| null` | | | | `error_kind` | `string \| null` | | | | `not_sent` | `boolean \| null` | | | | `truncated` | `boolean \| null` | | | **Example** ```json { "turn_id": "t-1", "status": "completed", "usage": {} } ``` ## step ### `step/started` Model step started within a turn. | Mode | Delivery | Ignorable | Retain | On error | |---|---|---|---|---| | `emit` | `required` | no | no | `continue` | | Field | Type | Required | Description | |---|---|---|---| | `turn_id` | `string` | yes | | | `step_id` | `string` | yes | | | `turn` | `integer \| null` | | | | `model` | `any` | | | | `attempt` | `integer \| null` | | | | `truncated` | `boolean \| null` | | | **Example** ```json { "turn_id": "t-1", "step_id": "s-1", "turn": 1, "attempt": 0 } ``` ### `step/completed` Model step finished (completed, failed, or retrying). | Mode | Delivery | Ignorable | Retain | On error | |---|---|---|---|---| | `emit` | `required` | no | no | `continue` | | Field | Type | Required | Description | |---|---|---|---| | `turn_id` | `string` | yes | | | `step_id` | `string` | yes | | | `status` | `StepStatus` | yes | | | `stop_reason` | `string \| null` | | | | `usage` | `any` | | | | `error` | `EventError \| null` | | | | `error_kind` | `string \| null` | | | | `will_retry` | `boolean \| null` | | | | `attempt` | `integer \| null` | | | | `delay_ms` | `number \| null` | | | | `reset` | `boolean \| null` | | | | `truncated` | `boolean \| null` | | | **Example** ```json { "turn_id": "t-1", "step_id": "s-1", "status": "completed", "will_retry": false } ``` ## item ### `item/started` Semantic item (message, tool call, custom record, or compaction) started. Oversized wire payloads are bounded at the outbound tap (`truncated: true` on truncated items/blocks; fetch full content via `session.get_item`). | Mode | Delivery | Ignorable | Retain | On error | |---|---|---|---|---| | `emit` | `required` | no | no | `continue` | | Field | Type | Required | Description | |---|---|---|---| | `turn_id` | `string \| null` | | | | `item_id` | `string` | yes | | | `step_id` | `string \| null` | | | | `item` | `Item` | yes | | **Example** ```json { "turn_id": "t-1", "item_id": "it-1", "item": { "type": "assistant_message" } } ``` ### `item/delta` Append-only incremental delta for an in-flight item. | Mode | Delivery | Ignorable | Retain | On error | |---|---|---|---|---| | `emit` | `required` | yes | no | `continue` | | Field | Type | Required | Description | |---|---|---|---| | `turn_id` | `string` | yes | | | `item_id` | `string` | yes | | | `kind` | `ItemDeltaKind` | yes | | | `delta` | `string` | yes | | | `offset` | `integer ≥ 0` | yes | | | `tool_call_id` | `string \| null` | | | | `partial` | `any` | | | | `event` | `any` | | | | `truncated` | `boolean \| null` | | | **Example** ```json { "turn_id": "t-1", "item_id": "it-1", "kind": "text", "delta": "hi", "offset": 0 } ``` ### `item/completed` Authoritative completed item. For `tool_call`, `item.message` is the sole carrier of `content`/`details`. Oversized wire payloads project images to `{ type: "image", mime, path?, bytes, truncated: true }`, truncate long strings with `truncated: true`, or fall back to `item_omitted: true`; fetch full content via `session.get_item`. | Mode | Delivery | Ignorable | Retain | On error | |---|---|---|---|---| | `emit` | `required` | no | no | `continue` | | Field | Type | Required | Description | |---|---|---|---| | `turn_id` | `string \| null` | | | | `item_id` | `string` | yes | | | `status` | `ItemStatus` | yes | | | `item` | `Item \| null` | | | | `item_omitted` | `boolean \| null` | | | **Example** ```json { "turn_id": "t-1", "item_id": "c-1", "status": "completed", "item": { "type": "tool_call", "tool_call_id": "c-1", "name": "read", "status": "completed", "message": { "role": "tool_result", "tool_call_id": "c-1", "tool_name": "read", "content": [], "is_error": false }, "result_status": "success", "execution_status": "unknown" } } ``` ## queue ### `queue/changed` Agent steer/follow-up queue snapshot changed. | Mode | Delivery | Ignorable | Retain | On error | |---|---|---|---|---| | `emit` | `lossy` | no | yes | `continue` | | Field | Type | Required | Description | |---|---|---|---| | `items` | `QueueItem[]` | yes | | | `action` | `string \| null` | | | | `truncated` | `boolean \| null` | | True when the outbound event tap truncated strings or projected images to stay within `EVENT_MAX_BYTES`. | **Example** ```json { "items": [ { "input_id": "q-1", "lane": "steer", "text": "stop" } ] } ``` ## host ### `host/notice` Informational or warning notice from the agent or host. | Mode | Delivery | Ignorable | Retain | On error | |---|---|---|---|---| | `emit` | `lossy` | yes | no | `continue` | | Field | Type | Required | Description | |---|---|---|---| | `level` | `string` | yes | | | `text` | `string` | yes | | | `truncated` | `boolean \| null` | | True when the outbound event tap truncated strings or projected images to stay within `EVENT_MAX_BYTES`. | **Example** ```json { "level": "info", "text": "ok" } ``` ## subagent ### `subagent/started` Subagent run started. | Mode | Delivery | Ignorable | Retain | On error | |---|---|---|---|---| | `emit` | `required` | no | no | `continue` | | Field | Type | Required | Description | |---|---|---|---| | `subagent_id` | `string` | yes | | | `agent_id` | `string \| null` | | | | `name` | `string \| null` | | | | `label` | `string \| null` | | | | `run_id` | `string \| null` | | | | `seq` | `integer \| null` | | | | `task` | `string \| null` | | | | `parent_session_id` | `string \| null` | | | | `parent_session_epoch` | `string \| null` | | | | `truncated` | `boolean \| null` | | True when the outbound event tap truncated strings or projected images to stay within `EVENT_MAX_BYTES`. | **Example** ```json { "subagent_id": "child-1", "parent_session_id": "parent-1" } ``` ### `subagent/progress` Latest coalesced progress snapshot for a subagent. | Mode | Delivery | Ignorable | Retain | On error | |---|---|---|---|---| | `emit` | `lossy` | yes | no | `continue` | | Field | Type | Required | Description | |---|---|---|---| | `subagent_id` | `string` | yes | | | `parent_session_id` | `string \| null` | | | | `parent_session_epoch` | `string \| null` | | | | `progress` | `object` | yes | | | `truncated` | `boolean \| null` | | True when the outbound event tap truncated strings or projected images to stay within `EVENT_MAX_BYTES`. | **Example** ```json { "subagent_id": "child-1", "parent_session_id": "parent-1", "progress": { "state": "working" } } ``` ### `subagent/completed` Subagent run completed. | Mode | Delivery | Ignorable | Retain | On error | |---|---|---|---|---| | `emit` | `required` | no | no | `continue` | | Field | Type | Required | Description | |---|---|---|---| | `subagent_id` | `string` | yes | | | `agent_id` | `string \| null` | | | | `name` | `string \| null` | | | | `label` | `string \| null` | | | | `status` | `string` | yes | | | `run_id` | `string \| null` | | | | `seq` | `integer \| null` | | | | `parent_session_id` | `string \| null` | | | | `parent_session_epoch` | `string \| null` | | | | `text` | `string \| null` | | | | `error` | `EventError \| null` | | | | `error_kind` | `string \| null` | | | | `usage` | `any` | | | | `truncated` | `boolean \| null` | | True when the outbound event tap truncated strings or projected images to stay within `EVENT_MAX_BYTES`. | **Example** ```json { "subagent_id": "child-1", "status": "completed", "parent_session_id": "parent-1" } ``` ## approval ### `approval/requested` Approval prompt opened or requested for an action. | Mode | Delivery | Ignorable | Retain | On error | |---|---|---|---|---| | `emit` | `required` | no | no | `continue` | | Field | Type | Required | Description | |---|---|---|---| | `approval_id` | `string` | yes | | | `category` | `string` | yes | | | `tool_call_id` | `string \| null` | | | | `snapshot` | `any` | | | | `child_approval_id` | `integer \| null` | | | | `truncated` | `boolean \| null` | | | **Example** ```json { "approval_id": "ap-1", "category": "tool", "tool_call_id": "c-1", "snapshot": "snap-1" } ``` ### `approval/resolved` Approval prompt resolved with its decision outcome. | Mode | Delivery | Ignorable | Retain | On error | |---|---|---|---|---| | `emit` | `required` | no | no | `continue` | | Field | Type | Required | Description | |---|---|---|---| | `approval_id` | `string` | yes | | | `category` | `string` | yes | | | `tool_call_id` | `string \| null` | | | | `result` | `ApprovalResult` | yes | | | `truncated` | `boolean \| null` | | | **Example** ```json { "approval_id": "ap-1", "category": "tool", "tool_call_id": "c-1", "result": { "call": { "tool_call_id": "c-1", "name": "write" }, "decision": "allow", "source": "user" } } ``` ### `approval/changed` Approval policy or revision changed. | Mode | Delivery | Ignorable | Retain | On error | |---|---|---|---|---| | `emit` | `lossy` | no | yes | `continue` | | Field | Type | Required | Description | |---|---|---|---| | `policy` | `any` | yes | | | `revision` | `integer` | yes | | **Example** ```json { "policy": "ask", "revision": 1 } ``` ### `approval/review-result` Automated approval reviewer outcome. | Mode | Delivery | Ignorable | Retain | On error | |---|---|---|---|---| | `emit` | `required` | no | no | `continue` | | Field | Type | Required | Description | |---|---|---|---| | `category` | `string` | yes | | | `result` | `object` | yes | | **Example** ```json { "category": "exec", "result": { "call": { "name": "exec", "tool_call_id": "c-1" }, "decision": "allow", "source": "reviewer" } } ``` ## status ### `status/changed` Unified agent status changed. | Mode | Delivery | Ignorable | Retain | On error | |---|---|---|---|---| | `emit` | `lossy` | no | yes | `continue` | | Field | Type | Required | Description | |---|---|---|---| | `state` | `string` | yes | | | `message` | `string` | yes | | | `session` | `object` | yes | | | `seq` | `integer ≥ 0` | yes | | | `truncated` | `boolean \| null` | | True when the outbound event tap truncated strings or projected images to stay within `EVENT_MAX_BYTES`. | **Example** ```json { "state": "idle", "message": "ready", "session": {}, "seq": 1 } ``` ## interaction ### `interaction/requested` Interactive prompt opened and waiting for a responder. | Mode | Delivery | Ignorable | Retain | On error | |---|---|---|---|---| | `emit` | `required` | no | no | `continue` | | Field | Type | Required | Description | |---|---|---|---| | `interaction_id` | `string` | yes | | | `kind` | `InteractionKind` | yes | | | `title` | `string \| null` | | | | `session_id` | `string \| null` | | | | `truncated` | `boolean \| null` | | True when the outbound event tap truncated strings or projected images to stay within `EVENT_MAX_BYTES`. | **Example** ```json { "interaction_id": "int-1", "kind": "select", "title": "Pick" } ``` ### `interaction/resolved` Interactive prompt finished with answered, cancelled, or unavailable. | Mode | Delivery | Ignorable | Retain | On error | |---|---|---|---|---| | `emit` | `required` | no | no | `continue` | | Field | Type | Required | Description | |---|---|---|---| | `interaction_id` | `string` | yes | | | `kind` | `InteractionKind` | yes | | | `outcome` | `InteractionOutcome` | yes | | | `title` | `string \| null` | | | | `session_id` | `string \| null` | | | | `truncated` | `boolean \| null` | | True when the outbound event tap truncated strings or projected images to stay within `EVENT_MAX_BYTES`. | **Example** ```json { "interaction_id": "int-1", "kind": "select", "outcome": "answered" } ``` ## compact ### `compact/completed` Context compaction completed (succeeded, cancelled, failed, or stalled). | Mode | Delivery | Ignorable | Retain | On error | |---|---|---|---|---| | `emit` | `required` | no | no | `continue` | | Field | Type | Required | Description | |---|---|---|---| | `cancelled` | `boolean \| null` | | | | `changed` | `boolean` | yes | | | `compact_id` | `string` | | | | `compactions` | `integer \| null` | | | | `error` | `{ code: string, data?: any, message: string }` | | | | `message` | `string \| null` | | | | `offloaded_count` | `integer \| null` | | | | `pruned_count` | `integer \| null` | | | | `reason` | `string` | yes | | | `stalled` | `boolean \| null` | | | | `status` | `"completed" \| "cancelled" \| "failed" \| "stalled"` | yes | | | `tokens_after` | `number` | yes | | | `tokens_before` | `number` | yes | | **Example** ```json { "changed": true, "compact_id": "c-1", "reason": "auto", "status": "completed", "tokens_after": 60, "tokens_before": 100 } ``` ### `compact/stage` Best-effort compaction pipeline stage diagnostic. | Mode | Delivery | Ignorable | Retain | On error | |---|---|---|---|---| | `emit` | `lossy` | yes | no | `continue` | | Field | Type | Required | Description | |---|---|---|---| | `changed` | `boolean` | | | | `phase` | `string` | yes | | | `reason` | `string` | | | | `stage` | `string` | yes | | | `tokens` | `number` | | | | `tokens_after` | `number` | | | | `tokens_before` | `number` | | | **Example** ```json { "phase": "before", "stage": "prune", "tokens": 100.0 } ``` ### `compact/started` Context compaction started. | Mode | Delivery | Ignorable | Retain | On error | |---|---|---|---|---| | `emit` | `required` | no | no | `continue` | | Field | Type | Required | Description | |---|---|---|---| | `compact_id` | `string` | | | | `messages` | `integer` | | | | `reason` | `string` | yes | | **Example** ```json { "compact_id": "c-1", "messages": 4, "reason": "manual" } ``` ## jobs ### `jobs/changed` Background job state changed. | Mode | Delivery | Ignorable | Retain | On error | |---|---|---|---|---| | `emit` | `lossy` | no | yes | `continue` | | Field | Type | Required | Description | |---|---|---|---| | `job` | `object` | yes | | | `truncated` | `boolean` | | | **Example** ```json { "job": { "job_id": "j-1", "kind": "bash", "owner": "bash", "started_at_ms": 1700000000000, "status": "running" } } ``` ## model ### `model/changed` Active model selection changed. | Mode | Delivery | Ignorable | Retain | On error | |---|---|---|---|---| | `emit` | `lossy` | no | yes | `continue` | | Field | Type | Required | Description | |---|---|---|---| | `model_id` | `string` | yes | | | `provider_id` | `string` | yes | | | `ref` | `string` | yes | | **Example** ```json { "model_id": "gpt-5", "provider_id": "openai", "ref": "openai/gpt-5" } ``` ## permission ### `permission/changed` Active permission preset or policy state changed. | Mode | Delivery | Ignorable | Retain | On error | |---|---|---|---|---| | `emit` | `lossy` | no | yes | `continue` | | Field | Type | Required | Description | |---|---|---|---| | `label` | `string` | | | | `partial` | `boolean` | | | | `preset` | `string` | | | **Example** ```json { "label": "DEFAULT", "preset": "default" } ``` ## session ### `session/changed` Active session created, resumed, or forked. | Mode | Delivery | Ignorable | Retain | On error | |---|---|---|---|---| | `emit` | `required` | no | yes | `continue` | | Field | Type | Required | Description | |---|---|---|---| | `path` | `string` | | | | `reason` | `"resume" \| "new" \| "fork"` | yes | | | `session_id` | `string` | yes | | **Example** ```json { "reason": "new", "session_id": "s-1" } ``` ## ui ### `ui/card` UI card emitted via ui.card (persistent cards are also written to session records). | Mode | Delivery | Ignorable | Retain | On error | |---|---|---|---|---| | `emit` | `required` | no | no | `continue` | | Field | Type | Required | Description | |---|---|---|---| | `after_entry_id` | `string` | | | | `block_id` | `integer` | | | | `card_id` | `string` | | | | `kind` | `string` | yes | | | `markdown` | `string` | yes | | | `meta` | `any` | | | | `persistent` | `boolean` | yes | | | `title` | `string` | yes | | **Example** ```json { "kind": "info", "markdown": "**hi**", "persistent": false, "title": "Note" } ``` ### `ui/keymap-changed` Runtime keymap bindings changed (set, delete, or detach cleanup). | Mode | Delivery | Ignorable | Retain | On error | |---|---|---|---|---| | `emit` | `lossy` | no | yes | `continue` | | Field | Type | Required | Description | |---|---|---|---| | `action` | `string \| boolean` | | | | `context` | `string` | | | | `key` | `string` | | | | `session_id` | `string` | | | **Example** ```json { "action": "transcript", "context": "editor", "key": "ctrl+t" } ``` ### `ui/print` Ephemeral UI print output outside the durable session log. | Mode | Delivery | Ignorable | Retain | On error | |---|---|---|---|---| | `emit` | `lossy` | yes | no | `continue` | | Field | Type | Required | Description | |---|---|---|---| | `lines` | `string[]` | | | | `text` | `string` | yes | | **Example** ```json { "lines": [ "hello" ], "text": "hello" } ``` ## usage ### `usage/changed` Session token usage and cost totals changed. | Mode | Delivery | Ignorable | Retain | On error | |---|---|---|---|---| | `emit` | `lossy` | no | yes | `continue` | | Field | Type | Required | Description | |---|---|---|---| | `cache_read` | `integer` | yes | | | `cache_write` | `integer` | yes | | | `cache_write_1h` | `integer` | | | | `cost` | `number` | yes | | | `cost_unknown` | `boolean` | | | | `input` | `integer` | yes | | | `last_cache_read` | `integer` | yes | | | `last_context` | `integer` | yes | | | `output` | `integer` | yes | | | `requests` | `integer` | yes | | | `side_requests` | `integer` | yes | | | `subscription_requests` | `integer` | yes | | **Example** ```json { "cache_read": 0.0, "cache_write": 0.0, "cost": 0.01, "input": 1.0, "last_cache_read": 0.0, "last_context": 10.0, "output": 2.0, "requests": 1.0, "side_requests": 0.0, "subscription_requests": 0.0 } ``` ## web ### `web/providers-changed` Registered web search or fetch providers changed. | Mode | Delivery | Ignorable | Retain | On error | |---|---|---|---|---| | `emit` | `lossy` | no | yes | `continue` | | Field | Type | Required | Description | |---|---|---|---| | `action` | `string` | | | | `kind` | `string` | yes | | | `provider_id` | `string` | | | **Example** ```json { "action": "added", "kind": "search", "provider_id": "brave" } ``` ================================================================================ Title: Exit codes Section: Reference URL: https://signalridge.github.io/mare/en/reference/exit-codes/ Markdown: https://signalridge.github.io/mare/raw/en/reference/exit-codes.md Source: docs/en/reference/exit-codes.md ================================================================================ # Exit codes The process exit codes of `mare` for headless runs, RPC and ACP servers, the interactive interface and subcommands, and the `reason` values of the final `settled` record. > This reference page is maintained by hand (not generated by `scripts/gen_docs.py`). ## Headless runs `mare -p` and `mare --json` finish with one of these codes. With `--json`, the same code and a matching `reason` appear in the last record (see [JSON event stream](https://signalridge.github.io/mare/en/integrate/json-stream/)). | Code | `settled.reason` | Meaning | |---|---|---| | 0 | `completed` | The turn finished without an error. | | 1 | `error` | A provider, tool or runtime error. Also a session that `-c` or `--resume` could not find, and SIGTERM or SIGHUP. | | 2 | `usage` | Bad arguments or configuration: an unknown flag, no prompt, an unreadable stdin, a failing `init.lua`, a config warning under `--strict-config`, or a trust problem. The run never started. | | 3 | `approval_unavailable` | An approval was answered with "deny and stop" (`abort`) and the turn was stopped. | | 4 | `max_turns` | `--max-turns` was reached. | | 4 | `timeout` | `--timeout` was reached. | | 5 | `save_failed` | Session persistence failed. Any final answer is still written to stdout, unsaved records are written to `<state>/quarantine/`, and a warning is printed to stderr. | | 130 | `interrupted` | SIGINT (Ctrl+C). | | 141 | none | Stdout was closed by the reader, for example `mare --json ... \| head`. The turn is stopped and no `settled` record is written. | Some notes on how these are chosen: - Code 3 is only for runs that stopped because an approval was answered `abort`. An approval nobody could answer is a denied call, not a stop: the model gets the denial, and if it works around it the turn completes with 0. Every denial is listed on stderr, whatever the exit code. - `--timeout` bounds the whole run, including delivering output. When it fires, mare cancels the turn, tries to write `turn.failed` and `settled` (with `timeout`) and exits 4. If the reader of stdout is blocked, the stream can end without them, so treat a missing `settled` as a failure. - The first SIGINT cancels the turn and finishes normally with 130. A second SIGINT exits at once with 130 and writes no `settled` record. - A usage error under `--json` still prints `session`, `turn.failed` and `settled` lines so a script reading the stream always gets an outcome. - `--timeout` is refused with 2 outside headless runs (`-p` and `--json`). ```sh mare -p --timeout 5m --max-turns 30 "Fix the failing tests" case $? in 0) echo done ;; 3) echo "stopped by an approval abort: rerun with a permission preset that allows it" ;; 4) echo "ran out of turns or time" ;; *) echo "failed" ;; esac ``` ## Servers and the interface | Mode | Code | When | |---|---|---| | `mare --rpc` | 0 | Stdin closed, `shutdown` received, or SIGTERM or SIGINT. | | `mare --rpc` | 2 | Config warnings under `--strict-config`, a broken `init.lua`, or a trust problem at startup. mare writes the message to stderr. | | `mare acp` | 0 | The editor closed the connection. | | Interactive | 0 | Normal quit, or SIGTERM during startup. | | Interactive | 130 | SIGINT before the interface took over. | | Interactive | 2 | You chose to quit from the startup dialog for a failing config file. | ## Subcommands | Command | Codes | |---|---| | `mare doctor` | 0 when every check passes, 1 when any check fails. `--json` uses the same codes. | | `mare session ...` | `new`, `list`, `fork`, `archive`, `unarchive`, `delete`: 0 on success (`new` and `fork` print the id); 1 when `new` creates no session, `delete` is cancelled, or an operation fails; 2 for invalid `--limit`, an unresolved or ambiguous session selector, or `delete` without `--yes` on non-TTY stdin. | | `mare test` | 0 when all tests pass, 1 when one or more test cases fail, 2 on usage, spec discovery, host startup, or spec load/syntax errors. | | `mare token rotate` | 0 on success, 1 on failure. | | `mare web url` | 0 on success (prints the `?token=` login URL), 1 when no listener is running or token lookup fails. | | `mare login`, `mare logout`, `mare model refresh` | 0 on success, 1 on failure, 2 when the host could not start or `--with-api-key` has no key on stdin. | | `mare mcp ...` | 0, or 1 when the action reports a config error or a failure. | | `mare peer send` | 0 once the receiving session accepted the message (it prints `held`, `delivered` or `handled`). 1 for a missing target, a refused message or no answer within 30 seconds. | | `mare sandbox status` | 0. With `--require-full`, 1 unless all sandbox isolation capabilities are fully enforced (currently exits 1 on Windows even when the enhanced self-test passes because per-call network isolation is not enforced). | | `mare sandbox setup` | 0 on success, 1 on failure. 2 on platforms other than Windows. | | `mare trust`, `mare init`, `mare runtime`, `mare plugin ...`, `mare completion`, `mare rpc schema` | 0 on success. Any error is reported on stderr with exit code 1. | Argument errors from the command-line parser itself, such as an unknown subcommand, exit with 2. A crash that ends the process writes a report under `<state>/crashes/` and exits non-zero (see [Files](https://signalridge.github.io/mare/en/reference/files/)). ================================================================================ Title: Files and directories Section: Reference URL: https://signalridge.github.io/mare/en/reference/files/ Markdown: https://signalridge.github.io/mare/raw/en/reference/files.md Source: docs/en/reference/files.md ================================================================================ # Files and directories Every file and directory mare reads or writes: the four user directories, what is inside each, and the files a project can carry. Paths use `~` for the home directory; on Windows read it as `%USERPROFILE%`. > This reference page is maintained by hand (not generated by `scripts/gen_docs.py`). ## Locations mare uses XDG-style directories on every platform. macOS and Windows do not get `Library` or `AppData` locations. | Directory | Default | Override | |---|---|---| | Config | `~/.config/mare` | `$XDG_CONFIG_HOME/mare` | | State | `~/.local/state/mare` | `$XDG_STATE_HOME/mare` | | Data | `~/.local/share/mare` | `$XDG_DATA_HOME/mare` | | Cache | `~/.cache/mare` | `$XDG_CACHE_HOME/mare` | `MARE_HOME` beats all of those: the four directories become `$MARE_HOME/config`, `state`, `data` and `cache`. See [Environment variables](https://signalridge.github.io/mare/en/reference/environment/). Lua code gets the same paths as `mare.paths.config`, `mare.paths.state`, `mare.paths.data`, `mare.paths.auth`, `mare.paths.sessions` and `mare.paths.packages`. `mare doctor` checks that these directories exist and are writable, and on Unix that `auth.json` is mode 0600 and the sessions and state directories are mode 0700. ## Config directory Files you write and edit. | Path | Purpose | |---|---| | `init.lua` | Your configuration. `mare init` creates it and never overwrites it. See [Options](https://signalridge.github.io/mare/en/configure/options/). | | `.luarc.json` | Lua language server settings pointing at mare's type files. `mare init` writes it, and rewrites it only while it still matches what mare last wrote. | | `lua/` | Lua modules you `require` from `init.lua`. | | `plugins/` | User plugins. See [Plugins](https://signalridge.github.io/mare/en/extend/plugins/). | | `skills/` | User skills, one directory per skill with a `SKILL.md`. | | `prompts/` | Prompt templates that become slash commands. | | `themes/` | Themes. | | `AGENTS.md` | Your own instructions, loaded into every session. Per directory mare loads the first of `AGENTS.override.md`, `AGENTS.md`, `CLAUDE.md` that exists. | | `SYSTEM.md` | Replaces the default system prompt. | | `APPEND_SYSTEM.md` | Text appended to the system prompt. | | `mcp.json` | MCP servers. See [MCP](https://signalridge.github.io/mare/en/use/mcp/). | | `auth.json` | Credentials stored by `mare login`, mode 0600. Next to it: `auth.json.lock` while a login or refresh runs and `auth.json.bak` after a repair. | | `mare-lock.json` | Package lockfile: the exact revision of every installed package. See [Packages](https://signalridge.github.io/mare/en/configure/packages/). | | `plugins.json` | The optional package extras you enabled. | ## State directory Runtime state written by mare. Rebuildable session indexes are marked below. Keep unrecovered `quarantine/` records and active session lock, commit, and rollback files (the store reads recovery records when reopening a session). | Path | Purpose | |---|---| | `state.json` | Runtime choices such as the model picked with `/model`, used as defaults on the next start. Explicit `init.lua` values win. `state.json.lock` guards writes. | | `trust.json` | Project trust decisions, written by `mare trust` and the trust prompt. | | `sessions/` | Saved sessions. See below. | | `log/mare.log` | The log. Rotates at 10 MiB and keeps five old files, `mare.log.1` to `mare.log.5`. Set the level with `MARE_LOG`. | | `crashes/<timestamp>/report.txt` | A redacted crash report, written when a panic ends mare. | | `history.jsonl` | Prompt history for the editor. | | `lua-history` | History of the Lua console. | | `permissions.json` | Permission rules you saved from approval prompts. `permissions.json.lock` guards writes. | | `news.json` | Package news state. | | `models-cache/<provider>.json` | Model lists fetched by `mare model refresh`. | | `skills-cache/*.json` | Cached skill discovery metadata. | | `domains/ns-*.json` | Named domain state files. | | `snapshots/run-<pid>-<uuid>/` | File snapshots for runs without a session file (per-session snapshots live beside `<name>.jsonl` in `<name>.jsonl.snapshots/`). | | `attachments/<session-id or unsaved>/` | Fallback directory for images offloaded during compaction when no session file exists (per-session attachments live in `<name>.attachments/`). | | `spill/<prefix>-*.log` | The full output of long commands, named by their writer: `bash-*.log` for shell commands, `hooks-*.log` for hook commands. | | `spill-results/` | Recoverable tool output, private to the owning session (see the `spill.*` methods in [RPC](https://signalridge.github.io/mare/en/integrate/rpc/)). | | `host/token`, `host/.token.lock` | Bearer token for the local HTTP/WS web listener (`mare --web`, rotated with `mare token rotate`), mode 0600, and its lock file. | | `web/<pid>-<id>.json` | Running host web listener endpoint metadata read by `mare web url` (stored outside `host/`, removed on shutdown; stale entries are pruned), mode 0600. | | `quarantine/` | Unsaved session JSONL records quarantined when normal session persistence fails. | | `mcp.log` | Output of MCP servers. | | `mcp-approvals.json` | Saved project and `$MARE_MCP_CONFIG` MCP server approvals (keyed by server name and config hash). | | `mcp-disabled.json` | Per-project disabled MCP servers. | | `mcp-tools/` | Cached tool schemas for MCP servers. | | `mcp-output/` | The full form of truncated MCP results. | | `mcp-oauth/<server>-<hash>.json` | OAuth tokens for MCP servers. | | `peers/<pid>.json`, `peers/<pid>.sock` | The session registry and peer sockets of running sessions. Removed on exit; stale entries are pruned. See [RPC](https://signalridge.github.io/mare/en/integrate/rpc/). | | `pgroups/` | Registry of process groups started by mare, used to clean up after a crash. | | `crash-guard.json` | Requests that crashed mare, so a resumed session does not resend one forever. `crash-guard.lock` guards it. | | `kitty/` | Markers that keep terminal keyboard-mode state consistent after a crash. Unix only. | | `key-conflicts` | The last key-conflict warning shown, so it is not repeated. | | `luarc.generated` | The last `.luarc.json` mare wrote. | | `terminal-hint-shown` | Windows only: set after the one-time terminal hint. | ### Sessions Sessions live under `sessions/<project>/`, where `<project>` is the working directory with every character other than letters, digits, `.` and `_` replaced by `-`, wrapped in `--`. For `/home/me/app` that is `--home-me-app--`. | Path | Purpose | |---|---| | `<time>_<id8>.jsonl` | One session, an append-only log of entries. This is the source of truth. The name is the start time (`2026-11-14T09-30-00`) and the last eight characters of the id. | | `<time>_<id8>.jsonl.lock` | The single writer's lock. Next to it, `.lock.rollback` and `.lock.commit` files hold crash-recovery data. | | `<time>_<id8>.jsonl.v<N>` | Backups made before a session file is rewritten. | | `<time>_<id8>.attachments/` | Images stored with the session. | | `<time>_<id8>.jsonl.snapshots/` | The file snapshot journal for the session. | | `agents/<run>/<seq>-<label>.jsonl` | Sub-agent sessions, linked to their parent. | | `index.sqlite` (in `sessions/`) | Rebuildable SQLite index for `/resume`, `-c` and id lookups. Stores session metadata and single-line user input summaries (`preview` for the first qualifying user message and `last_input` for the latest); full messages live in the JSONL files. Delete it and mare rebuilds it from the session files. | ## Data directory Files mare installs for itself. | Path | Purpose | |---|---| | `runtime/` | Read-only copies of the built-in plugins and Lua type files. `mare runtime` prints the path. Rewritten when the mare version changes. | | `packages/` | Installed packages, one directory per source. See [Packages](https://signalridge.github.io/mare/en/configure/packages/). | | `package-types/` | Type files mirrored from installed packages for the language server. | ## Cache directory | Path | Purpose | |---|---| | `luac/` | Compiled Lua bytecode. Safe to delete. | ## Project files These live in the project, relative to the working directory. | Path | Purpose | |---|---| | `.mare/init.lua` | Project configuration, applied after your `init.lua`. | | `.mare/plugins/` | Project plugins. | | `.mare/plugins.json`, `.mare/mare-lock.json` | Project-scoped optional plugin selections and package lockfile. | | `.mare/lua/` | Lua modules for the project's `init.lua`. | | `.mare/skills/`, `.agents/skills/` | Project skills, resolved once against the project resource root (`mare.project.root`; startup trust probing also checks ancestor directories up to `.git` for `.agents/skills`). | | `.mare/prompts/` | Project prompt templates. | | `.mare/SYSTEM.md`, `.mare/APPEND_SYSTEM.md` | Project system prompt files. They take precedence over the ones in your config directory. | | `.mare/mcp.json`, `.mcp.json` | Project MCP servers. | | `AGENTS.md` | Project instructions, read from the working directory and its parents up to the directory that contains `.git`. Per directory the first of `AGENTS.override.md`, `AGENTS.md`, `CLAUDE.md` is used. | Everything under `.mare/` that can run code or change the prompt (`init.lua`, `plugins`, `plugins.json`, `skills`, `prompts`, `SYSTEM.md`, `APPEND_SYSTEM.md`) and `.agents/skills` load only in a trusted project. A bare `.mare/` directory needs no decision. See [Permissions](https://signalridge.github.io/mare/en/use/permissions/). ## Platform notes | Platform | Difference | |---|---| | Linux, macOS | Peer sockets are Unix sockets at `<state>/peers/<pid>.sock`, mode 0600 in a 0700 directory. Private files get mode 0600. | | Windows | The same directory layout under `%USERPROFILE%`. A peer socket is a named pipe with a random name; its path holds an endpoint file that names the pipe. Private files get a restricted ACL instead of mode bits. The enhanced sandbox keeps its setup in `%ProgramData%\mare\sandbox` (or `MARE_SANDBOX_DIR`). | ================================================================================ Title: RPC reference Section: Reference URL: https://signalridge.github.io/mare/en/reference/rpc/ Markdown: https://signalridge.github.io/mare/raw/en/reference/rpc.md Source: docs/en/reference/rpc.md ================================================================================ # RPC reference Every method, notification and callback of `mare --rpc`, taken from `mare rpc schema`. Field names use `snake_case` across the protocol. How a session runs over RPC, with examples, is in [JSON-RPC](https://signalridge.github.io/mare/en/integrate/rpc/). > This page is generated from the code by `scripts/gen_docs.py`. Do not edit it by hand. Protocol version: **3.0** ## Methods (client → mare) ### agent #### `agent.cancel` | Field | Type | Required | Description | |---|---|---|---| | `clear_queue` | `boolean` | | | | `mode` | `"cancel" \| "halt"` | | | | `reason` | `string` | | Cancellation cause (`user`, `parent`, `hook`, `disposed`) or free-form note (classified as `user`). | | `request_id` | `string` | | | | `turn_id` | `string` | | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `duplicate` | `boolean` | | | | `removed` | `{ content?: object[], images: { data?: string, mime: string, path?: string, size?: integer }[], input_context?: any, input_id: string, lane: "steer" \| "follow_up", text: string }[]` | yes | | | `turn_id` | `string` | | | #### `agent.continue` | Field | Type | Required | Description | |---|---|---|---| | `effort` | `string` | | | | `tools` | `string \| object[]` | | | | `output_schema` | `object` | | | | `source` | `string` | | | | `system` | `string` | | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `turn_id` | `string` | yes | | #### `agent.delete_queued` | Field | Type | Required | Description | |---|---|---|---| | `input_id` | `string` | yes | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: `object` #### `agent.get` | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `activity` | `{ extra: object, extra_errors: object }` | | | | `busy` | `boolean` | yes | | | `effort` | `string` | | | | `interrupted` | `boolean` | | | | `message_count` | `integer` | | | | `model` | `string` | | | | `queued` | `integer` | yes | | | `session_id` | `string` | | | | `turn_cancelled` | `boolean` | | | | `turn_id` | `string` | | | #### `agent.list_messages` | Field | Type | Required | Description | |---|---|---|---| | `cursor` | `string` | | | | `limit` | `integer` | | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `data` | `object[]` | yes | | | `next_cursor` | `string` | | | #### `agent.list_queue` | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `data` | `{ content?: object[], images: { data?: string, mime: string, path?: string, size?: integer }[], input_context?: any, input_id: string, lane: "steer" \| "follow_up", text: string }[]` | yes | | #### `agent.prompt` | Field | Type | Required | Description | |---|---|---|---| | `effort` | `string` | | | | `when_busy` | `"queue" \| "reject"` | | | | `input` | `string \| object[]` | yes | | | `output_schema` | `object` | | | | `request_id` | `string` | | | | `source` | `string` | | | | `system` | `string` | | | | `tools` | `string \| object[]` | | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `duplicate` | `boolean` | | | | `input_id` | `string` | | | | `status` | `"started" \| "queued"` | yes | | | `turn_id` | `string` | | | #### `agent.steer` | Field | Type | Required | Description | |---|---|---|---| | `expected_turn_id` | `string` | | | | `input` | `string \| object[]` | yes | | | `request_id` | `string` | | | | `source` | `string` | | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `duplicate` | `boolean` | | | | `input_id` | `string` | yes | | #### `agent.update_queued` | Field | Type | Required | Description | |---|---|---|---| | `input` | `string \| object[]` | | | | `input_id` | `string` | yes | | | `lane` | `"steer" \| "follow_up"` | | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `content` | `object[]` | | Optional ordered content blocks with image bytes stripped (preserved on cancel). | | `images` | `{ data?: string, mime: string, path?: string, size?: integer }[]` | yes | Queued image attachments. | | `input_context` | `any` | | Opaque caller-supplied JSON metadata preserved with the queued input. | | `input_id` | `string` | yes | Stable queued input id. | | `lane` | `"steer" \| "follow_up"` | yes | Delivery lane (`steer` or `follow_up`). | | `text` | `string` | yes | Queued input text. | #### `agent.wait` | Field | Type | Required | Description | |---|---|---|---| | `timeout_ms` | `integer` | | | | `turn_id` | `string` | | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `cancellation_cause` | `"user" \| "parent" \| "hook" \| "disposed"` | | Origin of cancellation when `termination_reason` is `interrupted`. | | `completed_at_ms` | `integer` | | Unix epoch milliseconds when the turn finished. | | `error` | `{ code: string, data?: any, message: string }` | | | | `error_kind` | `string` | | Classified failure kind when present. | | `messages` | `object[]` | | Session messages visible at turn end. | | `not_sent` | `boolean` | | True when the prompt failed before reaching the provider. | | `save_warning` | `string` | | Quarantine/save failure warning when another error took precedence. | | `started_at_ms` | `integer` | yes | Unix epoch milliseconds when the turn started. | | `status` | `"completed" \| "cancelled" \| "failed" \| "running"` | yes | Turn completion outcome (or `running` when `wait` timed out). | | `structured` | `any` | | Validated structured output when `output_schema` was supplied. | | `termination_reason` | `"completed" \| "usage_limit" \| "interrupted" \| "aborted" \| "turn_limit" \| "error"` | | Machine-readable turn termination outcome. | | `text` | `string` | | Final assistant text produced during the turn. | | `timed_out` | `boolean` | | True when `agent.wait` returned on `timeout_ms` before settlement. | | `turn_id` | `string` | yes | Turn identifier. | | `usage` | `object` | | Aggregated token/cost usage for the turn. | ### baseline #### `baseline.read` Parameters for `baseline.read`. | Field | Type | Required | Description | |---|---|---|---| | `baseline_id` | `string` | yes | | | `part` | `string` | yes | | | `cursor` | `string \| null` | | | | `limit` | `integer \| null` | | Optional maximum number of items to return in one page (>= 1). | Result: `BaselineReadResult` | Field | Type | Required | Description | |---|---|---|---| | `data` | `any[]` | yes | | | `next_cursor` | `string \| null` | | | Errors: `baseline.stale`, `baseline.unknown_part`, `baseline.item_too_large` ### cells #### `cells.cancel` | Field | Type | Required | Description | |---|---|---|---| | `cell_id` | `string` | yes | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: `object` #### `cells.get` | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `retains_state` | `boolean` | yes | | | `running` | `integer` | yes | | | `store_durable` | `boolean` | yes | | | `stored_keys` | `integer` | yes | | #### `cells.list` | Field | Type | Required | Description | |---|---|---|---| | `cursor` | `string` | | | | `limit` | `integer` | | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `data` | `{ cell_id: string, status: "running" \| "completed" \| "failed" \| "cancelled" }[]` | yes | | | `next_cursor` | `string` | | | #### `cells.list_tools` | Field | Type | Required | Description | |---|---|---|---| | `cursor` | `string` | | | | `limit` | `integer` | | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `data` | `{ declaration: string, description: string, name: string, output_schema: object, parameters: object }[]` | yes | | | `next_cursor` | `string` | | | #### `cells.reset` | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: `object` #### `cells.start` | Field | Type | Required | Description | |---|---|---|---| | `capabilities` | `string[]` | | | | `cell_id` | `string` | | | | `code` | `string` | yes | | | `max_output_tokens` | `integer` | | | | `state_owner` | `string` | | | | `timeout_ms` | `integer \| false` | | | | `yield_time_ms` | `integer` | | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: `mare.CellResult` | Field | Type | Required | Description | |---|---|---|---| | `cell_id` | `string` | yes | | | `content` | `any[]` | yes | | | `error` | `string` | | | | `result` | `any` | | | | `status` | `"running" \| "completed" \| "failed" \| "cancelled"` | yes | | | `stop_unconfirmed` | `boolean` | | | #### `cells.wait` | Field | Type | Required | Description | |---|---|---|---| | `cell_id` | `string` | yes | | | `max_output_tokens` | `integer` | | | | `terminate` | `boolean` | | | | `yield_time_ms` | `integer` | | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: `mare.CellResult` | Field | Type | Required | Description | |---|---|---|---| | `cell_id` | `string` | yes | | | `content` | `any[]` | yes | | | `error` | `string` | | | | `result` | `any` | | | | `status` | `"running" \| "completed" \| "failed" \| "cancelled"` | yes | | | `stop_unconfirmed` | `boolean` | | | ### commands #### `commands.get` | Field | Type | Required | Description | |---|---|---|---| | `name` | `string` | yes | | Result: | Field | Type | Required | Description | |---|---|---|---| | `alias_of` | `string` | | | | `args` | `string` | | | | `auto_execute` | `boolean` | | | | `availability` | `"always" \| "idle" \| "session" \| "main" \| "running" \| "tui" \| "always" \| "idle" \| "session" \| "main" \| "running" \| "tui"[]` | | | | `description` | `string` | | | | `local_only` | `boolean` | | | | `name` | `string` | yes | | #### `commands.list` No parameters. Result: | Field | Type | Required | Description | |---|---|---|---| | `data` | `object[]` | yes | | #### `commands.register` | Field | Type | Required | Description | |---|---|---|---| | `alias_of` | `string` | | | | `args` | `string` | | | | `auto_execute` | `boolean` | | | | `availability` | `"always" \| "idle" \| "session" \| "main" \| "running" \| "tui" \| "always" \| "idle" \| "session" \| "main" \| "running" \| "tui"[]` | | | | `description` | `string` | | | | `local_only` | `boolean` | | | | `name` | `string` | yes | | | `replace` | `boolean` | | | | `callbacks` | `"complete" \| "run"[]` | | | | `scope` | `"all" \| "session"` | | | | `session_id` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `registration_id` | `string` | yes | | #### `commands.run` | Field | Type | Required | Description | |---|---|---|---| | `input` | `{ content?: object[] }` | | | | `line` | `string` | yes | | | `session_id` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `result` | `any` | | | ### compact #### `compact.run` | Field | Type | Required | Description | |---|---|---|---| | `instructions` | `string` | | | | `messages` | `object[]` | | | | `reason` | `"manual"` | | | | `summarize_only` | `boolean` | | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `dropped` | `integer` | | | | `status` | `"compacted" \| "nothing_to_compact" \| "unchanged" \| "summarized"` | yes | | | `summary` | `string` | | | | `tokens_after` | `integer` | yes | | | `tokens_before` | `integer` | yes | | ### config #### `config.describe` Return redacted config metadata, provenance, and redacted warnings. | Field | Type | Required | Description | |---|---|---|---| | `keys` | `string[] \| null` | | option names or dotted paths (default: all) | Result: `ConfigDescribeResult` | Field | Type | Required | Description | |---|---|---|---| | `options` | `map<string, OptionDescriptor>` | yes | | | `warnings` | `string[]` | | | ### connection #### `connection.set_capabilities` | Field | Type | Required | Description | |---|---|---|---| | `capabilities` | `StrictClientCapabilities` | yes | | Result: `SetCapabilitiesResult` | Field | Type | Required | Description | |---|---|---|---| | `capabilities` | `ClientCapabilities` | yes | | ### events #### `events.list` No parameters. Result: `EventsListResult` | Field | Type | Required | Description | |---|---|---|---| | `data` | `EventInfo[]` | yes | | #### `events.subscribe` `events.subscribe`: subscribe to (or filter) a session's event stream. | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string \| null` | | session id to subscribe to (required unless `scope = "all"` is explicitly set by the owner) | | `session_epoch` | `string \| null` | | last observed `session_epoch`; mismatches fall back to `mode = "baseline"` | | `last_seq` | `integer \| null` | | last delivered `seq` within `session_epoch` for resumptive replay | | `scope` | `RegistrationScopeKind \| null` | | | | `include` | `string[] \| null` | | | | `exclude` | `string[] \| null` | | | Result: `EventsSubscribeResult` | Field | Type | Required | Description | |---|---|---|---| | `mode` | `SubscribeMode` | yes | | | `session_epoch` | `string` | yes | | | `seq` | `integer ≥ 0` | yes | sequence number at which the stream continues (`next_seq` for `live`/`baseline`, `last_seq + 1` for `replay`) | ### flags #### `flags.get` `flags.get` params. | Field | Type | Required | Description | |---|---|---|---| | `name` | `string` | yes | | Result: `FlagsGetResult` | Field | Type | Required | Description | |---|---|---|---| | `name` | `string` | yes | | | `registered` | `boolean` | yes | | | `value` | `any` | | | #### `flags.list` No parameters. Result: `FlagsListResult` | Field | Type | Required | Description | |---|---|---|---| | `data` | `FlagEntry[]` | yes | | ### fs #### `fs.list` | Field | Type | Required | Description | |---|---|---|---| | `path` | `string` | yes | | Result: | Field | Type | Required | Description | |---|---|---|---| | `data` | `{ file_name: string, is_directory: boolean, is_file: boolean }[]` | yes | | #### `fs.read` | Field | Type | Required | Description | |---|---|---|---| | `max_bytes` | `integer` | | | | `path` | `string` | yes | | Result: | Field | Type | Required | Description | |---|---|---|---| | `data_base64` | `string` | yes | | #### `fs.stat` | Field | Type | Required | Description | |---|---|---|---| | `path` | `string` | yes | | Result: | Field | Type | Required | Description | |---|---|---|---| | `created_at_ms` | `integer` | yes | | | `is_directory` | `boolean` | yes | | | `is_file` | `boolean` | yes | | | `mode` | `integer` | | | | `modified_at_ms` | `integer` | yes | | | `nlink` | `integer` | | | | `size` | `integer` | yes | | #### `fs.watch` | Field | Type | Required | Description | |---|---|---|---| | `path` | `string` | yes | | Result: | Field | Type | Required | Description | |---|---|---|---| | `registration_id` | `string` | yes | | #### `fs.write` | Field | Type | Required | Description | |---|---|---|---| | `atomic` | `boolean` | | | | `create_new` | `boolean` | | | | `data_base64` | `string` | yes | | | `path` | `string` | yes | | Result: `object` ### hooks #### `hooks.subscribe` | Field | Type | Required | Description | |---|---|---|---| | `event` | `string` | yes | | | `prepend` | `boolean` | | | | `timeout_ms` | `integer` | | | | `callbacks` | `"handle"[]` | yes | | | `scope` | `"all" \| "session"` | | | | `session_id` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `registration_id` | `string` | yes | | ### `initialize` | Field | Type | Required | Description | |---|---|---|---| | `protocol_version` | `string` | yes | Protocol version the host speaks (`major.minor`); the major version must match. | | `client` | `ClientInfo \| null` | | | | `capabilities` | `ClientCapabilities` | | Callbacks the host can answer. Undeclared callbacks are never sent (defaults apply). (default `{"callbacks": false, "ui": false, "approvals": false, "elicitation": false}`) | | `callback_timeout_ms` | `integer \| null` | | Timeout for callbacks into the host in milliseconds (default 30000, clamped to 1..=3600000). | | `approval_timeout_ms` | `integer \| null` | | Optional human approval timeout in milliseconds; absent means wait without a deadline. | Result: `InitializeResult` | Field | Type | Required | Description | |---|---|---|---| | `protocol_version` | `string` | yes | | | `server` | `ServerInfo` | yes | | | `capabilities` | `ServerCapabilities` | yes | | | `session` | `any` | | Live `mare.Session` snapshot of the opened initial session, if any (`session_id` and `session_epoch` live on this object; session-scoped contract methods take `session_id`). | ### jobs #### `jobs.background` | Field | Type | Required | Description | |---|---|---|---| | `job_id` | `string` | yes | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: `object` #### `jobs.cancel` | Field | Type | Required | Description | |---|---|---|---| | `job_id` | `string` | yes | | | `reason` | `string` | | | | `silent` | `boolean` | | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: `object` #### `jobs.list` | Field | Type | Required | Description | |---|---|---|---| | `cursor` | `string` | | | | `limit` | `integer` | | | | `owner` | `string` | | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `data` | `object[]` | yes | | | `next_cursor` | `string` | | | #### `jobs.read` | Field | Type | Required | Description | |---|---|---|---| | `job_id` | `string` | yes | | | `max_bytes` | `integer` | | | | `offset` | `integer` | | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `done` | `boolean` | | | | `dropped` | `integer` | | | | `next_offset` | `integer` | | | | `text` | `string` | yes | | ### llm #### `llm.get_model` | Field | Type | Required | Description | |---|---|---|---| | `ref` | `string` | | describe this model instead (hidden or unlisted ones too); the selection is unchanged | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `available` | `boolean` | yes | | | `context_window` | `integer` | | | | `cost` | `{ cache_read?: number, cache_write?: number, input?: number, output?: number }` | | | | `default_effort` | `string` | | | | `edit_tool` | `"apply_patch" \| "replace"` | | | | `efforts` | `string[]` | yes | | | `images` | `boolean` | yes | | | `max_output` | `integer` | | | | `model_id` | `string` | yes | | | `name` | `string` | | | | `parameters` | `object[]` | yes | | | `provider` | `string` | yes | | | `ready` | `boolean` | yes | | | `ready_reason` | `string` | | | | `reasoning` | `boolean` | yes | | | `ref` | `string` | yes | | | `route` | `string` | | | | `route_error` | `string` | | | | `tool_update` | `"addition_only"` | | | | `unavailable_reason` | `string` | | | | `wire_route` | `string` | | | #### `llm.list_auth_keys` | Field | Type | Required | Description | |---|---|---|---| | `prefix` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `data` | `string[]` | yes | | #### `llm.list_models` No parameters. Result: | Field | Type | Required | Description | |---|---|---|---| | `data` | `object[]` | yes | | #### `llm.list_providers` No parameters. Result: | Field | Type | Required | Description | |---|---|---|---| | `data` | `object[]` | yes | | #### `llm.login` | Field | Type | Required | Description | |---|---|---|---| | `key` | `string` | | | | `method` | `"oauth" \| "device" \| "api_key" \| "auto"` | | | | `provider` | `string` | yes | | Result: `object` #### `llm.logout` | Field | Type | Required | Description | |---|---|---|---| | `provider` | `string` | yes | | Result: | Field | Type | Required | Description | |---|---|---|---| | `kept` | `string[]` | yes | | | `removed` | `string[]` | yes | | | `warnings` | `string[]` | yes | | #### `llm.register_provider` | Field | Type | Required | Description | |---|---|---|---| | `default_model` | `string` | | | | `models` | `object[]` | | | | `provider` | `string` | yes | | | `replace` | `boolean` | | | | `callbacks` | `"stream"[]` | | | | `scope` | `"all" \| "session"` | | | | `session_id` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `registration_id` | `string` | yes | | #### `llm.set_effort` | Field | Type | Required | Description | |---|---|---|---| | `also_global` | `boolean` | | | | `effort` | `string` | yes | | | `save` | `boolean` | | | | `scope_name` | `string` | | | | `target` | `"session" \| "global"` | | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: `object` #### `llm.set_model` | Field | Type | Required | Description | |---|---|---|---| | `ref` | `string` | yes | | | `save` | `boolean` | | | | `target` | `"session" \| "global"` | | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `available` | `boolean` | yes | | | `context_window` | `integer` | | | | `cost` | `{ cache_read?: number, cache_write?: number, input?: number, output?: number }` | | | | `default_effort` | `string` | | | | `edit_tool` | `"apply_patch" \| "replace"` | | | | `efforts` | `string[]` | yes | | | `images` | `boolean` | yes | | | `max_output` | `integer` | | | | `model_id` | `string` | yes | | | `name` | `string` | | | | `parameters` | `object[]` | yes | | | `provider` | `string` | yes | | | `ready` | `boolean` | yes | | | `ready_reason` | `string` | | | | `reasoning` | `boolean` | yes | | | `ref` | `string` | yes | | | `route` | `string` | | | | `route_error` | `string` | | | | `tool_update` | `"addition_only"` | | | | `unavailable_reason` | `string` | | | | `wire_route` | `string` | | | ### mcp #### `mcp.connect` | Field | Type | Required | Description | |---|---|---|---| | `server` | `string` | yes | | Result: `mare.McpServerStatus` | Field | Type | Required | Description | |---|---|---|---| | `error` | `string` | | | | `missing` | `string[]` | | | | `name` | `string` | yes | | | `source` | `string` | | | | `state` | `string` | yes | | | `target` | `string` | | | | `tier` | `string` | | | | `tools` | `integer` | yes | | | `transport` | `string` | | | #### `mcp.get_prompt` | Field | Type | Required | Description | |---|---|---|---| | `arguments` | `map<string, string>` | | | | `name` | `string` | yes | | | `server` | `string` | yes | | Result: | Field | Type | Required | Description | |---|---|---|---| | `description` | `string` | | | | `messages` | `object[]` | yes | | #### `mcp.list_prompts` | Field | Type | Required | Description | |---|---|---|---| | `connect` | `boolean` | | | | `server` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `data` | `object[]` | yes | | #### `mcp.list_resources` | Field | Type | Required | Description | |---|---|---|---| | `connect` | `boolean` | | | | `server` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `data` | `object[]` | yes | | | `resource_templates` | `object[]` | yes | | #### `mcp.list_servers` No parameters. Result: | Field | Type | Required | Description | |---|---|---|---| | `data` | `mare.McpServerStatus[]` | yes | | | `errors` | `string[]` | yes | | #### `mcp.list_tools` | Field | Type | Required | Description | |---|---|---|---| | `connect` | `boolean` | | | | `server` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `data` | `object[]` | yes | | #### `mcp.read_resource` | Field | Type | Required | Description | |---|---|---|---| | `server` | `string` | yes | | | `uri` | `string` | yes | | Result: | Field | Type | Required | Description | |---|---|---|---| | `contents` | `object[]` | yes | | #### `mcp.reconnect` | Field | Type | Required | Description | |---|---|---|---| | `server` | `string` | yes | | Result: `mare.McpServerStatus` | Field | Type | Required | Description | |---|---|---|---| | `error` | `string` | | | | `missing` | `string[]` | | | | `name` | `string` | yes | | | `source` | `string` | | | | `state` | `string` | yes | | | `target` | `string` | | | | `tier` | `string` | | | | `tools` | `integer` | yes | | | `transport` | `string` | | | ### message #### `message.append` | Field | Type | Required | Description | |---|---|---|---| | `content` | `string \| any[]` | yes | | | `created_at_ms` | `integer` | | | | `delivery` | `{ deliver_as?: "steer" \| "follow_up" \| "next_turn", trigger_turn?: boolean, wait?: boolean }` | | | | `details` | `any` | | | | `display` | `boolean` | | | | `request_id` | `string` | | | | `type` | `string` | yes | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `duplicate` | `boolean` | | | | `message` | `object` | yes | | | `result` | `object` | | | | `status` | `"appended" \| "queued" \| "deferred" \| "triggered"` | yes | | #### `message.list_types` No parameters. Result: | Field | Type | Required | Description | |---|---|---|---| | `data` | `{ type: string }[]` | yes | | #### `message.register_type` | Field | Type | Required | Description | |---|---|---|---| | `type` | `string` | yes | | | `callbacks` | `"render" \| "validate"[]` | | | | `scope` | `"all" \| "session"` | | | | `session_id` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `registration_id` | `string` | yes | | ### options #### `options.get` Read effective option values (matching `mare.o.<name>`). Sensitive fields (`config_sensitive`, `providers` keys/headers/query, credentials) are always redacted like `/config`. | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string` | yes | | | `keys` | `string[] \| null` | | option names or dotted paths (default: all) | | `describe` | `boolean` | | return per-key metadata (`effective`, `default`, `source`, `description`, `redacted`, …) instead of bare values (default `false`) | Result: `object` #### `options.set` | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string` | yes | | | `values` | `object` | yes | name → value (e.g. `{"model": "openai/gpt-6.1-terra", "effort": "high"}`) | Result: `EmptyResult` ### peer #### `peer.info` No parameters. Result: `PeerInfo` | Field | Type | Required | Description | |---|---|---|---| | `name` | `string` | yes | | | `pid` | `integer ≥ 0` | yes | | | `cwd` | `string` | yes | | | `version` | `string` | yes | mare version | | `allowed` | `string[]` | yes | methods this connection may call (default set + the session's `peer.allow`) | | `delivery_modes` | `string[]` | | supported inbound message delivery modes (e.g. `trigger_turn`, `queue_only`) | #### `peer.message` `peer.message` params: a message from another session. Where the socket reports the connecting process (Unix credentials), a `from` that disagrees with it is refused: a `pid` other than the connecting process's, or the `name` of a registered session that isn't it. Everything else in `from`, and `policy`, is self-reported: shown only, never grounds for allowing anything. Always held until the receiving user confirms; a plugin can take it over via the `peer/inbound` event. Never an approval. | Field | Type | Required | Description | |---|---|---|---| | `from` | `PeerRef` | | (default `{"name": null, "pid": null, "cwd": null, "session_id": null}`) | | `text` | `string` | yes | | | `queue_only` | `boolean` | | enqueue the message without waking an idle receiver (default `false`) | | `policy` | `any` | | the sender's policy as it reports it (display only until identities can be verified) | Result: `PeerMessageResult` | Field | Type | Required | Description | |---|---|---|---| | `message_id` | `string` | yes | id of this message (repeated in `peer.message_status`) | | `status` | `string` | yes | "held" (waiting for the receiving user; the outcome follows as `peer.message_status`) or "handled" (a plugin took it over via `peer/inbound`) | ### permissions #### `permissions.get` | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `desc` | `string` | | | | `grants` | `{ network?: boolean \| string[], read?: string[], write?: string[] }` | | | | `label` | `string` | yes | | | `level` | `string` | | | | `like` | `"read-only" \| "auto" \| "full-access"` | | | | `partial` | `boolean` | yes | | | `policy_revision` | `integer` | yes | | | `preset` | `string` | yes | | | `rules` | `object[]` | | | #### `permissions.list` | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `data` | `{ current: boolean, desc: string, label: string, level: string, like: "read-only" \| "auto" \| "full-access", name: string }[]` | yes | | #### `permissions.set` | Field | Type | Required | Description | |---|---|---|---| | `confirm` | `boolean` | | | | `name` | `string` | yes | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `desc` | `string` | | | | `grants` | `{ network?: boolean \| string[], read?: string[], write?: string[] }` | | | | `label` | `string` | yes | | | `level` | `string` | | | | `like` | `"read-only" \| "auto" \| "full-access"` | | | | `partial` | `boolean` | yes | | | `policy_revision` | `integer` | yes | | | `preset` | `string` | yes | | | `rules` | `object[]` | | | ### plugins #### `plugins.check` | Field | Type | Required | Description | |---|---|---|---| | `names` | `string[]` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `data` | `{ behind_count: integer, breaking: boolean, commits: string[], error?: string, name: string, status: "up_to_date" \| "outdated" \| "pinned" \| "local" \| "unreachable" }[]` | yes | | #### `plugins.install` | Field | Type | Required | Description | |---|---|---|---| | `name` | `string` | | Optional plugin short name or declared source name; omitted operates on all eligible sources. | | `reload` | `boolean` | | When true and the package operation succeeds, run a full host reload. | Result: | Field | Type | Required | Description | |---|---|---|---| | `log` | `string[]` | yes | | | `reload` | `{ added: string[], notices: string[], reloaded: string[], removed: string[], replaced: string[] }` | | | #### `plugins.list` | Field | Type | Required | Description | |---|---|---|---| | `kind` | `"skills" \| "prompts" \| "themes" \| "types"` | | Optional content kind (`skills \| prompts \| themes \| types`) for `dirs`; omitted returns package roots. | Result: | Field | Type | Required | Description | |---|---|---|---| | `data` | `object[]` | yes | | | `diagnostics` | `{ constraint?: string, message: string, path: string, plugin: string }[]` | yes | | | `dirs` | `{ dir: string, name: string }[]` | yes | | #### `plugins.uninstall` | Field | Type | Required | Description | |---|---|---|---| | `name` | `string` | | Optional plugin short name or declared source name; omitted operates on all eligible sources. | | `reload` | `boolean` | | When true and the package operation succeeds, run a full host reload. | Result: | Field | Type | Required | Description | |---|---|---|---| | `log` | `string[]` | yes | | | `reload` | `{ added: string[], notices: string[], reloaded: string[], removed: string[], replaced: string[] }` | | | #### `plugins.update` | Field | Type | Required | Description | |---|---|---|---| | `name` | `string` | | Optional plugin short name or declared source name; omitted operates on all eligible sources. | | `reload` | `boolean` | | When true and the package operation succeeds, run a full host reload. | | `stash` | `boolean` | | Save local changes and untracked files in git stash before updating. | Result: | Field | Type | Required | Description | |---|---|---|---| | `log` | `string[]` | yes | | | `reload` | `{ added: string[], notices: string[], reloaded: string[], removed: string[], replaced: string[] }` | | | ### query #### `query.call` | Field | Type | Required | Description | |---|---|---|---| | `arguments` | `object` | yes | | | `operation` | `string` | yes | | | `provider` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `next_cursor` | `string` | | | | `provider` | `string` | | | #### `query.list_providers` No parameters. Result: | Field | Type | Required | Description | |---|---|---|---| | `data` | `{ name: string, operations: string[], priority: integer, revision: string, source: { capability: "in_process" \| "opaque" } }[]` | yes | | ### registrations #### `registrations.release` Release one registration this connection holds; answered once it is withdrawn. | Field | Type | Required | Description | |---|---|---|---| | `registration_id` | `string` | yes | | Result: `ReleaseResult` ### services #### `services.list` No parameters. Result: `ServicesListResult` | Field | Type | Required | Description | |---|---|---|---| | `data` | `ServiceInfo[]` | yes | | #### `services.register` | Field | Type | Required | Description | |---|---|---|---| | `name` | `string` | yes | | | `methods` | `map<string, MethodSpec>` | yes | | | `scope` | `RegistrationScopeKind \| null` | | | | `session_id` | `string \| null` | | | Result: `Registration` | Field | Type | Required | Description | |---|---|---|---| | `registration_id` | `string` | yes | | | `name` | `string` | yes | | ### session #### `session.add_record` | Field | Type | Required | Description | |---|---|---|---| | `data` | `any` | | | | `kind` | `string` | yes | | | `persist` | `boolean` | | | | `sync` | `boolean` | | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `durable` | `boolean` | yes | | | `record_id` | `string` | yes | | #### `session.archive` | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string` | yes | | Result: `object` #### `session.close` | Field | Type | Required | Description | |---|---|---|---| | `expected_epoch` | `string` | | | | `session_id` | `string` | yes | | Result: `object` #### `session.create` | Field | Type | Required | Description | |---|---|---|---| | `cwd` | `string` | | | | `name` | `string` | | | | `request_id` | `string` | | | | `subscribe` | `boolean` | | | Result: `mare.LiveSession` | Field | Type | Required | Description | |---|---|---|---| | `archived` | `boolean` | | Whether the session is archived in the index. | | `created_at_ms` | `integer` | yes | Session creation timestamp in milliseconds. | | `cwd` | `string` | yes | Working directory of the session. | | `ephemeral` | `boolean` | | Whether the session is running with persistence disabled. | | `leaf_entry_id` | `string` | | Current leaf entry id when loaded. | | `loaded` | `boolean` | yes | Whether this session is loaded in the current host. | | `name` | `string` | | Optional user-assigned or generated session name. | | `name_revision` | `integer` | | Monotonic revision of the session name when loaded. | | `parent_session_id` | `string` | | Parent or fork-origin session id, if any. | | `path` | `string` | | On-disk JSONL file path when saved. | | `session_epoch` | `string` | yes | In-memory session epoch when loaded. | | `session_id` | `string` | yes | Unique session id. | | `status` | `"idle" \| "busy"` | | Live activity status when loaded. | | `updated_at_ms` | `integer` | yes | Last update timestamp in milliseconds. | #### `session.delete` | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string` | yes | | Result: `object` #### `session.fork` | Field | Type | Required | Description | |---|---|---|---| | `before_item_id` | `string` | | | | `expected_epoch` | `string` | | | | `name` | `string` | | | | `request_id` | `string` | | | | `session_id` | `string` | yes | | | `subscribe` | `boolean` | | | Result: `mare.LiveSession` | Field | Type | Required | Description | |---|---|---|---| | `archived` | `boolean` | | Whether the session is archived in the index. | | `created_at_ms` | `integer` | yes | Session creation timestamp in milliseconds. | | `cwd` | `string` | yes | Working directory of the session. | | `ephemeral` | `boolean` | | Whether the session is running with persistence disabled. | | `leaf_entry_id` | `string` | | Current leaf entry id when loaded. | | `loaded` | `boolean` | yes | Whether this session is loaded in the current host. | | `name` | `string` | | Optional user-assigned or generated session name. | | `name_revision` | `integer` | | Monotonic revision of the session name when loaded. | | `parent_session_id` | `string` | | Parent or fork-origin session id, if any. | | `path` | `string` | | On-disk JSONL file path when saved. | | `session_epoch` | `string` | yes | In-memory session epoch when loaded. | | `session_id` | `string` | yes | Unique session id. | | `status` | `"idle" \| "busy"` | | Live activity status when loaded. | | `updated_at_ms` | `integer` | yes | Last update timestamp in milliseconds. | #### `session.get` | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string` | yes | | Result: `mare.Session` | Field | Type | Required | Description | |---|---|---|---| | `archived` | `boolean` | | Whether the session is archived in the index. | | `created_at_ms` | `integer` | yes | Session creation timestamp in milliseconds. | | `cwd` | `string` | yes | Working directory of the session. | | `ephemeral` | `boolean` | | Whether the session is running with persistence disabled. | | `leaf_entry_id` | `string` | | Current leaf entry id when loaded. | | `loaded` | `boolean` | yes | Whether this session is loaded in the current host. | | `name` | `string` | | Optional user-assigned or generated session name. | | `name_revision` | `integer` | | Monotonic revision of the session name when loaded. | | `parent_session_id` | `string` | | Parent or fork-origin session id, if any. | | `path` | `string` | | On-disk JSONL file path when saved. | | `session_epoch` | `string` | | In-memory session epoch when loaded. | | `session_id` | `string` | yes | Unique session id. | | `source_leaf_entry_id` | `string` | | Source leaf entry id observed when creating a snapshot, if any. | | `status` | `"idle" \| "busy"` | | Live activity status when loaded. | | `updated_at_ms` | `integer` | yes | Last update timestamp in milliseconds. | #### `session.get_item` | Field | Type | Required | Description | |---|---|---|---| | `after` | `integer` | | | | `before` | `integer` | | | | `item_id` | `string` | yes | | | `max_bytes` | `integer` | | | | `offset` | `integer` | | | | `session_id` | `string` | yes | | Result: | Field | Type | Required | Description | |---|---|---|---| | `chunk` | `string` | | | | `chunk_offset` | `integer` | | | | `corpus_revision` | `string` | yes | | | `item` | `object` | | | | `item_id` | `string` | yes | | | `neighbors` | `{ item_id: string, type: string }[]` | yes | | | `next_offset` | `integer` | | | | `seq` | `integer` | yes | | | `session_id` | `string` | yes | | | `total_bytes` | `integer` | | | #### `session.label_item` | Field | Type | Required | Description | |---|---|---|---| | `item_id` | `string` | | | | `label` | `string` | yes | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `item_id` | `string` | yes | | | `label` | `string` | | | #### `session.list` | Field | Type | Required | Description | |---|---|---|---| | `all` | `boolean` | | | | `archived` | `boolean` | | | | `cursor` | `string` | | | | `cwd` | `string` | | | | `limit` | `integer` | | | | `loaded` | `boolean` | | | | `parent_session_id` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `data` | `mare.Session[]` | yes | | | `next_cursor` | `string` | | | #### `session.list_items` | Field | Type | Required | Description | |---|---|---|---| | `branch` | `"current" \| "all"` | | | | `cursor` | `string` | | | | `direction` | `"asc" \| "desc"` | | | | `limit` | `integer` | | | | `types` | `string[]` | | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `data` | `object[]` | yes | | | `leaf_entry_id` | `string` | | | | `next_cursor` | `string` | | | #### `session.list_records` | Field | Type | Required | Description | |---|---|---|---| | `branch` | `"current" \| "all"` | | | | `cursor` | `string` | | | | `kind` | `string` | yes | | | `limit` | `integer` | | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `data` | `any[]` | yes | | | `next_cursor` | `string` | | | #### `session.load` | Field | Type | Required | Description | |---|---|---|---| | `path` | `string` | | | | `session_id` | `string` | | | | `subscribe` | `boolean` | | | Result: `mare.LiveSession` | Field | Type | Required | Description | |---|---|---|---| | `archived` | `boolean` | | Whether the session is archived in the index. | | `created_at_ms` | `integer` | yes | Session creation timestamp in milliseconds. | | `cwd` | `string` | yes | Working directory of the session. | | `ephemeral` | `boolean` | | Whether the session is running with persistence disabled. | | `leaf_entry_id` | `string` | | Current leaf entry id when loaded. | | `loaded` | `boolean` | yes | Whether this session is loaded in the current host. | | `name` | `string` | | Optional user-assigned or generated session name. | | `name_revision` | `integer` | | Monotonic revision of the session name when loaded. | | `parent_session_id` | `string` | | Parent or fork-origin session id, if any. | | `path` | `string` | | On-disk JSONL file path when saved. | | `session_epoch` | `string` | yes | In-memory session epoch when loaded. | | `session_id` | `string` | yes | Unique session id. | | `status` | `"idle" \| "busy"` | | Live activity status when loaded. | | `updated_at_ms` | `integer` | yes | Last update timestamp in milliseconds. | #### `session.rewind` | Field | Type | Required | Description | |---|---|---|---| | `before_item_id` | `string` | | | | `expected_epoch` | `string` | | | | `restore_files` | `boolean` | | | | `session_id` | `string` | yes | | | `summarize` | `boolean` | | | Result: `mare.LiveSession` | Field | Type | Required | Description | |---|---|---|---| | `archived` | `boolean` | | Whether the session is archived in the index. | | `created_at_ms` | `integer` | yes | Session creation timestamp in milliseconds. | | `cwd` | `string` | yes | Working directory of the session. | | `ephemeral` | `boolean` | | Whether the session is running with persistence disabled. | | `leaf_entry_id` | `string` | | Current leaf entry id when loaded. | | `loaded` | `boolean` | yes | Whether this session is loaded in the current host. | | `name` | `string` | | Optional user-assigned or generated session name. | | `name_revision` | `integer` | | Monotonic revision of the session name when loaded. | | `parent_session_id` | `string` | | Parent or fork-origin session id, if any. | | `path` | `string` | | On-disk JSONL file path when saved. | | `session_epoch` | `string` | yes | In-memory session epoch when loaded. | | `session_id` | `string` | yes | Unique session id. | | `status` | `"idle" \| "busy"` | | Live activity status when loaded. | | `updated_at_ms` | `integer` | yes | Last update timestamp in milliseconds. | #### `session.search` | Field | Type | Required | Description | |---|---|---|---| | `cursor` | `string` | | | | `event_filters` | `{ event_types?: string[], from_ms?: integer, seq_from?: integer, seq_to?: integer, surfaces?: "current" \| "shadowed" \| "log_only"[], to_ms?: integer }` | | | | `filters` | `object` | | | | `limit` | `integer` | | | | `query` | `string` | | | | `sort_direction` | `"asc" \| "desc"` | | | | `sort_key` | `"relevance" \| "created_at_ms" \| "updated_at_ms"` | | | | `step_bound` | `boolean` | | | | `title_query` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `corpus_revision` | `string` | yes | | | `data` | `object[]` | yes | | | `incomplete` | `boolean` | yes | | | `next_cursor` | `string` | | | #### `session.search_items` | Field | Type | Required | Description | |---|---|---|---| | `cursor` | `string` | | | | `event_filters` | `{ event_types?: string[], from_ms?: integer, seq_from?: integer, seq_to?: integer, surfaces?: "current" \| "shadowed" \| "log_only"[], to_ms?: integer }` | | | | `filters` | `object` | | | | `limit` | `integer` | | | | `query` | `string` | | | | `session_id` | `string` | yes | | | `sort_direction` | `"asc" \| "desc"` | | | | `sort_key` | `"relevance" \| "created_at_ms" \| "updated_at_ms"` | | | | `step_bound` | `boolean` | | | | `title_query` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `corpus_revision` | `string` | yes | | | `data` | `object[]` | yes | | | `incomplete` | `boolean` | yes | | | `next_cursor` | `string` | | | #### `session.snapshot` | Field | Type | Required | Description | |---|---|---|---| | `before_item_id` | `string` | | | | `effort` | `string` | | | | `expected_epoch` | `string` | | | | `initiating_tool_call_id` | `string` | | | | `last_completed_turns` | `integer` | | | | `model` | `string` | | | | `name` | `string` | | | | `request_id` | `string` | | | | `session_id` | `string` | yes | | Result: `mare.Session` | Field | Type | Required | Description | |---|---|---|---| | `archived` | `boolean` | | Whether the session is archived in the index. | | `created_at_ms` | `integer` | yes | Session creation timestamp in milliseconds. | | `cwd` | `string` | yes | Working directory of the session. | | `ephemeral` | `boolean` | | Whether the session is running with persistence disabled. | | `leaf_entry_id` | `string` | | Current leaf entry id when loaded. | | `loaded` | `boolean` | yes | Whether this session is loaded in the current host. | | `name` | `string` | | Optional user-assigned or generated session name. | | `name_revision` | `integer` | | Monotonic revision of the session name when loaded. | | `parent_session_id` | `string` | | Parent or fork-origin session id, if any. | | `path` | `string` | | On-disk JSONL file path when saved. | | `session_epoch` | `string` | | In-memory session epoch when loaded. | | `session_id` | `string` | yes | Unique session id. | | `source_leaf_entry_id` | `string` | | Source leaf entry id observed when creating a snapshot, if any. | | `status` | `"idle" \| "busy"` | | Live activity status when loaded. | | `updated_at_ms` | `integer` | yes | Last update timestamp in milliseconds. | #### `session.trace` | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string` | yes | | Result: | Field | Type | Required | Description | |---|---|---|---| | `ancestors` | `{ created_at_ms?: integer, session_id: string, title_available: boolean }[]` | yes | | | `complete` | `boolean` | yes | | | `descendants` | `object[]` | yes | | | `incomplete` | `boolean` | yes | | | `metadata_only` | `boolean` | yes | | | `parent_boundary` | `boolean` | yes | | | `root` | `{ created_at_ms?: integer, session_id: string, title_available: boolean }` | | | | `scope` | `string` | yes | | | `target` | `{ created_at_ms?: integer, session_id: string, title_available: boolean }` | yes | | #### `session.trace_item` | Field | Type | Required | Description | |---|---|---|---| | `item_id` | `string` | yes | | | `session_id` | `string` | yes | | Result: | Field | Type | Required | Description | |---|---|---|---| | `availability` | `string` | yes | | | `created_at_ms` | `integer` | | | | `derived_event_seqs` | `integer[]` | yes | | | `entry_id` | `string` | | | | `incomplete` | `boolean` | yes | | | `item_id` | `string` | yes | | | `replaced_by` | `integer` | | | | `replaced_event_seqs` | `integer[]` | yes | | | `replacement_chain` | `integer[]` | yes | | | `result_entry_id` | `string` | | | | `role` | `string` | | | | `seq` | `integer` | yes | | | `session_id` | `string` | yes | | | `source_event_seqs` | `integer[]` | yes | | | `summary` | `string` | yes | | | `surface` | `string` | yes | | | `type` | `string` | yes | | #### `session.unarchive` | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string` | yes | | Result: `object` #### `session.update` | Field | Type | Required | Description | |---|---|---|---| | `expected_revision` | `integer` | | | | `name` | `string` | yes | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: `mare.LiveSession` | Field | Type | Required | Description | |---|---|---|---| | `archived` | `boolean` | | Whether the session is archived in the index. | | `created_at_ms` | `integer` | yes | Session creation timestamp in milliseconds. | | `cwd` | `string` | yes | Working directory of the session. | | `ephemeral` | `boolean` | | Whether the session is running with persistence disabled. | | `leaf_entry_id` | `string` | | Current leaf entry id when loaded. | | `loaded` | `boolean` | yes | Whether this session is loaded in the current host. | | `name` | `string` | | Optional user-assigned or generated session name. | | `name_revision` | `integer` | | Monotonic revision of the session name when loaded. | | `parent_session_id` | `string` | | Parent or fork-origin session id, if any. | | `path` | `string` | | On-disk JSONL file path when saved. | | `session_epoch` | `string` | yes | In-memory session epoch when loaded. | | `session_id` | `string` | yes | Unique session id. | | `status` | `"idle" \| "busy"` | | Live activity status when loaded. | | `updated_at_ms` | `integer` | yes | Last update timestamp in milliseconds. | ### `shutdown` No parameters. Result: `EmptyResult` ### spill #### `spill.delete` | Field | Type | Required | Description | |---|---|---|---| | `spill_id` | `string` | yes | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: `object` #### `spill.list_backends` No parameters. Result: | Field | Type | Required | Description | |---|---|---|---| | `data` | `{ name: string, selected: boolean }[]` | yes | | #### `spill.read` | Field | Type | Required | Description | |---|---|---|---| | `encoding` | `"text" \| "base64"` | | | | `limit` | `integer` | | | | `offset` | `integer` | | | | `spill_id` | `string` | yes | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `content` | `string` | | | | `data_base64` | `string` | | | | `next_offset` | `integer` | | | | `size` | `integer` | | | #### `spill.save` | Field | Type | Required | Description | |---|---|---|---| | `backend` | `string` | | | | `content` | `string` | | | | `data_base64` | `string` | | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `size` | `integer` | yes | | | `spill_id` | `string` | yes | | ### state #### `state.compare_exchange` Atomically replace durable namespace state at `expected_revision` (`ok`, `conflict` with the current snapshot, or `rejected`). Strict JSON preserves null and empty containers; deletion requires `null` and retains a monotonic revision. Cancellation before publication prevents writes; after publication admission rollback is not guaranteed, and `unknown_state` requires reread/reconciliation. | Field | Type | Required | Description | |---|---|---|---| | `namespace` | `string` | yes | | | `expected_revision` | `integer ≥ 0` | yes | | | `value` | `any` | yes | | | `delete` | `boolean` | | (default `false`) | Result: `StateCompareExchangeResult` #### `state.snapshot` Read isolated durable application state (distinct from `agent.get`). Absent or deleted namespaces report `exists: false` and `null` value with tombstone revision retained. | Field | Type | Required | Description | |---|---|---|---| | `namespace` | `string` | yes | | Result: `StateSnapshotResult` ### status #### `status.get` No parameters. Result: `mare.Status` | Field | Type | Required | Description | |---|---|---|---| | `cwd` | `string` | yes | | | `message` | `string` | yes | | | `model` | `string` | | | | `pid` | `integer` | yes | | | `seq` | `integer` | yes | | | `session` | `{ path?: string, resume?: string[], session_id?: string }` | yes | | | `state` | `"idle" \| "working" \| "blocked"` | yes | | ### subagent #### `subagent.cancel` | Field | Type | Required | Description | |---|---|---|---| | `subagent_id` | `string` | yes | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: `object` #### `subagent.get` | Field | Type | Required | Description | |---|---|---|---| | `subagent_id` | `string` | yes | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `ended_at_ms` | `integer` | | | | `error` | `{ code: string, data?: any, message: string }` | | | | `error_kind` | `string` | | | | `label` | `string` | | | | `name` | `string` | | | | `parent_session_id` | `string` | | | | `run_id` | `string` | | | | `seq` | `integer` | | | | `started_at_ms` | `integer` | yes | | | `status` | `"running" \| "completed" \| "failed" \| "cancelled" \| "interrupted"` | yes | | | `subagent_id` | `string` | yes | Unique identifier (child session id) of the subagent. | | `task` | `string` | | | #### `subagent.list` | Field | Type | Required | Description | |---|---|---|---| | `cursor` | `string` | | | | `limit` | `integer` | | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `data` | `object[]` | yes | | | `next_cursor` | `string` | | | #### `subagent.list_types` | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `data` | `object[]` | yes | | #### `subagent.register_type` | Field | Type | Required | Description | |---|---|---|---| | `definition` | `object` | yes | | | `replace` | `boolean` | | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `registration_id` | `string` | yes | | #### `subagent.start` | Field | Type | Required | Description | |---|---|---|---| | `config` | `object` | | | | `cwd` | `string` | | | | `effort` | `string` | | | | `fork` | `"none" \| "all" \| integer` | | | | `label` | `string` | | | | `messages` | `object[]` | | | | `model` | `string` | | | | `name` | `string` | | | | `output_schema` | `object` | | | | `params` | `object` | | | | `persona` | `string` | | | | `phase` | `string` | | | | `prompt` | `string` | yes | | | `run_id` | `string` | | | | `sections` | `object[]` | | | | `seq` | `integer` | | | | `system` | `string` | | | | `task` | `string` | | | | `tools` | `string[]` | | | | `type` | `string` | | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `ended_at_ms` | `integer` | | | | `error` | `{ code: string, data?: any, message: string }` | | | | `error_kind` | `string` | | | | `label` | `string` | | | | `name` | `string` | | | | `parent_session_id` | `string` | | | | `run_id` | `string` | | | | `seq` | `integer` | | | | `started_at_ms` | `integer` | yes | | | `status` | `"running" \| "completed" \| "failed" \| "cancelled" \| "interrupted"` | yes | | | `subagent_id` | `string` | yes | Unique identifier (child session id) of the subagent. | | `task` | `string` | | | #### `subagent.steer` | Field | Type | Required | Description | |---|---|---|---| | `subagent_id` | `string` | yes | | | `text` | `string` | yes | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: `object` #### `subagent.wait` | Field | Type | Required | Description | |---|---|---|---| | `subagent_id` | `string` | yes | | | `timeout_ms` | `integer` | | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `error` | `{ code: string, data?: any, message: string }` | | | | `error_kind` | `string` | | | | `messages` | `object[]` | | | | `status` | `"running" \| "completed" \| "failed" \| "cancelled" \| "interrupted"` | yes | | | `subagent_id` | `string` | yes | Unique identifier (child session id) of the subagent. | | `text` | `string` | | | | `timed_out` | `boolean` | yes | | | `usage` | `object` | | | ### terminal #### `terminal.close` | Field | Type | Required | Description | |---|---|---|---| | `grace_ms` | `integer` | | Optional SIGTERM grace period in milliseconds (0..30000, default 3000). | | `terminal_id` | `string` | yes | Owned terminal identifier returned by `terminal.create`. | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: `mare.TerminalSessionSnapshot` | Field | Type | Required | Description | |---|---|---|---| | `alternate_screen` | `boolean` | | | | `cols` | `integer` | yes | | | `command_exit_code` | `integer` | | | | `exit_code` | `integer` | | | | `exit_signal` | `integer` | | | | `name` | `string` | | | | `output_offset` | `integer` | yes | | | `pid` | `integer` | | | | `prompt_seq` | `integer` | | | | `rows` | `integer` | yes | | | `screen` | `string` | | | | `status` | `"running" \| "completed" \| "failed" \| "cancelled"` | yes | | | `terminal_id` | `string` | yes | | | `truncated` | `boolean` | yes | | | `view_truncated` | `boolean` | | | #### `terminal.create` | Field | Type | Required | Description | |---|---|---|---| | `args` | `string[]` | | | | `buffer_bytes` | `integer` | | | | `cmd` | `string` | | | | `cols` | `integer` | | Terminal columns (1..500, default 80). | | `cwd` | `string` | | | | `emulate` | `boolean` | | | | `env` | `map<string, string>` | | | | `name` | `string` | | Optional unique name within this owner (1..128 bytes). | | `rows` | `integer` | | Terminal rows (1..200, default 24). | | `scrollback_lines` | `integer` | | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: `mare.TerminalSessionSnapshot` | Field | Type | Required | Description | |---|---|---|---| | `alternate_screen` | `boolean` | | | | `cols` | `integer` | yes | | | `command_exit_code` | `integer` | | | | `exit_code` | `integer` | | | | `exit_signal` | `integer` | | | | `name` | `string` | | | | `output_offset` | `integer` | yes | | | `pid` | `integer` | | | | `prompt_seq` | `integer` | | | | `rows` | `integer` | yes | | | `screen` | `string` | | | | `status` | `"running" \| "completed" \| "failed" \| "cancelled"` | yes | | | `terminal_id` | `string` | yes | | | `truncated` | `boolean` | yes | | | `view_truncated` | `boolean` | | | #### `terminal.list` | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `data` | `mare.TerminalSessionSnapshot[]` | yes | | #### `terminal.read` | Field | Type | Required | Description | |---|---|---|---| | `count` | `integer` | | | | `max_bytes` | `integer` | | Maximum output bytes to return (1..4194304, default 262144). Applies to both incremental `output_offset` slicing (UTF-8 safe, floor one char) and VT page mode as well as `screen`; sets `truncated` true when capped. | | `offset` | `integer` | | | | `output_offset` | `integer` | | | | `screen` | `boolean` | | | | `terminal_id` | `string` | yes | Owned terminal identifier returned by `terminal.create`. | | `wait_ms` | `integer` | | Optional bounded wait in milliseconds (0..60000). | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `alternate_screen` | `boolean` | | | | `cols` | `integer` | yes | | | `command_exit_code` | `integer` | | | | `exit_code` | `integer` | | | | `exit_signal` | `integer` | | | | `line_begin` | `integer` | yes | | | `line_end` | `integer` | yes | | | `name` | `string` | | | | `next_output_offset` | `integer` | yes | | | `output_offset` | `integer` | yes | | | `pid` | `integer` | | | | `prompt_seq` | `integer` | | | | `rows` | `integer` | yes | | | `screen` | `string` | | | | `status` | `"running" \| "completed" \| "failed" \| "cancelled"` | yes | | | `terminal_id` | `string` | yes | | | `text` | `string` | yes | | | `total_lines` | `integer` | yes | | | `truncated` | `boolean` | yes | | | `view_truncated` | `boolean` | | | #### `terminal.resize` | Field | Type | Required | Description | |---|---|---|---| | `cols` | `integer` | yes | Terminal columns (1..500, default 80). | | `rows` | `integer` | yes | Terminal rows (1..200, default 24). | | `terminal_id` | `string` | yes | Owned terminal identifier returned by `terminal.create`. | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: `object` #### `terminal.send` | Field | Type | Required | Description | |---|---|---|---| | `max_bytes` | `integer` | | Maximum output bytes to return (1..4194304, default 262144). Output is truncated at a UTF-8 boundary (always returning at least one character if non-empty) and sets `truncated` true; when `screen` is true, rendered screen is head-trimmed to fit and sets `view_truncated`. | | `screen` | `boolean` | | | | `submit` | `boolean` | | | | `terminal_id` | `string` | yes | Owned terminal identifier returned by `terminal.create`. | | `text` | `string` | | | | `wait_ms` | `integer` | | Optional bounded wait in milliseconds (0..60000). | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `alternate_screen` | `boolean` | | | | `cols` | `integer` | yes | | | `command_exit_code` | `integer` | | | | `exit_code` | `integer` | | | | `exit_signal` | `integer` | | | | `name` | `string` | | | | `next_output_offset` | `integer` | yes | | | `output` | `string` | yes | | | `output_offset` | `integer` | yes | | | `pid` | `integer` | | | | `prompt_seq` | `integer` | | | | `rows` | `integer` | yes | | | `screen` | `string` | | | | `status` | `"running" \| "completed" \| "failed" \| "cancelled"` | yes | | | `terminal_id` | `string` | yes | | | `timed_out` | `boolean` | yes | | | `truncated` | `boolean` | yes | | | `view_truncated` | `boolean` | | | #### `terminal.signal` | Field | Type | Required | Description | |---|---|---|---| | `signal` | `"SIGINT" \| "SIGTERM" \| "SIGKILL" \| "SIGTSTP" \| "SIGHUP"` | yes | | | `terminal_id` | `string` | yes | Owned terminal identifier returned by `terminal.create`. | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: `object` ### theme #### `theme.cancel_preview` No parameters. Result: `mare.ThemeSnapshot` | Field | Type | Required | Description | |---|---|---|---| | `active` | `string` | yes | | | `appearance` | `"dark" \| "light"` | yes | | | `component` | `any` | yes | | | `dark` | `string` | yes | | | `icons` | `map<string, string>` | yes | | | `light` | `string` | yes | | | `preference` | `string` | yes | | | `preview` | `string` | | | | `revision` | `integer` | yes | | | `styles` | `map<string, object>` | yes | | | `syntax` | `string` | | | #### `theme.get` No parameters. Result: `mare.ThemeSnapshot` | Field | Type | Required | Description | |---|---|---|---| | `active` | `string` | yes | | | `appearance` | `"dark" \| "light"` | yes | | | `component` | `any` | yes | | | `dark` | `string` | yes | | | `icons` | `map<string, string>` | yes | | | `light` | `string` | yes | | | `preference` | `string` | yes | | | `preview` | `string` | | | | `revision` | `integer` | yes | | | `styles` | `map<string, object>` | yes | | | `syntax` | `string` | | | #### `theme.list` No parameters. Result: | Field | Type | Required | Description | |---|---|---|---| | `data` | `{ label: string, name: string, origin: string, variants: "dark" \| "light"[] }[]` | yes | | #### `theme.preview` | Field | Type | Required | Description | |---|---|---|---| | `theme` | `string` | yes | | Result: `mare.ThemeSnapshot` | Field | Type | Required | Description | |---|---|---|---| | `active` | `string` | yes | | | `appearance` | `"dark" \| "light"` | yes | | | `component` | `any` | yes | | | `dark` | `string` | yes | | | `icons` | `map<string, string>` | yes | | | `light` | `string` | yes | | | `preference` | `string` | yes | | | `preview` | `string` | | | | `revision` | `integer` | yes | | | `styles` | `map<string, object>` | yes | | | `syntax` | `string` | | | #### `theme.register` | Field | Type | Required | Description | |---|---|---|---| | `definition` | `object` | yes | | | `scope` | `"all" \| "session"` | | | | `session_id` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `registration_id` | `string` | yes | | #### `theme.register_override` | Field | Type | Required | Description | |---|---|---|---| | `layer_id` | `string` | yes | | | `styles` | `map<string, object>` | yes | | | `scope` | `"all" \| "session"` | | | | `session_id` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `registration_id` | `string` | yes | | #### `theme.select` | Field | Type | Required | Description | |---|---|---|---| | `save` | `boolean` | | | | `theme` | `string` | yes | | Result: `mare.ThemeSnapshot` | Field | Type | Required | Description | |---|---|---|---| | `active` | `string` | yes | | | `appearance` | `"dark" \| "light"` | yes | | | `component` | `any` | yes | | | `dark` | `string` | yes | | | `icons` | `map<string, string>` | yes | | | `light` | `string` | yes | | | `preference` | `string` | yes | | | `preview` | `string` | | | | `revision` | `integer` | yes | | | `styles` | `map<string, object>` | yes | | | `syntax` | `string` | | | ### tools #### `tools.register` | Field | Type | Required | Description | |---|---|---|---| | `access` | `{ kind: "file", op: "read" \| "write" \| "create" \| "delete", path_arg: string, recursive: boolean }[]` | | | | `concurrency_safe` | `boolean` | | | | `description` | `string` | yes | | | `exposure` | `"direct" \| "deferred" \| "nested"` | | | | `guidelines` | `string[]` | | | | `idempotent` | `boolean` | | | | `name` | `string` | yes | | | `parameters` | `object` | yes | | | `side_effect` | `"read" \| "write" \| "external"` | | | | `snippet` | `string` | | | | `timeout_ms` | `integer` | | | | `callbacks` | `"execute"[]` | yes | | | `scope` | `"all" \| "session"` | | | | `session_id` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `registration_id` | `string` | yes | | ### ui #### `ui.attach` | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string` | yes | | | `responder` | `boolean \| null` | | | | `takeover` | `string[]` | | (default `[]`) | | `viewport` | `UiViewport \| null` | | | Result: `UiAttachResult` | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string` | yes | | | `session_epoch` | `string` | yes | | | `responder` | `boolean` | yes | | | `takeover` | `string[]` | yes | | | `snapshot` | `UiShellSnapshot` | yes | | #### `ui.call_keymap` | Field | Type | Required | Description | |---|---|---|---| | `action` | `string` | | | | `context` | `string` | | | | `key` | `string` | | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `action` | `string` | | | | `context` | `string` | | | | `declined` | `boolean` | yes | | | `handled` | `boolean` | yes | | | `masked` | `boolean` | yes | | | `reason` | `string` | | | #### `ui.cancel_markdown` | Field | Type | Required | Description | |---|---|---|---| | `document_id` | `string` | yes | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: `object` #### `ui.delete_keymap` | Field | Type | Required | Description | |---|---|---|---| | `context` | `string` | yes | | | `key` | `string` | yes | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `context` | `string` | yes | | | `key` | `string` | yes | | #### `ui.delete_markdown` | Field | Type | Required | Description | |---|---|---|---| | `document_id` | `string` | yes | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: `object` #### `ui.detach` | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string` | yes | | Result: `UiDetachResult` | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string` | yes | | #### `ui.get_keymap` | Field | Type | Required | Description | |---|---|---|---| | `context` | `string` | | Optional context name to filter by. | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `actions` | `{ contexts?: string[], core?: boolean, desc?: string, essential?: boolean, keys?: string[], name: string }[]` | yes | | | `bindings` | `object[]` | yes | | | `conflicts` | `{ missing_essential: { action: string, context: string }[], unbound_essential: { action: string, context: string }[] }` | yes | | | `contexts` | `{ bindable: boolean, chain: string[], core: boolean, name: string, parents: string[] }[]` | yes | | #### `ui.get_markdown` | Field | Type | Required | Description | |---|---|---|---| | `document_id` | `string` | yes | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: `mare.MarkdownSnapshot` | Field | Type | Required | Description | |---|---|---|---| | `diagnostic` | `string` | | | | `document_id` | `string` | yes | | | `enhanced` | `boolean` | yes | | | `expanded_node` | `mare.Node` | yes | | | `node` | `mare.Node` | yes | | | `pending` | `integer` | yes | | | `render_seq` | `integer` | yes | | | `revision` | `integer` | yes | | | `session_epoch` | `string` | | | | `session_id` | `string` | | | | `source` | `string` | yes | | | `supports_artifact_images` | `boolean` | yes | | #### `ui.get_select_preview` | Field | Type | Required | Description | |---|---|---|---| | `index` | `integer` | yes | | | `select_id` | `string` | yes | | | `tab` | `integer` | | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `preview` | `string \| mare.Node` | | | #### `ui.invalidate` | Field | Type | Required | Description | |---|---|---|---| | `component` | `string` | | Widget (`widget:<id>` or widget id) or status segment id to redraw. | | `viewport` | `{ height?: integer, supports_artifact_images?: boolean, supports_images?: boolean, width?: integer }` | | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: `object` #### `ui.invalidate_presentations` | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: `object` #### `ui.list_markdown_presenters` No parameters. Result: | Field | Type | Required | Description | |---|---|---|---| | `data` | `{ language: string, preview: boolean, requires_artifact_images: boolean, timeout_ms: integer }[]` | yes | | #### `ui.register_entry_renderer` | Field | Type | Required | Description | |---|---|---|---| | `kind` | `string` | yes | | | `callbacks` | `"render"[]` | yes | | | `scope` | `"all" \| "session"` | | | | `session_id` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `registration_id` | `string` | yes | | #### `ui.register_markdown_transform` | Field | Type | Required | Description | |---|---|---|---| | `message_types` | `"user" \| "assistant" \| "assistant-reasoning" \| "custom" \| "summary" \| "changelog"[]` | | | | `callbacks` | `"transform"[]` | yes | | | `scope` | `"all" \| "session"` | | | | `session_id` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `registration_id` | `string` | yes | | #### `ui.render_markdown` | Field | Type | Required | Description | |---|---|---|---| | `base_node` | `mare.Node` | | | | `document_id` | `string` | yes | | | `replay` | `boolean` | | | | `source` | `string` | yes | | | `viewport` | `{ height?: integer, supports_artifact_images?: boolean, supports_images?: boolean, width?: integer }` | | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: `mare.MarkdownSnapshot` | Field | Type | Required | Description | |---|---|---|---| | `diagnostic` | `string` | | | | `document_id` | `string` | yes | | | `enhanced` | `boolean` | yes | | | `expanded_node` | `mare.Node` | yes | | | `node` | `mare.Node` | yes | | | `pending` | `integer` | yes | | | `render_seq` | `integer` | yes | | | `revision` | `integer` | yes | | | `session_epoch` | `string` | | | | `session_id` | `string` | | | | `source` | `string` | yes | | | `supports_artifact_images` | `boolean` | yes | | #### `ui.send_editor` | Field | Type | Required | Description | |---|---|---|---| | `attachments` | `object[]` | | | | `mode` | `"prompt" \| "steer" \| "follow_up"` | | | | `text` | `string` | | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `handled` | `boolean` | yes | | | `result` | `object` | | | | `revision` | `integer` | yes | | #### `ui.set_external_editor` | Field | Type | Required | Description | |---|---|---|---| | `action` | `"start" \| "commit" \| "cancel"` | yes | | | `text` | `string` | | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `program` | `string` | | | | `revision` | `integer` | yes | | | `running` | `boolean` | yes | | | `text` | `string` | yes | | #### `ui.set_keymap` | Field | Type | Required | Description | |---|---|---|---| | `action` | `string \| boolean` | yes | | | `context` | `string` | yes | | | `desc` | `string` | | | | `key` | `string` | yes | | | `priority` | `number` | | | | `unique` | `boolean` | | | | `when` | `string[]` | | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `registration_id` | `string` | yes | | #### `ui.transform_markdown` | Field | Type | Required | Description | |---|---|---|---| | `available_width` | `integer` | | | | `created_at_ms` | `integer` | | | | `is_streaming` | `boolean` | | | | `message_id` | `string` | | | | `message_type` | `"user" \| "assistant" \| "assistant-reasoning" \| "custom" \| "summary" \| "changelog"` | | | | `text` | `string` | yes | | Result: | Field | Type | Required | Description | |---|---|---|---| | `text` | `string` | yes | | #### `ui.update_editor` | Field | Type | Required | Description | |---|---|---|---| | `attachments` | `{ attachment_id: string, height?: integer, label?: string, mime_type?: string, width?: integer }[]` | | | | `image_markers` | `string[]` | | | | `offset` | `integer` | | | | `shell_mode` | `boolean` | | | | `text` | `string` | yes | | | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `attachments` | `{ attachment_id: string, height?: integer, label?: string, mime_type?: string, width?: integer }[]` | | | | `external_editor_running` | `boolean` | yes | | | `image_markers` | `string[]` | | | | `offset` | `integer` | yes | | | `revision` | `integer` | yes | | | `shell_mode` | `boolean` | yes | | | `text` | `string` | yes | | ### usage #### `usage.get` | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string` | yes | | | `expected_epoch` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `context_tokens` | `integer` | yes | | | `rate_limits` | `map<string, { credits?: string, limit_name?: string, primary?: object, reached?: string, received_at_ms: integer, secondary?: object }>` | yes | | | `totals` | `object` | yes | | ### web #### `web.fetch` | Field | Type | Required | Description | |---|---|---|---| | `timeout_ms` | `integer` | | | | `url` | `string` | yes | | Result: `mare.WebFetchResult` | Field | Type | Required | Description | |---|---|---|---| | `content` | `string` | yes | | | `content_type` | `string` | | | | `requested_url` | `string` | yes | | | `status` | `integer` | | | | `truncated` | `boolean` | | | | `url` | `string` | | | #### `web.list_providers` | Field | Type | Required | Description | |---|---|---|---| | `kind` | `"search" \| "fetch"` | yes | | Result: | Field | Type | Required | Description | |---|---|---|---| | `data` | `{ available: boolean, provider_id: string, selected: boolean, unconfined: boolean }[]` | yes | | | `reason` | `string` | | | #### `web.register_fetch` | Field | Type | Required | Description | |---|---|---|---| | `provider_id` | `string` | yes | | | `unconfined` | `boolean` | | | | `callbacks` | `"fetch"[]` | yes | | | `scope` | `"all" \| "session"` | | | | `session_id` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `registration_id` | `string` | yes | | #### `web.register_search` | Field | Type | Required | Description | |---|---|---|---| | `provider_id` | `string` | yes | | | `unconfined` | `boolean` | | | | `callbacks` | `"search"[]` | yes | | | `scope` | `"all" \| "session"` | | | | `session_id` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `registration_id` | `string` | yes | | #### `web.search` | Field | Type | Required | Description | |---|---|---|---| | `queries` | `string[]` | yes | | | `timeout_ms` | `integer` | | | Result: `mare.WebSearchResult` | Field | Type | Required | Description | |---|---|---|---| | `content` | `string` | | | | `data` | `{ published_at_ms?: integer, snippet?: string, summary?: string, title?: string, url: string }[]` | yes | | | `truncated` | `boolean` | | | ### webserver #### `webserver.get` No parameters. Result: | Field | Type | Required | Description | |---|---|---|---| | `host` | `string` | | | | `port` | `integer` | | | | `running` | `boolean` | yes | | | `tls` | `boolean` | | | | `trusted_hosts` | `string[]` | | | | `url` | `string` | | | | `ws_url` | `string` | | | #### `webserver.list_assets` No parameters. Result: | Field | Type | Required | Description | |---|---|---|---| | `data` | `{ asset_id: string, dir: string, fallback?: string, index?: string, plugin?: string, prefix: string }[]` | yes | | #### `webserver.list_routes` No parameters. Result: | Field | Type | Required | Description | |---|---|---|---| | `data` | `{ method: string, owner_session_id?: string, path: string, plugin?: string, route_id: string }[]` | yes | | #### `webserver.register_assets` | Field | Type | Required | Description | |---|---|---|---| | `dir` | `string` | yes | | | `fallback` | `string` | | | | `index` | `string` | | | | `prefix` | `string` | | | Result: | Field | Type | Required | Description | |---|---|---|---| | `registration_id` | `string` | yes | | #### `webserver.register_route` | Field | Type | Required | Description | |---|---|---|---| | `method` | `"GET" \| "POST" \| "PUT" \| "PATCH" \| "DELETE" \| "HEAD" \| "ANY"` | | | | `path` | `string` | yes | | | `callbacks` | `"handle"[]` | yes | | Result: | Field | Type | Required | Description | |---|---|---|---| | `registration_id` | `string` | yes | | ### workspace #### `workspace.get` | Field | Type | Required | Description | |---|---|---|---| | `cwd` | `string` | yes | | Result: | Field | Type | Required | Description | |---|---|---|---| | `dirs` | `string[]` | yes | | | `root` | `string` | yes | | | `trusted` | `boolean` | yes | | #### `workspace.set_trust` | Field | Type | Required | Description | |---|---|---|---| | `save` | `boolean` | | | | `trusted` | `boolean` | yes | | | `cwd` | `string` | yes | | Result: `object` ## Notifications (mare → client) ### `$/cancel_request` Cancels an outstanding mare-to-host request. Late replies to this ID are ignored. | Field | Type | Required | Description | |---|---|---|---| | `id` | `RequestId` | yes | | ### `dropped` Drop count for unretained `lossy` or refused events omitted from external stream consumers. | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string \| null` | | | | `session_epoch` | `string \| null` | | | | `count` | `integer ≥ 0` | yes | | ### `event` Envelope of an `event` notification: unified across RPC and headless streams. | Field | Type | Required | Description | |---|---|---|---| | `type` | `string` | yes | kernel event name, e.g. `turn/started`, `item/delta`, `item/completed`, `turn/completed` | | `session_id` | `string \| null` | | session the event belongs to | | `session_epoch` | `string \| null` | | opaque in-memory epoch identifier that rotates on every session create, load, or switch | | `seq` | `integer ≥ 0` | | per-session, per-epoch sequence number (1-based, contiguous) (default `0`) | | `turn_id` | `string \| null` | | run (prompt) the event belongs to — matches `agent.prompt` `turn_id` | | `ignorable` | `boolean \| null` | | whether a client that does not recognize this event type may skip it | | `data` | `any` | | | ### `fs/changed` | Field | Type | Required | Description | |---|---|---|---| | `watch_id` | `string` | yes | | | `changed_paths` | `string[]` | yes | | | `truncated` | `boolean` | | | ### `lagged` Sequence range omitted when an ordinary consumer cursor fell behind the bounded event log. | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string \| null` | | | | `session_epoch` | `string \| null` | | | | `from_seq` | `integer ≥ 0` | yes | | | `to_seq` | `integer ≥ 0` | yes | | ### `peer.message_status` `peer.message_status` notification (mare → peer): the receiving user's decision on a held message. | Field | Type | Required | Description | |---|---|---|---| | `message_id` | `string` | yes | | | `status` | `string` | yes | "delivered" \| "rejected" | | `reason` | `string \| null` | | | ### `snapshot` `snapshot` notification (mare → host): emitted immediately after an `events.subscribe` reply with `mode = "baseline"`, and immediately after `lagged` when a live cursor is evicted. | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string \| null` | | | | `session_epoch` | `string` | yes | | | `seq` | `integer ≥ 0` | yes | Ring tail sequence number `S` at the moment of the non-yielding cut; following events start at `S + 1`. | | `baseline_id` | `string \| null` | | Opaque handle for paging `parts` via `baseline.read`. | | `retained` | `object` | | Retained state (`events`, `status`, `queue`, `active_turn`, `active_items` skeletons, pending approvals/interactions). (default `{}`) | | `parts` | `string[]` | | Baseline parts available to page via `baseline.read` (e.g. `["entries", "active_items"]`). (default `[]`) | ### `stream.failed` `event` notification params — exactly one `mare -p --json` line. An event stream is incomplete and this connection will close. | Field | Type | Required | Description | |---|---|---|---| | `error` | `string` | yes | | ### `ui.editor_config` | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string \| null` | | | | `prompt` | `string \| null` | | | | `placeholder` | `string \| null` | | | | `busy_placeholder` | `string \| null` | | | | `border` | `string \| null` | | | ### `ui.editor_hint` | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string \| null` | | | | `text` | `string` | yes | | ### `ui.editor_state` | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string \| null` | | | | `text` | `string` | yes | | | `cursor` | `integer ≥ 0` | yes | | | `shell_mode` | `boolean` | | (default `false`) | | `image_markers` | `string[]` | | | | `attachments` | `UiEditorAttachment[]` | | | | `external_editor_running` | `boolean` | | (default `false`) | | `revision` | `integer ≥ 0` | yes | | ### `ui.markdown_changed` | Field | Type | Required | Description | |---|---|---|---| | `document_id` | `string` | yes | | | `source` | `string` | yes | | | `revision` | `integer ≥ 0` | yes | | | `render_seq` | `integer ≥ 0` | yes | | | `session_id` | `string \| null` | | | | `session_epoch` | `string \| null` | | | | `pending` | `integer ≥ 0` | yes | | | `enhanced` | `boolean` | yes | | | `supports_artifact_images` | `boolean` | yes | | | `diagnostic` | `string \| null` | | | | `node` | `any` | yes | Existing Node description. Image bytes become bounded canonical base64 `data`; no paths, callbacks, tokens, or userdata. Deserialize via mare.ui.node_from_wire in a Lua frontend. | | `expanded_node` | `any` | yes | Same Markdown document with each enhanced fence followed by its complete source. | ### `ui.notify` | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string \| null` | | | | `text` | `string` | yes | | | `level` | `string \| null` | | info \| success \| warning \| error | ### `ui.overlay` | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string \| null` | | | | `title` | `string` | yes | | | `node` | `any` | | | | `open` | `boolean` | yes | | | `context` | `string \| null` | | | ### `ui.set_editor` | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string \| null` | | | | `text` | `string` | yes | | | `keep_draft` | `boolean` | | (default `false`) | | `prepend` | `boolean` | | (default `false`) | ### `ui.status` | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string \| null` | | | | `status_id` | `string` | yes | | | `align` | `string` | yes | | | `order` | `integer` | | (default `0`) | | `keep` | `boolean` | | (default `false`) | | `node` | `any` | | | ### `ui.widget` | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string \| null` | | | | `widget_id` | `string` | yes | | | `slot` | `string` | yes | | | `order` | `integer` | | (default `0`) | | `node` | `any` | | | ### `ui/component-updated` | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string` | yes | | | `component` | `string` | yes | | | `payload` | `any` | | | ### `ui/select-closed` | Field | Type | Required | Description | |---|---|---|---| | `select_id` | `string` | yes | | ### `ui/select-updated` | Field | Type | Required | Description | |---|---|---|---| | `select_id` | `string` | yes | | | `items` | `UiSelectItem[]` | | | | `tabs` | `UiSelectTab[]` | | | ## Notifications (client → mare) ### `$/cancel_request` Cancels an outstanding mare-to-host request. Late replies to this ID are ignored. | Field | Type | Required | Description | |---|---|---|---| | `id` | `RequestId` | yes | | ### `callback.update` `callback.update`: client → server notification streaming a partial update for an in-flight `callback.call` request identified by `id`. | Field | Type | Required | Description | |---|---|---|---| | `id` | `RequestId` | yes | | | `partial` | `any` | yes | | ## Callbacks (mare → client requests) ### `approval.request` `approval.request` (mare → host): a tool call or a network host needs approval. No answer (timeout, disconnect, error, invalid result) counts as `deny`. | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string` | yes | session that needs approval | | `turn_id` | `string \| null` | | active turn id, when known | | `kind` | `string` | yes | "tool" or "network" | | `approval_id` | `string \| null` | | unique approval lifecycle id (pairs with `approval/requested` and `approval/resolved`) | | `tool_call_id` | `string \| null` | | tool call id (kind = tool) | | `tool` | `string \| null` | | tool name (kind = tool) | | `arguments` | `any` | | the call's arguments (kind = tool) | | `command` | `string \| null` | | shell command, when the tool runs one | | `diff` | `string \| null` | | proposed change (patch / edit), when the tool writes files | | `host` | `string \| null` | | host:port (kind = network) | | `cwd` | `string` | yes | | | `reason` | `string \| null` | | why approval is needed (from the policy vote) | | `side_effect` | `string \| null` | | "read" \| "write" \| "external" | | `unconfined` | `boolean` | | runs outside the local sandbox (MCP / RPC-host tools) (default `false`) | | `proposed_amendment` | `any` | | a rule the policy proposes for `allow_amend` (opaque to core) | | `requested_permissions` | `PermissionProfile \| null` | | Explicit permission increment requested by this tool call (read/write paths, network hosts). | | `scope` | `PermissionGrantScope \| null` | | Requested maximum lifetime, when this is a structured permission request. | Result: `ApprovalRequestResult` | Field | Type | Required | Description | |---|---|---|---| | `decision` | `ApprovalDecision` | yes | | | `permissions` | `PermissionProfile` | | Optional structured subset of the requested read/write/network increment. | | `scope` | `PermissionGrantScope` | | Lifetime of the grant: turn or session (the request remains an upper bound). | | `amendment` | `any` | | with `allow_amend`: the rule to persist (opaque to core) | | `reason` | `string \| null` | | shown to the model when denied | ### `callback.call` `callback.call`: server → client request invoking one contract callback on a registration the client holds. Arguments match the callback's params schema; result is checked against its result schema. | Field | Type | Required | Description | |---|---|---|---| | `registration_id` | `string` | yes | | | `callback` | `string` | yes | | | `session_id` | `string \| null` | | | | `turn_id` | `string \| null` | | | | `tool_call_id` | `string \| null` | | | | `caller_id` | `string \| null` | | | | `arguments` | `any` | yes | | Result: `any` ### `mcp.elicitation` `mcp.elicitation` (mare → host): an MCP server requested user input or URL confirmation. | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string` | yes | session that requested elicitation | | `turn_id` | `string \| null` | | active turn id, when known | | `server` | `string` | yes | | | `request_id` | `any` | | | | `mode` | `string \| null` | | | | `message` | `string` | | (default `""`) | | `requested_schema` | `any` | | | | `url` | `string \| null` | | | | `elicitation_id` | `string \| null` | | | | `_meta` | `any` | | | Result: `McpElicitationResult` | Field | Type | Required | Description | |---|---|---|---| | `action` | `McpElicitationAction` | yes | | | `content` | `any` | | | ### `ui.confirm` | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string \| null` | | | | `prompt` | `string` | yes | | | `default` | `boolean \| null` | | | Result: `UiConfirmResult` | Field | Type | Required | Description | |---|---|---|---| | `confirmed` | `boolean \| null` | | true/false when answered; null when cancelled or interrupted | | `reason` | `string \| null` | | Dismissal reason when cancelled (`"cancelled"` \| `"interrupted"`) | ### `ui.editor` | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string \| null` | | | | `title` | `string` | | (default `""`) | | `prefill` | `string` | | (default `""`) | Result: `UiTextPromptResult` | Field | Type | Required | Description | |---|---|---|---| | `text` | `string \| null` | | null when cancelled | | `reason` | `string \| null` | | Dismissal reason when cancelled (`"cancelled"` \| `"interrupted"`) | ### `ui.input` | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string \| null` | | | | `title` | `string` | | (default `""`) | | `placeholder` | `string` | | (default `""`) | | `default` | `string \| null` | | | | `secret` | `boolean` | | (default `false`) | Result: `UiTextPromptResult` | Field | Type | Required | Description | |---|---|---|---| | `text` | `string \| null` | | null when cancelled | | `reason` | `string \| null` | | Dismissal reason when cancelled (`"cancelled"` \| `"interrupted"`) | ### `ui.questions` | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string \| null` | | | | `title` | `string \| null` | | | | `questions` | `UiQuestionItem[]` | yes | | Result: `UiQuestionsResult` | Field | Type | Required | Description | |---|---|---|---| | `answers` | `map<string, UiQuestionAnswer>` | | (default `{}`) | | `dismissed` | `boolean \| null` | | | | `reason` | `string \| null` | | | | `note` | `string \| null` | | | ### `ui.select` | Field | Type | Required | Description | |---|---|---|---| | `session_id` | `string \| null` | | | | `select_id` | `string \| null` | | | | `title` | `string` | | (default `""`) | | `title_right` | `any` | | | | `body` | `any[]` | | Explanatory lines shown above the options (strings or wire `Node` objects). | | `items` | `UiSelectItem[]` | yes | | | `selected` | `integer ≥ 0` | | 0-based preselected index (default `0`) | | `multi` | `boolean` | | Allow checking multiple items before confirming. (default `false`) | | `accept_label` | `string \| null` | | | | `allow_search` | `boolean \| null` | | Defaults to true when omitted. | | `filter` | `string \| null` | | | | `tabs` | `UiSelectTab[]` | | | | `tab` | `integer ≥ 0` | | 0-based initial tab index (default `0`) | | `kind` | `string \| null` | | "list" \| "confirm" | | `keys` | `UiSelectKey[]` | | | | `vim` | `boolean \| null` | | | | `has_highlight` | `boolean \| null` | | | Result: `UiSelectResult` | Field | Type | Required | Description | |---|---|---|---| | `index` | `integer \| null` | | | | `selected_indices` | `integer ≥ 0[] \| null` | | 0-based checked item indices for a multi-select; an empty array is a valid answer. | | `tab` | `integer \| null` | | | | `key` | `string \| null` | | | | `filter` | `string \| null` | | | | `reason` | `string \| null` | | Dismissal reason when cancelled (`"cancelled"` \| `"interrupted"`) | ## Error codes An error's `data.code` says what failed and `data.data` carries its additional data. A service's own codes are `<service>.<name>`, declared by its contract (`services.list` shows them); anything else is `internal`. | `data.code` | number | meaning | |---|---|---| | `parse_error` | `-32700` | the message is not valid JSON | | `invalid_request` | `-32600` | the message is not a valid request | | `method_not_found` | `-32601` | no such method, or it is not exported to this caller | | `invalid_arguments` | `-32602` | the arguments do not match the method's schema | | `already_provided` | `-32000` | the service already has a provider | | `invalid_result` | `-32000` | the provider's result does not match the method's schema | | `internal` | `-32603` | an unexpected failure; the message is bounded and carries no raw error value | | `cancelled` | `-32800` | cancelled by the caller, an owner release or a shutdown | | `inactive_ctx` | `-32000` | the caller's context was disposed; it can no longer register anything | | `timed_out` | `-32000` | a deadline passed before the work finished | | `disconnected` | `-32000` | the connection that implements or awaits the call went away | | `denied` | `-32000` | not allowed for the connection this work runs for | | `unavailable` | `-32000` | the service or its provider is not available | | `unknown_session` | `-32000` | no session with that id | | `stale_session` | `-32000` | the session changed since the id was obtained | | `overloaded` | `-32000` | admission refused before the work started; try again later | | `busy` | `-32000` | the target cannot take the request now and it cannot be queued | | `unsupported` | `-32000` | no backend or model supports the requested capability | | `unsupported_version` | `-32000` | the protocol major version is not supported | | `request_id_conflict` | `-32000` | a request id was reused with different content | | `persist_failed` | `-32000` | durable session persistence failed | | `invalid_namespace` | `-32000` | the state namespace name is not valid | | `invalid_value` | `-32000` | the state value is not valid | | `read_only` | `-32000` | the state namespace is read-only here | | `lock_timeout` | `-32000` | the state lock was not acquired in time | | `corrupt` | `-32000` | the stored state cannot be read | | `revision_exhausted` | `-32000` | the state revision counter is exhausted | | `io` | `-32000` | the state could not be read or written | | `unknown_state` | `-32000` | the state outcome is unknown | | `baseline.stale` | `-32000` | the baseline handle is unknown, expired, superseded, completed, or from another session epoch | | `baseline.unknown_part` | `-32000` | the requested baseline part is not valid for this baseline | | `baseline.item_too_large` | `-32000` | a single baseline item exceeds the page byte budget | ================================================================================ Title: Slash commands Section: Reference URL: https://signalridge.github.io/mare/en/reference/slash-commands/ Markdown: https://signalridge.github.io/mare/raw/en/reference/slash-commands.md Source: docs/en/reference/slash-commands.md ================================================================================ # Slash commands Slash commands registered by the built-in plugins. Packages and your own plugins can add more; `/commands` lists what is available in a running session. > This page is generated from the code by `scripts/gen_docs.py`. Do not edit it by hand. | Command | Description | Aliases | |---|---|---| | `/add-dir` | Add a directory to the workspace (/add-dir <path>; no arg lists them) | | | `/agents` | Sub-agents, workflow members, jobs and other sessions | | | `/approval` | Independent approval policy: ask / never / untrusted | | | `/archive` | Archive this session and start a new one | | | `/btw` | Open or control an ephemeral side conversation (/btw [<question> \| back \| close]) | | | `/clone` | Duplicate this session into a new one | | | `/commands` | Browse slash commands; Enter runs one | | | `/compact` | Compact the conversation (/compact [focus]) | | | `/config` | Show options, their values and where each was set | `/settings` | | `/context [all]` | Show what the context is made of (/context all: per item) | | | `/continue` | Continue an interrupted turn (after a crash or kill) | | | `/copy` | Copy the last response (/copy N: the Nth-last) — a code block or the whole Markdown | | | `/debug` | Show recent log lines and the latest crash report | | | `/delete [path]` | Delete this session, or delete a session file by path | | | `/diff` | File changes by turn | | | `/doctor` | Check the installation, credentials, plugins and MCP servers | | | `/effort [level]` | Set reasoning effort (/effort [level] [--session]; lists the model's levels) | | | `/exit` | Exit mare | `/q`, `/quit` | | `/export` | Export the conversation as Markdown (/export [path]) | `/export-md` | | `/fork [pick]` | Fork into a new session from your latest message (/fork pick: choose one) | | | `/help` | Show commands and keyboard shortcuts | `/?`, `/h` | | `/hotkeys` | Show key bindings | | | `/init` | Analyze the codebase and create or update AGENTS.md | | | `/jobs` | Background jobs: view output or stop one | | | `/label` | Label the current point in the session tree (/label <text>; empty clears) | | | `/login` | Log in to a provider (/login [provider]) | | | `/logout` | Remove a provider's stored credentials (/logout [provider]) | | | `/lua [code]` | Run Lua in mare's running state (/lua [code]) (TUI local command) | | | `/mcp` | MCP servers (/mcp [filter], /mcp reconnect\|enable\|disable\|login\|logout\|tools <server>) | | | `/memory [add [--user] <text>]` | Show the instruction files (AGENTS.md) in effect; /memory add [--user] <text> | | | `/model [provider/id]` | Select model | | | `/name` | Name this session (/name <title>) | `/rename`, `/title` | | `/new` | Start a new session | `/clear` | | `/news` | Show the update notes of mare and the enabled plugins again | | | `/permission [read-only\|auto\|full-access\|log\|caps]` | Permission preset (read-only / auto / full-access) · /permission log · /permission caps | `/permissions` | | `/plugins` | Manage plugins or show the runtime tree | | | `/profile` | Startup timeline and plugin load times | | | `/reload` | Reload plugins (/reload [plugin]) or the configuration (/reload config) | | | `/resume` | Resume a session (/resume all · /resume search <text>) | `/sessions` | | `/retry` | Regenerate the last answer (the old one stays on its branch: /tree) | | | `/review [sha\|commit\|base\|changes\|instructions]` | Review code in a read-only session (/review [sha\|base <branch>\|<instructions>]) | | | `/rewind [turn]` | Restore files to before a turn (/rewind [turn]) | | | `/session` | Show session info (/session id copies the id) | | | `/show-reasoning` | Toggle showing full reasoning instead of “Thought for N s” | | | `/side` | Open or control an ephemeral side conversation (/side [<question> \| back \| close]) | | | `/skills` | Browse skills; Enter loads one | | | `/status` | Show version, model, session and working directory | | | `/statusline` | Choose the status bar's segments (saved) | | | `/terminal-setup` | Check this terminal's keys (Shift+Enter, Alt+Enter) and show how to fix them | | | `/theme [flavor]` | Pick the theme flavor (auto / dark / light / installed flavors) | | | `/tree` | Navigate the session tree (branch from any earlier point) | | | `/undo` | Rewind the conversation to before a prompt (/undo picks one; /undo N: the Nth-last); files stay — /rewind restores them | | | `/usage` | Token usage, cost and subscription quota for this session | `/cost` | | `/web` | List or switch search and fetch backends (/web [mode\|search\|fetch <val>]) | | | `/yolo` | Switch to full-access (no sandbox; explicit prompt rules and dangerous-command checks still ask) — /permission full-access | |