# poo — Complete Documentation Source: https://poo.douggo.com --- # Why poo? Many JS-written harnesses like [pi](https://pi.dev) promote a *self-improving* agent. `poo` promotes an **engineered agent**. Each approach fits different work. A self-improving harness fits when you want an agent that writes and loads its own extensions at runtime. `poo` fits when you want fixed capability boundaries, headless automation, or a custom Go binary. From one Go codebase, `poo` ships two deliverables: - A **headless CLI** (with an interactive [REPL](/getting-started/repl)) that runs sessions without a full terminal UI. - An **embeddable Go library** that a wrapping application links into its own binary. Unlinked packages cannot be reached at runtime. A read-only build omits `bash`, so no prompt or config can invoke a shell. ## The Extensibility Ladder Not every customization requires writing Go. `poo` separates operational configuration from structural capability across three layers: 1. **Drop-in manifests (no rebuild):** Extend an existing `poo` binary with declarative JSON/YAML files on disk: - [`cli-registry`](/capabilities/cli-registry) manifests to expose CLI tools through `call_cli` (and `find_tool` when a catalog grows large). - [`mcp.json`](/capabilities/mcp-servers) manifests for MCP servers and resource feeds. - [`feeds`](/capabilities/feeds-and-daemon) manifests for long-lived command streams that deliver events into a session. - [`skills`](/capabilities/skills) directories (`SKILL.md`) for on-demand procedural guidance. 2. **YAML profiles & prompt sections (no rebuild):** Shape behavior per project or role in `settings.yaml`. Compose profiles (`base`, `code`, `search`, or custom profiles), append or swap named prompt sections, and tune compaction strategies. You can also attach permission rules, asker chains, and `bwrap` sandboxing. 3. **Compile-time Go binary (`server.New`):** Use this layer when you need hard capability boundaries, custom tools, custom executors, or a bespoke wire server. Import `poo` as a library, wire your packages into `server.New`, and ship a single static binary. See [Build Your Own Binary](/extending/custom-binary). ## Stdlib-Only Core The core packages — `poo`, `poo/prompt`, `poo/decide`, and `poo/wire/protocol` — depend on the Go standard library only. `internal/depcheck` enforces this boundary in `go test`. Opt-in packages (YAML/TOML config, MCP SDK, QuickJS/Starlark codemode, SQLite, readline) live outside the core. Consumers embedding `poo` only pull in the dependencies they actually link. ## Explicit FSM & Closed Settle Reasons Agent loops built around `while True` and exception-driven control flow make wire protocols, session replay, and headless automation fragile. `poo` runs an explicit finite state machine: ``` idle → requesting → streaming → executing → compacting → settling → settled ``` Every run terminates with a closed, typed settle reason (such as completed, cancelled, turn/token/duration limit, or truncation). Runs never rely on a magic string printed to stdout or a control message mixed into the transcript. Tool calls are recorded as typed records with explicit outcomes, and the `finish` tool carries a schema-validated result. ## Non-Silent History `poo` enforces a single governing rule for transcripts: **nothing rewrites the model's view of history silently.** - The append-only session store preserves the full trajectory. - Compaction never mutates or drops older turns behind the scenes. Strategies like `summary`, `handoff`, `mine`, `pointer`, and `native` record a visible, typed replacement in the session log while leaving the underlying store intact. - The rendered system prompt is frozen for the length of a run so provider prompt caches remain valid. ## Proven on Evals Architecture claims only matter if the harness can drive models through real multi-step engineering tasks. `poo` ships both a 20-task local evaluation suite (`poo-eval`) and a [Harbor](https://github.com/harbor-framework/harbor) adapter (`evals/harbor`) for Terminal-Bench and SWE-bench. In head-to-head Terminal-Bench runs on locally hosted `glm-5.3-flash`, `poo` beat `pi` and tied `mini-swe-agent`. That is not an exhaustive benchmark across every frontier model, and results will vary by model and dataset. Still, it shows that `poo`'s explicit FSM, stateless shell contract, and compaction pipeline hold up under relentless autonomous runs. ## Further Reading - [Prior Art](/extending/prior-art) — exactly what `poo` copies and rejects from `mini-swe-agent` and `pi-durable`. - [Evals & Benchmarks](/reference/evals) — running `poo-eval` and the Harbor Terminal-Bench / SWE-bench adapter. - [Build Your Own Binary](/extending/custom-binary) — wiring custom tools, profiles, and conformance tests at compile time. --- # Install `poo` ships as a single static binary for Linux and macOS (`amd64` and `arm64`). ## Release script (recommended) Download the latest GitHub release binary, verify its SHA-256 checksum against `checksums.txt`, and install it to `~/.local/bin`: ```bash curl -fsSL https://raw.githubusercontent.com/sdougbrown/poo/main/install.sh | sh ``` To install into a different directory, set `BINDIR`: ```bash curl -fsSL https://raw.githubusercontent.com/sdougbrown/poo/main/install.sh | BINDIR=/usr/local/bin sh ``` If `BINDIR` is not on your `PATH`, the script prints the `export PATH=...` line to add to your shell profile. ## `go install` Requires **Go 1.26 or newer**: ```bash go install github.com/sdougbrown/poo/cmd/poo@latest ``` Pin a specific release tag by replacing `@latest` with `@vX.Y.Z`. ## Build from source Development uses [mise](https://mise.jdx.dev/) to pin Go 1.26 (see `mise.toml`): ```bash git clone https://github.com/sdougbrown/poo.git cd poo mise install mise exec -- go build -o poo ./cmd/poo ``` Run the vet and race-detector test suite to verify your checkout: ```bash mise exec -- go vet ./... mise exec -- go test -race ./... ``` ## Verify the installation `poo version` reports build information embedded in the binary. For a `go install ...@version` or release build, it shows the module version. For a checkout build, it shows the VCS revision, commit timestamp, and `modified` flag: ```bash poo version ``` For scripts or CI pipelines that need to pin or inspect the binary, pass `--json`: ```bash poo version --json ``` --- # Quickstart You can run a headless session in under a minute with either a local OpenAI-compatible server or a built-in cloud provider. ## Option A: Local OpenAI-compatible endpoint No settings file is required. Pass `--endpoint` and `--model-id` directly to `poo run`: ```bash poo run \ --endpoint http://localhost:4000/v1 \ --model-id gemma4 \ --context-limit 262144 \ --max-turns 8 \ --log session.jsonl \ "List the Go packages in this repository." ``` `poo` runs the session to completion, writes the structured transcript to `session.jsonl`, and exits with a code reflecting the settle reason. ## Option B: Built-in provider `poo` ships built-in provider records for OpenCode Console, Codex (`openai-codex`), and Ollama Cloud. Authenticate once with `poo login`: ```bash # Pick one: poo login opencode poo login codex poo login ollama-cloud ``` Credentials are stored in `poo`'s default credential file (`~/.config/poo/auth.yaml` on Linux, `~/Library/Application Support/poo/auth.yaml` on macOS). Once authenticated, assign a model to the [`roles.chat` role](/configuration/models-and-catalog#roles-and-required-operations) in your settings file: ```yaml # .poo/settings.yaml version: 1 profile: code roles: chat: opencode-go/glm-5.3 # or openai-codex/gpt-6.1-sol, or ollama-cloud/glm-5.3 ``` ## Starter settings files The repository includes annotated starter configs under `examples/`: | File | Use case | |---|---| | `examples/code.settings.yaml` | Local OpenAI-compatible endpoint (`gemma4`), `code` profile, `decide` asker, `bwrap` executor, `summary` compaction. | | `examples/sandboxed.settings.yaml` | `code` profile with guardrails: `unmatched: ask`, `bwrap` with `network: false`, `protected_paths`, `restrict_to_working_dir`, and `fetch` disabled. | | `examples/opencode.settings.yaml` | OpenCode Console gateway (`opencode-go/glm-5.3`), no `endpoints` or `models` block needed. | | `examples/codex.settings.yaml` | Built-in `openai-codex` provider with `native` compaction and model-family prompt guidance. | Copy one to `.poo/settings.yaml` in your project root (or `~/.config/poo/settings.yaml` as your user default), or pass it explicitly with `--settings`: ```bash poo run --settings examples/code.settings.yaml "Run go test ./... and summarize any failures." ``` ## Preflight with `poo roles` Before starting a session, verify that every [role](/configuration/models-and-catalog#roles-and-required-operations) in your settings resolves to a valid model and credential: ```bash poo roles ``` `poo roles` prints each assigned role, the provider serving it, and where that provider's credential comes from — without printing secrets or making network calls. If a role cannot resolve, it exits non-zero and lists the models that could serve it. ## Launch the interactive REPL With a settings file in place, run a bare `poo` to open the interactive REPL: ```bash poo ``` `poo` discovers settings automatically in order: `--settings`, `POO_SETTINGS`, `.poo/settings.{json,yaml,yml,toml}` walking up from the current directory, then your user config directory. See [Interactive REPL](/getting-started/repl) for slash commands and keybindings. ## Next Steps - **Tune reasoning effort and sampling** for custom or local models: [Reasoning & Sampling](/configuration/reasoning-and-sampling) - **Run async event feeds in a resident daemon**: [Feeds & Daemon](/capabilities/feeds-and-daemon) - **Add a CLI tool without rebuilding `poo`**: [CLI Registry & Script Tools](/capabilities/cli-registry) - **Lock down bash and filesystem access**: [Sandboxing (`bwrap`)](/operations/sandbox) --- # Interactive REPL `poo repl` is poo's terminal interface. It accepts the same flags as `poo serve`, launches `poo serve` as a subprocess, and connects to it over the JSON-RPC wire protocol. Replies render as Markdown with syntax-highlighted code blocks, and tool calls and results render as decorated blocks. ## Starting the REPL ```bash # Launch the default UI (repl) poo # Explicit subcommand with flags poo repl --profile code --working-dir ./my-repo ``` Running bare `poo` launches the interface configured by `ui` in settings (defaulting to `repl`). If no settings file exists yet, bare `poo` runs an interactive setup flow in the terminal to configure a sign-in and chat model. To use a different default profile in interactive sessions than in headless `poo run` / `poo serve` invocations, set `repl_profile` in your settings file. When stdin and stdout are both terminals, the REPL pins the input editor and statusline to the bottom. The transcript scrolls above them. When piped, it falls back to plain line-oriented I/O. ## Input Editing and Keybindings At a terminal, the REPL uses a readline editor in **vi insert mode** (`vi-insert`) and persists input history in `/poo/repl-history-v2`. ### Control Keys and Bash Chords | Key | Behavior | |---|---| | `Enter` | Submit the entire draft (including multi-line drafts). | | `Ctrl-J` | Insert a newline into the draft without submitting. | | `Esc` | Stop the active turn/run if working; switch to vi command mode (`vi-command`) when idle. | | `Ctrl-C` | Cancel the active run if working; clear the current draft if non-empty; exit the REPL (exit code `130`) when the prompt is empty. | | `Shift+Tab` | Cycle the chat model's reasoning level (same as `/thinking`). | | `Ctrl-A` | Jump to the beginning of the line. | | `Ctrl-E` | Jump to the end of the line. | | `Ctrl-B` | Move cursor back one character. | | `Ctrl-F` | Move cursor forward one character. | | `Ctrl-T` | Transpose the two characters before the cursor. | | `Ctrl-K` | Kill from the cursor to the end of the line. | | `Ctrl-U` | Clear from the cursor to the start of the line. | | `Ctrl-W` | Cut the word behind the cursor. | ### Steering an Active Run Submitting a regular message (not a slash command) during an active run sends a **steer** message (`run/message`). The session queues it and delivers it to the model at the end of the current turn. Slash commands other than `/bg` wait until the run settles. ## Slash Commands | Command | Description | |---|---| | `/model` | List available models in the catalog (numbered), marking the active chat model with `←`. | | `/model ` | Switch to an exact model name, or filter the catalog by fragment. A single match switches immediately; multiple matches print a ranked, numbered list. | | `/model ` | Switch to a model by number from the most recent `/model` or `/models` list. | | `/models` | Probe configured endpoints for what they currently serve, refresh the catalog, and list the models. Supports `/models ` and `/models `. | | `/thinking` | Cycle the reasoning level (`default`, `minimal`, `low`, `medium`, `high`, `xhigh`, `off`). Same as `Shift+Tab`. | | `/thinking ` | Set the reasoning level explicitly, or pass a token budget for budget-based models. `default` omits the reasoning field; `off` asks the model not to think. | | `/bg` | Move the currently running backgroundable tool call (such as `bash`) into a session background job without restarting it. | | `/less` | Open the session transcript in `less -R`. | | `/help` | Show the command list (aliases: `/h`, `?`). | | `/cancel` | Cancel the active run. | | `/quit` | Close the session and exit the REPL (aliases: `/q`, `/exit`). | ::: tip Backgrounding with `/bg` `/bg` only moves a call when exactly one backgroundable call is running. The promoted job survives run cancellation, but it keeps the original `bash` command timeout. For long-running work that needs the full job timeout, instruct the model to run it in the background from the start (so it launches with `background: true`). ::: ## Permission Prompts The REPL declares the `permission_answers` wire capability, so asks routed to the `wire` asker appear inline in the terminal: ```text ⚙ permission · bash rm -rf build/ allow bash? [y/N] ``` Type `y` or `yes` to allow the call. Any other input — including pressing `Enter` on an empty line or reaching EOF — denies the call. See [Permissions & Safety](/operations/permissions-and-safety) for configuring rules and askers. ## Statusline The statusline sits on the bottom row of the pinned footer (or inline before the prompt when no pinned footer is active) and displays: ```text ⌂ my-repo │ ⎇ main │ gpt-6 │ 🧠 medium │ ctx 12.4k/128k ``` - **Folder (`⌂`)** — basename of the session's working directory. - **Git branch (`⎇`)** — current branch or short commit hash when in a detached HEAD (omitted outside a git repository). - **Model** — active chat model name. - **Reasoning (`🧠`)** — active reasoning level (omitted when set to `default`). - **Context fill (`ctx`)** — input token count from the most recent request against the model's prompt limit. ## Continuing and Resuming Sessions Logged sessions can be reopened directly from the command line: ```bash # Reopen the most recently active unlocked session for the current directory poo repl --continue poo repl -c poo -c # Reopen a specific session by ID poo repl --resume poo --resume ``` Find session IDs with `poo sessions list`. When a session is reopened: - It retains the working directory, profile, and model recorded in its log. - The REPL renders up to the **newest 500 history items** as scrollback before the first prompt. None of the replayed scrollback is re-sent to the model. - If the previous process crashed, any recovery actions (such as a truncated tail or interrupted runs) are shown as a warning. - `--continue` skips sessions currently locked by another process. ### Refusals (Exit Code 2) The REPL refuses to start and exits with code `2` when: - Both `--continue` and `--resume` are passed together. - `--continue` finds no unlocked logged session matching the working directory. - `--ephemeral` or `session.mode: ephemeral` is active. - `--resume ` targets a session whose recorded working directory differs from the current one (resume from that directory or pass `--working-dir `). --- # Settings Discovery Every poo command loads a single settings file—there is no merging across project and user settings files. If discovery finds no file, poo runs on defaults that CLI flags can override. For the full list of supported keys, see the [Settings Reference](/reference/settings). ## Discovery Order Commands check these locations in order and stop at the first match: 1. **CLI flag (`--settings `)**: Uses the exact path given. If the file does not exist, poo fails immediately. 2. **Environment variable (`POO_SETTINGS`)**: Uses the exact path in `POO_SETTINGS`. If the file does not exist, poo fails immediately. 3. **Project directory (`.poo/`)**: Starts in the working directory (or current directory when empty) and walks up to the filesystem root, checking `/.poo/` at each level. 4. **User config directories**: - **Linux**: `$XDG_CONFIG_HOME/poo` when set, otherwise `~/.config/poo`. - **macOS**: `~/Library/Application Support/poo` first, then `~/.config/poo`. - **Windows**: `%AppData%\poo`. ::: tip Explicit paths are promises Missing files in `.poo/` or user config directories are skipped silently. A missing path passed via `--settings` or `POO_SETTINGS` always fails the command. ::: ## File Extension Priority & Formats Inside each searched directory, poo looks for these filenames in order: 1. `settings.json` 2. `settings.yaml` 3. `settings.yml` 4. `settings.toml` The first regular file found wins. A `settings.json` in the same directory shadows `settings.yaml`, `settings.yml`, and `settings.toml`. The file extension selects the parser: | Extension | Parser | |---|---| | `.yaml`, `.yml` | YAML | | `.toml` | TOML | | `.json` (or any other / no extension) | JSON | All three formats normalize to the same canonical JSON representation before decoding, so keys, types, and validation rules behave identically across JSON, YAML, and TOML. ## Strict Unknown-Key Rejection Settings are decoded strictly (`DisallowUnknownFields`). Any unrecognized key—or a key with the wrong value type—fails the load and names the offending field. Validation runs in two stages after decoding: 1. **Schema rules** (`config/schema/settings.umpire.json`): Enforces required fields (`version: 1`), value ranges and enums, mutual exclusions (such as `skills.default` vs `skills.user_path`, and `system_prompt.base_file` vs `system_prompt.replace`), and cross-field dependencies (such as `permission.decide.*` requiring `roles.decider`). 2. **Runtime checks**: Validates role names, permission rule structure, asker names, protected path globs, engine-specific limits, and the existence of referenced files (`system_prompt.base_file`, `finish.schema_file`, `session.user_prompt_file`, `pi_auth_file`). ### Legacy Key Aliases Three pre-v1 keys are still accepted and rewritten automatically when the current key name is absent: | Legacy key | Current key | Scope | |---|---|---| | `cliregistry` | `cli_registry` | Any depth | | `pi_models_file` | `models_file` | Any depth | | `base_url` | `endpoint` | Entries inside `endpoints` only | ## Relative Path Resolution Rules Absolute paths are always kept as-is. Leading `~` or `~/` expands to the current user's home directory (`$HOME`) across all path keys (`~user` is not expanded and is treated as a relative path). Relative paths resolve against different base directories depending on the key: ### Resolved against the settings file's directory These keys point to companion configuration files that travel with the settings file: - `models_file` - `auth_file` - `pi_auth_file` - `profiles_files` - `system_prompt.base_file` - `finish.schema_file` - `profiles..prompt_file` (when declared inline in the settings file) - `profiles..prompt_append_file` (when declared inline in the settings file) When `config.Parse` parses a settings document in memory with no file path, relative paths in these keys stay relative to the working directory. ### Resolved against the declaring profiles file's directory When a profile loads from an external file in `profiles_files`, these keys resolve against **that profiles file's directory** rather than the main settings directory: - `profiles..prompt_file` - `profiles..prompt_append_file` ### Resolved against the working directory These keys point to project-scoped manifests and guidance directories: - `cli_registry.paths` - `feeds.paths` - `mcp.paths` - `skills.paths` Leading `~` or `~/` in any of these lists resolves under the user's home directory instead of the working directory. ### Home expansion only (relative to process working directory) These keys expand a leading `~` or `~/` and otherwise pass through relative to the process working directory: - `session.dir` (defaults to `~/.local/state/poo/sessions`) - `session.user_prompt_file` - `skills.user_path` ### Default Companion File Discovery When optional companion keys are omitted, poo checks beside the settings file or in the platform user config directory: | Resource | Default behavior when omitted | |---|---| | `models_file` | Loads `models.yaml` or `models.json` beside the settings file (having both in the same directory is an error). | | `auth_file` / `pi_auth_file` | Uses `auth.yaml` or `auth.json` beside the loaded `models_file`, or `auth.yaml` (falling back to legacy `auth.json`) in the user config directory. On macOS, an existing `~/.config/poo/auth.yaml` (or `auth.json`) stands in when the native `~/Library/Application Support/poo/` file is absent. | | `cli_registry.defaults`, `feeds.defaults`, `mcp.defaults` | Enabled (`true`) by default; loads `cli-registry/`, `feeds/`, and `mcp/` from the user config directory (with `~/.config/poo/` fallback on macOS). | | `session.user_prompt` | Reads `AGENTS.md` from the native user config directory (`~/Library/Application Support/poo` on macOS). | --- # Models & Catalog poo resolves every model through a single catalog that merges built-in family rules, live endpoint discovery, a models file, and `settings.yaml`. Sessions and transports read the merged `ModelInfo` record from this catalog. ## Endpoints, Models, and Roles Configuration splits model setup into three blocks in `settings.yaml` (see [Settings Reference](/reference/settings)): - **`endpoints`** — where a server lives and how to reach it (`endpoint` base URL, `api_key_env` or `api_key`, optional `session_header`, `skip_probe`, `instructions_per_question`). - **`models`** — named model declarations that pair an endpoint name with a `model_id` and any model-specific overrides (`api`, `context_limit`, `input_limit`, `max_output`, `inputs`, `ops`, `tools_mode`, `reasoning`, `reasoning_levels`, `quirks`, `prompt_variant`). - **`roles`** — assigns a catalog model name to each job a session performs. ```yaml version: 1 endpoints: local: endpoint: http://localhost:4000/v1 api_key_env: LOCAL_API_KEY models: coder: endpoint: local model_id: qwen3-coder-30b context_limit: 131072 max_output: 16384 tools_mode: native roles: chat: coder compaction: local/qwen3-8b ``` A role can reference a model declared under `models` (`coder`) or a model provided by a models file or live discovery using its `/` name (`local/qwen3-8b`). ### Roles and Required Operations | Role | Purpose | Required `ops` | Required? | | :--- | :--- | :--- | :--- | | `chat` | Primary conversation and tool-calling turns | `chat` | Yes (session fails to build if unresolved) | | `decider` | Fast yes/no permission and state decisions (see [Decision Model](/capabilities/decision-model)) | `systemone` or `decisions` | Optional (warning if unresolved) | | `compaction` | Summarizing or reconstructing history during compaction (see [Context Compaction](/capabilities/compaction)) | `chat` | Optional (warning if unresolved) | If no layer sets `ops` on a model, the catalog defaults it to `[chat]`. Assigning a model that does not declare the operation a role needs (for example, assigning a `systemone`-only decider model to `chat`) is a configuration error. ## Catalog Layering Each model in the catalog is assembled from four layers merged in order. Later layers win **field by field** — setting one field in a higher layer leaves every other field from lower layers intact: 1. **`curated`** — family rules embedded in the binary (`gemma`, `qwen`, `minimax`), matched by `model_id` prefix. They supply family defaults such as `context_limit`, `ops`, `tools.mode`, `reasoning`, `temperature`, and `prompt_cache`. 2. **`discovery`** — what the endpoint reports when probed (OpenAI `/models`, llama.cpp server props, or Ollama model show). Results are cached at `/poo/discovery.json` with a 10-minute freshness TTL (`DefaultDiscoveryTTL`). Session builds read the local cache without blocking on network probes; `poo models` and `poo models --explain` reprobe live. Set `skip_probe: true` on endpoints that do not expose a model list. 3. **`models_file`** — endpoints and models declared in a models file, assembled in two steps: - First, the embedded `builtin-models.yaml` (or the file named by `POO_BUILTIN_MODELS`) when a credential file exists, gated to endpoints whose credentials are present. - Second, your `models.yaml` or imported pi `models.json` (set via `models_file` or auto-discovered beside `settings.yaml`), folded over the built-ins by name. 4. **`settings`** — `endpoints`, `models`, and top-level `sampling` in `settings.yaml`. Any field still unset after all four layers takes a catalog default (`default` layer): `api` defaults to the endpoint's `api` or `chat_completions`, and `ops` defaults to `[chat]`. For the full `models.yaml` schema, pi `models.json` import rules, and `POO_BUILTIN_MODELS` behavior, see [Models File Reference](/reference/models-file). For credential resolution and built-in providers, see [Providers & Auth](/configuration/providers-and-auth). ## Context, Input, and Output Limits poo distinguishes three token limits on a model: | Field | Meaning | Effect | | :--- | :--- | :--- | | `context_limit` | Total context window shared by prompt and response | Sizes the output room (`max_tokens`) and bounds prompt size when `input_limit` is unset | | `input_limit` | Largest prompt the endpoint accepts (when smaller than `context_limit`) | Caps the prompt budget used by compaction and model-switch checks (`min(context_limit, input_limit)`), while leaving `max_tokens` sized from `context_limit` | | `max_output` | Maximum tokens the model writes in one response | Sets the request's `max_tokens` ceiling | poo always computes and sends `max_tokens` rather than relying on an endpoint's hidden default. When `max_output` is unset or `0`, poo derives a default ceiling from `context_limit`: | `context_limit` | Default `max_output` | | :--- | :--- | | Unknown (`<= 0`) | `16384` | | `< 65536` | `8192` | | `65536` – `131071` | `16384` | | `>= 131072` | `32768` | Before sending a request, poo clamps `max_tokens` to the room remaining in `context_limit` after the estimated prompt and output reserve (floored at `1`). ## Inspecting the Catalog ### `poo models` and `poo models --explain` Run `poo models` to reprobe configured endpoints and print every available model: ```bash poo models poo models --json ``` To see every resolved field for one model and **which layer set it**, pass `--explain`: ```bash poo models --explain coder poo models --explain openai-codex/gpt-6.1-sol ``` Output shows `FIELD`, `VALUE`, and `LAYER` (`curated`, `discovery`, `models_file`, `settings`, or `default`), including nested fields such as `reasoning.mode`, `reasoning.param`, `reasoning.levels`, `tools.mode`, and `sampling.temperature`. Use this whenever a model behaves unexpectedly to see whether a value came from family defaults, a probe, a models file, or `settings.yaml`. ### `poo roles` Run `poo roles` to verify role resolution before starting a session: ```bash poo roles ``` It prints a table of `ROLE`, `MODEL`, `PROVIDER`, and `CREDENTIAL` (`env:`, `static`, or `none`) for `chat`, `decider`, and `compaction`: - Prints no secrets and triggers no token refresh. - Uses the same catalog resolution as a session build. - Exits non-zero if any assigned role cannot be resolved or does not serve the required operation. In that case, it lists the catalog models that could serve that role. --- # Reasoning & Sampling poo separates **how a model controls reasoning** from **what reasoning level a session requests**. You declare the control mechanism on the model definition, and set the requested level in `reasoning.chat`, CLI flags, or the REPL. ## Setting Reasoning Effort on a Custom Model A common mistake with custom models is setting `reasoning.chat: medium` without telling poo how the model accepts reasoning on the wire. Without a `reasoning` control on the model definition, poo treats the model as `mode: none` and refuses the setting with a configuration error. Setting reasoning effort on a custom model takes **two parts**: 1. **Declare the model's reasoning control** on the model entry in `settings.yaml` (or [models.yaml](/reference/models-file)). 2. **Select the active level** in `settings.yaml`, via `--reasoning-effort`, or interactively in the REPL. ```yaml # settings.yaml version: 1 endpoints: myserver: endpoint: https://api.example.com/v1 api_key_env: EXAMPLE_API_KEY models: custom-reasoner: endpoint: myserver model_id: my-reasoning-model context_limit: 131072 # Part 1: declare how this model accepts reasoning reasoning: mode: effort param: reasoning_effort # Optional: restrict accepted levels (lowest first) reasoning_levels: [off, low, medium, high] roles: chat: custom-reasoner # Part 2: select the active reasoning level reasoning: chat: medium ``` You can also set Part 2 per run or interactively: - **CLI (`poo run`)**: `--reasoning-effort medium`. When you pass a named effort level (`minimal`, `low`, `medium`, `high`, `xhigh`) on `--reasoning-effort`, `poo run` forces `reasoning: { mode: effort, param: reasoning_effort }` even if the model did not declare one. Passing `default` or `off` preserves the model's own reasoning control. - **REPL**: press `Shift+Tab` or run `/thinking` to cycle levels, or run `/thinking medium` (or `/thinking ` for budget models). See [Interactive REPL](/getting-started/repl). Verify the merged control on any model with `poo models --explain `. ## Reasoning Modes `reasoning.mode` declares how a model's thinking is controlled on the wire. Four modes exist: | Mode | Purpose | Default `param` if omitted | | :--- | :--- | :--- | | `none` | Model reasoning cannot be controlled (default when unset) | — | | `toggle` | Boolean on/off switch (common on local servers) | `chat_template_kwargs.enable_thinking` | | `effort` | Named effort level (`minimal`, `low`, `medium`, `high`, `xhigh`, or model-declared levels) | `reasoning_effort` | | `budget` | Positive integer token budget | `thinking.budget_tokens` | ### How Settings Map to Request Fields The table below shows what poo sends for each combination of `reasoning.chat` (or session level) and `reasoning.mode`: | Setting | `none` | `toggle` | `effort` | `budget` | | :--- | :--- | :--- | :--- | :--- | | `default` (or unset) | No field | No field | No field | No field | | `off` | No field | `: false` | Off word or quietest level (see below) | No field | | Named level (e.g. `high`) | Error | `: true` | `: ""` | Error | | Positive integer (e.g. `4096`) | Error | `: true` | Error | `: 4096` | - `default` always omits the reasoning field so the endpoint's own default applies. - `off` is accepted by every model: `toggle` sends `false`, `effort` sends the model's off word (or quietest level), and `none`/`budget` omit the field. ### Common `param` Spellings `reasoning.param` supports dot-separated paths, which poo encodes as nested JSON objects in the request body: | Backend / API | `mode` | `param` | Wire JSON sent | | :--- | :--- | :--- | :--- | | OpenAI-compatible Chat Completions | `effort` | `reasoning_effort` | `{"reasoning_effort": "medium"}` | | OpenAI Responses / Codex (`api: responses`) | `effort` | `reasoning_effort` | `{"reasoning": {"effort": "medium", "summary": "auto"}}` | | Local servers (llama.cpp, vLLM, SGLang) | `toggle` | `chat_template_kwargs.enable_thinking` | `{"chat_template_kwargs": {"enable_thinking": true}}` | | Anthropic Messages (adaptive effort) | `effort` | `output_config.effort` | `{"output_config": {"effort": "high"}, "thinking": {"type": "adaptive"}}` | | Anthropic Messages (token budget) | `budget` | `thinking.budget_tokens` | `{"thinking": {"type": "enabled", "budget_tokens": 4096}}` | Notes on transport behavior: - **Anthropic Messages (`api: anthropic_messages`)**: when `param` starts with `output_config.`, the transport automatically sets `thinking.type: "adaptive"`. When `param` starts with `thinking.`, it automatically sets `thinking.type: "enabled"`. - **Codex / Responses (`api: responses`)**: only accepts `mode: effort` with `param: reasoning_effort`. Toggle or budget controls on a Responses model return a configuration error. ## `reasoning_levels` and Off-Word Handling `reasoning_levels` lists the exact levels a model accepts, ordered **lowest first**: ```yaml reasoning: mode: effort param: reasoning_effort reasoning_levels: [none, low, medium, high, xhigh] ``` When `reasoning_levels` is set: - **Validation**: poo rejects levels outside the list (except `default` and `off`) instead of sending a value the server would ignore or reject. - **Verbatim spelling**: declared levels are sent as spelled (including custom names such as `max` or `none`). - **REPL cycling**: `/thinking` and `Shift+Tab` cycle through the model's declared levels. - **`off` resolution on `effort` models**: 1. If `reasoning_levels` contains `"off"` or `"none"`, poo sends that word verbatim (so an endpoint that spells off as `none` receives `"none"`). 2. If `reasoning_levels` is non-empty but contains neither `"off"` nor `"none"`, poo sends the first (quietest) declared level (e.g. `"low"`). 3. If `reasoning_levels` is empty, poo sends `"none"`. 4. On the Codex Responses transport, `off` is always translated to `reasoning.effort: "none"`. When switching models mid-session in the REPL, if the current reasoning level is not accepted by the new model, poo resets it to `off`. ## Per-Model Sampling poo supports four sampling parameters: `temperature`, `top_p`, `top_k`, and `min_p`. Unset parameters are omitted from requests so the endpoint uses its own defaults. Sampling is layered in two places: 1. **Model defaults** in [models.yaml](/reference/models-file) under `endpoints..models..sampling`. 2. **Per-model overrides** in `settings.yaml` under the top-level `sampling` map, keyed by catalog model name: ```yaml # settings.yaml sampling: local/qwen3-coder: temperature: 0.2 top_p: 0.9 top_k: 40 min_p: 0.05 ``` Overrides merge field by field over the model's defaults. - If a model's catalog temperature mode is `fixed` or `unsupported`, poo drops `temperature` even when an override sets it. - The Anthropic Messages transport sends `temperature`, `top_p`, and `top_k` (it does not send `min_p`). ## Transport Quirks `quirks` is an ordered list of named request-shaping and response-repair adaptations applied by the OpenAI-compatible Chat Completions transport. Set `quirks` on a model in `settings.yaml` or `models.yaml`: ```yaml models: local-audio: endpoint: sglang model_id: qwen-omni inputs: [text, audio] quirks: [think_tags, audio_url] ``` Shipped quirks: | Quirk | Phase | Behavior | | :--- | :--- | :--- | | `think_tags` | Response | Extracts `...` blocks from streamed text into structured thinking blocks | | `chat_template_thinking` | Request | Sets `chat_template_kwargs.enable_thinking: true` unless already claimed by the model's reasoning control | | `simplify_tool_schemas` | Request | Strips tool parameter JSON schemas down to `type`, `properties`, and `required` for servers with weak schema parsers | | `degenerate_stream` | Response | Detects and logs repetitive/degenerate output loops without interrupting the stream | | `text_tool_calls` | Response | Enables the text tool-call parser even when `tools_mode` is not `text` or `auto` | | `audio_url` | Request | Rewrites `input_audio` content parts to `audio_url` data URLs (needed by servers such as SGLang that mirror `image_url`) | Rules: - Quirks run in the order listed. - A quirk never overrides a request parameter already set by the model's `reasoning` or `sampling` controls. - Unknown quirk names are skipped with a warning rather than failing the request. ## Tool-Calling Modes (`tools_mode`) `tools_mode` controls how poo advertises tools and parses tool calls for a model: | Value | Behavior | | :--- | :--- | | `native` | Sends tool definitions on the wire and reads structured wire tool calls | | `text` | Describes tools in the system prompt and parses tool calls from response text | | `auto` | Sends tool definitions on the wire and falls back to parsing response text when the wire returns no tool calls | | `none` | Sends no tools | When `tools_mode` is `text` or `auto`, the OpenAI Chat Completions text parser supports `hermes`, `qwen_xml`, `mistral`, `json`, and `auto` formats (set by the curated catalog's `tools.text_format`, defaulting to `auto`). On the Anthropic Messages transport, `native`, `auto`, and unset all send native wire tools. --- # Providers & Auth `poo` separates **credentials** (OAuth tokens and API keys) from **endpoints** (URLs, wire APIs, and headers). Built-in providers activate automatically when a credential is available, and custom endpoints can speak OpenAI Chat Completions or Anthropic Messages. ## Credential Files & Resolution ### File Formats `poo` reads three credential file shapes and preserves the format it reads when writing back: 1. **`poo` versioned format (`auth.yaml`, default)** — YAML with a top-level `version: 1` and a `credentials` map. OAuth entries use the same field names as `pi`: ```yaml version: 1 credentials: openai-codex: type: oauth access: ... refresh: ... expires: 1767225600000 accountId: ... ``` A JSON file in this same versioned shape is read as the same document and written as YAML on the first write. 2. **Legacy `auth.json` and `pi`'s `auth.json`** — Unversioned JSON keyed directly by provider ID. An existing `auth.json` in `poo`'s config directory is read in place so prior sign-ins are not lost; renaming it to `auth.yaml` moves `poo` with it. When `pi_auth_file` points at `pi`'s `auth.json`, `poo` preserves `pi`'s JSON shape so `pi` can keep reading it. 3. **Codex CLI `auth.json` (read-only)** — Owned and refreshed by the Codex CLI. `poo` reads the access token's `exp` claim and never writes to the file (requires `auth_readonly: true`). ### Path Resolution & Platform Defaults Configure the credential path in settings with either `auth_file` or `pi_auth_file` (setting both is rejected): ```yaml # Keep credentials beside your settings file auth_file: auth.yaml ``` Relative paths resolve against the settings file's directory. When using `auth_file`, pass the same `--settings` path to `poo login`, `poo auth status`, and `poo auth refresh`. When neither `auth_file` nor `pi_auth_file` is set, `poo` resolves the credential file in this order: 1. **Beside a loaded models file** — If a `models_file` (or adjacent `models.yaml` / `models.json`) is loaded, `poo` looks beside it for `auth.yaml`, `auth.json`, or `pi`'s `auth.json` (beside `models.json`). 2. **Platform config directory**: - **macOS**: `~/Library/Application Support/poo/auth.yaml`. If absent, `poo` falls back to an existing `~/.config/poo/auth.yaml` without merging the two. If neither exists, `poo login` creates the native `Application Support` file. - **Linux & Windows**: `auth.yaml` in `poo`'s platform config directory (e.g. `~/.config/poo/auth.yaml` on Linux). ### Credential Precedence For API-key endpoints, `poo` resolves keys in strict order: 1. **Environment variable** named by the endpoint's `api_key_env` (highest precedence). 2. **Credential file** key entry matching that provider's environment variable (for example, an endpoint declaring `api_key_env: OLLAMA_API_KEY` reads the `ollama-cloud` key stored via `poo login ollama-cloud`). 3. **Literal `api_key`** written in settings or a models file (lowest precedence). ### Read-Only Mode (`auth_readonly`) Set `auth_readonly: true` when sharing a credential file managed by another tool: ```yaml auth_file: ~/.codex/auth.json auth_readonly: true ``` In read-only mode, `poo` never writes to the file: `poo login`, `poo auth import`, `poo auth refresh`, and token refreshes during sessions are all refused. If the access token expires, `poo` returns an error directing you to refresh with the owning tool. ## Built-in Providers Built-in provider definitions ship in `builtin-models.yaml` (override the embedded file with `POO_BUILTIN_MODELS=/path/to/file.yaml`). A built-in provider's models appear in the catalog once a credential for it is in reach. Models declared in `models_file` or settings `models` always win on name collisions. See [Models & Catalog](/configuration/models-and-catalog) for layering details. | Provider | Sign-in command | Auth method / Env var | Wire API | Probed | | :--- | :--- | :--- | :--- | :--- | | `openai-codex` | `poo login codex` | OAuth (`chatgpt.com/backend-api`) | `responses` | No | | `ollama-cloud` | `poo login ollama-cloud` | Key / `OLLAMA_API_KEY` | `chat_completions` | Yes | | `opencode` / `opencode-go` | `poo login opencode` | Key / `OPENCODE_API_KEY` | `chat_completions` | Yes | | `opencode-anthropic` / `opencode-go-anthropic` | `poo login opencode` | Key / `OPENCODE_API_KEY` | `anthropic_messages` | Yes | | `typesafe` | `poo login typesafe` | Key / `TYPESAFE_API_KEY` | Decisions (`ops: [systemone]`) | No | ::: tip Key input security Key-based `poo login ` flows prompt interactively (with hidden input) or read a single line from `stdin`. There is no `--key` flag, keeping secrets out of shell history and process lists. ::: ### OpenAI Codex (`openai-codex`) `openai-codex` uses OAuth against `https://chatgpt.com/backend-api` with `api: responses` and `skip_probe: true`. `poo` pins the OAuth credential strictly to that endpoint and refuses to send it anywhere else. Codex models serve `chat` turns and cannot be assigned to `decider`. ```yaml roles: chat: openai-codex/gpt-6.1-sol ``` **Sign in:** ```sh poo login codex ``` `poo login codex` (or `poo login openai-codex`) opens your browser and listens on a loopback callback port (default timeout: 5 minutes, adjustable with `--wait `). Pass `--force` to replace an existing credential without prompting. For headless or remote machines, use `--no-browser`: ```sh poo login codex --no-browser ``` Open the printed URL on a machine with a browser, then paste the full final redirect URL back into the terminal (including its `state` query parameter; a bare authorization code is rejected). **Background token refresh (`poo auth refresh`):** `poo auth refresh` checks the same credential file that sessions use and refreshes `openai-codex` when the access token has 5 minutes or less remaining. It prints nothing on success, exits non-zero on failure, and makes no model request. ```sh poo auth refresh --settings /abs/path/to/settings.yaml --leeway 30m ``` - Use `--leeway ` (e.g. `30m`) to refresh earlier. - Use `--force` for manual one-off refreshes regardless of expiry. - For idle or daemonized agents, run `poo auth refresh` from a `systemd` user timer or `launchd` job with an absolute `--settings` path. Schedule the timer more frequently than `--leeway`, and **do not** pass `--force` on a timer. If OpenAI revokes the refresh grant, you must run `poo login codex` again. **Importing from `pi` (`poo auth import pi`):** ```sh poo auth import pi [--from /path/to/auth.json] [--force] ``` Copies the `openai-codex` OAuth credential from `--from`, then `pi_auth_file`, then `~/.pi/agent/auth.json` into `poo`'s credential file without modifying `pi`'s file. ::: warning One-way door OAuth refreshes rotate the refresh token, so only one tool can own a grant's refresh lifecycle. After `poo`'s first refresh, `pi`'s copy becomes stale; if `pi` refreshes first, `poo`'s copy stops working. Run one tool per grant, not both. ::: **Sharing Codex CLI's credential:** To reuse a sign-in owned by the Codex CLI without conflicting refreshes, point `auth_file` at `~/.codex/auth.json` and enable `auth_readonly: true`. Run the Codex CLI to refresh when expired. ### Ollama Cloud (`ollama-cloud`) ```sh poo login ollama-cloud ``` Stores an API key for `https://ollama.com/v1` (also reachable via `OLLAMA_API_KEY`). `poo` probes the endpoint immediately after login so the live model list is ready for your first session, and refreshes it on `poo models` or `/models`. Reference models as `ollama-cloud/`: ```yaml roles: chat: ollama-cloud/glm-5.3 ``` ### OpenCode (`opencode`, `opencode-go`, and Anthropic Messages siblings) ```sh poo login opencode ``` Stores a single OpenCode Console key (`OPENCODE_API_KEY`) shared across four built-in endpoints (your workspace plan determines which endpoints bill it): - **Chat Completions**: `opencode` (`https://opencode.ai/inference/openai/v1`) and `opencode-go` (`https://opencode.ai/inference/go/openai/v1`) - **Anthropic Messages**: `opencode-anthropic` (`https://opencode.ai/inference/anthropic/v1`) and `opencode-go-anthropic` (`https://opencode.ai/inference/go/anthropic/v1`), configured with `api: anthropic_messages` ```yaml roles: chat: opencode-go/glm-5.3 # Or use the Anthropic Messages sibling: # chat: opencode-go-anthropic/claude-haiku-5-5 ``` All four endpoints probe the gateway's live model list and declare `session_header: x-opencode-session`, which causes `poo`'s transports to attach the session ID on every turn, fork, and compaction request. The Anthropic Messages transport handles content blocks, streamed tool call arguments, thinking blocks with preserved signatures, adaptive effort (`output_config.effort`), and token thinking budgets. ### TypeSafe (`typesafe`) ```sh poo login typesafe ``` Stores a TypeSafe Console key (`TYPESAFE_API_KEY`) for `https://api.typesafe.ai/v1`. TypeSafe serves Jev decision models (`jev-latest`, `jev-preview`) that declare `ops: [systemone]` — they answer `decider` queries and cannot serve `chat` turns. See [Decision Model](/capabilities/decision-model). ```yaml roles: chat: opencode-go/glm-5.3 decider: typesafe/jev-latest ``` The built-in endpoint sets `instructions_per_question: true` (folding framing into each question because the API rejects request-level `instructions`) and `skip_probe: true` (its model list is not OpenAI-shaped). To add a newer Jev model before a binary release, declare it under `models` on the `typesafe` endpoint with `ops: [systemone]`. ## Custom Endpoints Declare custom OpenAI-compatible or Anthropic Messages servers under `endpoints` and `models` in settings (or in a [Models File](/reference/models-file)): ```yaml endpoints: local-vllm: endpoint: http://localhost:8000/v1 api_key_env: LOCAL_VLLM_KEY anthropic-gateway: endpoint: https://gateway.example.com/anthropic/v1 api_key_env: GATEWAY_API_KEY session_header: x-session-id skip_probe: true models: local-qwen: endpoint: local-vllm model_id: Qwen/Qwen3-32B api: chat_completions gateway-claude: endpoint: anthropic-gateway model_id: claude-sonnet-4-5 api: anthropic_messages roles: chat: gateway-claude ``` ### Endpoint Fields | Field | Type | Description | | :--- | :--- | :--- | | `endpoint` | `string` | Base URL for the provider API (required). | | `api_key_env` | `string` | Environment variable holding the API key (checked before credential files and `api_key`). | | `api_key` | `string` | Literal API key fallback when `api_key_env` is unset. | | `session_header` | `string` | HTTP header name carrying the session ID on turns, forks, and compactions. | | `skip_probe` | `bool` | Skip `GET /models` discovery when the endpoint does not expose an OpenAI-compatible model list. | | `instructions_per_question` | `bool` | Fold decider framing into each question instead of sending a request-level `instructions` field. | ### Wire APIs (`api`) Each model (or endpoint in a models file) selects its wire transport with `api`: - `chat_completions` (default when omitted) — OpenAI Chat Completions API. - `anthropic_messages` — Anthropic Messages API (content blocks, streaming tools, thinking signatures, effort/budget controls). - `responses` — OpenAI Responses API (used by the built-in `openai-codex` transport). See [Wire API Mapping](/reference/wire-api-mapping) for exact request/response field mappings across transports. ## Verification Workflow Run these two read-only checks before starting a session. Neither prints secrets nor trades tokens. ### Check Stored Credentials (`poo auth status`) ```sh poo auth status [--settings /path/to/settings.yaml] [--json] ``` Reports the resolved file path, format (`poo`, `pi`, or Codex CLI), provider, OAuth client ID (if recorded), account ID, expiry timestamp, and state: - `live` — Ready to use as-is (always `live` for API keys). - `refresh needed` — OAuth access token is expired or within leeway; `poo` will refresh it on use or on `poo auth refresh`. - `no readable expiry` — OAuth token has no readable `exp` claim. - `expired (read-only: refresh with the tool that owns the file)` — Expired token in an `auth_readonly: true` file. Pass `--json` for machine-readable output (`file`, `format`, `provider`, `client_id`, `account_id`, `expires`, `state`). ### Verify Role Resolution (`poo roles`) ```sh poo roles [--settings /path/to/settings.yaml] ``` Builds the catalog the same way a session does and prints each [role](/configuration/models-and-catalog#roles-and-required-operations) (`chat`, `compaction`, `decider`) with its resolved `MODEL`, `PROVIDER`, and `CREDENTIAL` source (`env:`, `static`, or `none`). Exits non-zero if any assigned role fails to resolve, listing candidate models that would satisfy it. ## Related Pages - [Settings Discovery](/configuration/settings-discovery) - [Models & Catalog](/configuration/models-and-catalog) - [Wire API Mapping](/reference/wire-api-mapping) - [Decision Model](/capabilities/decision-model) - [CLI Reference](/reference/cli) --- # Profiles & Prompts A profile defines the tool set, default permission stance, prompt guidance, and manifest defaults a session starts with. The system prompt is assembled from named markdown sections that can be overridden per profile, in settings, or via CLI flags. ## Built-in profiles Select a profile with `--profile`, the top-level `profile` setting, or `session/create.profile` over the wire protocol. The default is `code`. | Profile | Tools | Unmatched side-effecting calls | Notes | | --- | --- | --- | --- | | `base` | none | policy default | Minimal contract; useful for pure chat or as a base for custom profiles. | | `code` | `bash`, `read`, `grep`, `history`, `edit`, `write`, `fetch`, `codemode` | `allow` | Default profile. Ships coding-agent guidance in its `profile` section. | | `search` | `read`, `grep` | `allow` | Read-only exploration profile. | Additional tools are attached automatically when applicable: - `jobs` and `cancel_job` are added by the core whenever a profile links a tool that supports background execution (such as `bash`). - `finish` is added when `finish.schema_file` is configured. ## Disabling tools globally Use `tools.disabled` to strip tools from every profile a settings file runs under: ```yaml tools: disabled: [codemode, fetch] ``` - Naming a tool the active profile does not offer is ignored. - Naming a tool the binary does not link, or a core-managed tool (`jobs`, `cancel_job`, `finish`), is an error. - Disabling every tool a selected profile offers is an error, and such a profile is omitted from the binary's profile list. ## Named profiles Define custom profiles under `profiles` in your settings file, then select them by name anywhere a profile is accepted: ```yaml profiles: reviewer: base: code prompt_file: prompts/reviewer.md prompt_append: Focus on correctness and regressions. model_family: true feeds: [apron-room] feeds_defaults: false cli_registry_defaults: false mcp_defaults: false mcp_servers: [github] tools: disabled: [edit, write, bash, codemode] ``` ### Profile fields | Field | Type | Behavior | | --- | --- | --- | | `base` | string | Required. Names a built-in linked profile or another defined profile. | | `prompt_file` | string | Absolute path, `~/...`, or path relative to the settings file (or profiles file). Read when opening a new session, not when listing profiles. Replaces the `profile` prompt section without replacing `base` or tool sections. | | `prompt_append` | string | Inline text appended to the `profile` section after the base's prose (or after `prompt_file` if both are set). Mutually exclusive with `prompt_append_file`. | | `prompt_append_file` | string | File form of `prompt_append`, resolved against the same directory as `prompt_file`. Mutually exclusive with `prompt_append`. | | `model_family` | bool | Off unless set to `true`. Enables the `family` prompt section keyed by the chat model's `prompt_variant` (ships `gpt-5.6`, `gpt-6`, and `gpt-6.2`). An unknown or unset variant leaves the prompt unchanged. | | `feeds` | list of strings | Feed manifest names this profile declares it needs; adds to the base's feeds (deduplicated). This is a presence assertion, not a filter: `feeds.paths` still controls which feeds load, and every loaded feed runs. A declared feed that is not loaded is skipped with a warning rather than failing the session. | | `feeds_defaults` | bool | Overrides `feeds.defaults` for sessions under this profile. Omitting it keeps the top-level setting. | | `cli_registry_defaults` | bool | Overrides `cli_registry.defaults` for sessions under this profile. Omitting it keeps the top-level setting. | | `mcp_defaults` | bool | Overrides `mcp.defaults` for sessions under this profile. Omitting it keeps the top-level setting. | | `mcp_servers` | list of strings | [MCP servers](/capabilities/mcp-servers) this profile's sessions start, by server name; adds to the base's selection (deduplicated, first-appearance order). `mcp.paths` still controls which manifests load; a selected server that is not loaded is skipped with a warning, and no server starts without a selection. | | `tools.disabled` | list of strings | Tool exclusions added on top of global `tools.disabled`. Exclusions do not alter [permission rules](/operations/permissions-and-safety) or sandbox the remaining tools. | An explicit `system_prompt.replace`, or a `system_prompt` rule that sets or removes the `profile` section, takes precedence over `prompt_file`, `prompt_append`, and `prompt_append_file`. A resumed session keeps the prompt recorded in its log once it has run. ## Layering with `profiles_files` To keep large profile definitions out of your main settings file, move them into separate files listed under `profiles_files`: ```yaml profiles_files: - profiles.yaml - team/profiles.yaml ``` Each file uses the same vocabulary under a top-level `profiles` key: ```yaml profiles: slim: base: code feeds_defaults: false cli_registry_defaults: false mcp_defaults: false ``` - **Format:** Determined by file extension — YAML (`.yaml` / `.yml`) or JSON (`.json`). - **Strict validation:** Unknown keys, unreadable files, or a file declaring zero profiles fail the load. - **Precedence:** The settings file's own `profiles` map wins over `profiles_files`. Within `profiles_files`, the first file that defines a profile name wins over later files. - **Path resolution:** Relative entries in `profiles_files` resolve against the settings file's directory. Relative `prompt_file` and `prompt_append_file` paths inside a profiles file resolve against that profiles file's own directory, so a profiles file travels with its prompts. ## REPL default profile (`repl_profile`) `repl_profile` sets the profile used by the [interactive REPL](/getting-started/repl) when invoked without `--profile`: ```yaml profile: code repl_profile: reviewer ``` - Scoped to the REPL only: `poo run` and `poo serve` continue to use `--profile` or the top-level `profile` setting. - Applies only when the REPL starts a new conversation; a reopened session runs under the profile recorded in its session log. - Must name a profile known to the binary. ## System prompt sections (`system_prompt`) The system prompt is composed from named sections rendered in this order: 1. `persona` — single-line identity header 2. `base` — core operating contract 3. `profile` — active profile's instructions 4. `family` — model-family guidance (when `model_family: true`) 5. `tools` — per-tool sections (`tools.`) in tool offer order 6. `catalog` — [CLI registry](/capabilities/cli-registry) catalog (when applicable) 7. `skills` — [skills](/capabilities/skills) catalog 8. `environment` — working directory, OS, and session date (`YYYY-MM-DD`) 9. `user` — operator instructions (`session.user_prompt` / `session.user_prompt_file`) 10. `project` — project instructions (`session.project_prompt`) 11. Custom sections added via `system_prompt.sections` (in insertion order) Configure overrides under `system_prompt`: ```yaml system_prompt: base_file: prompts/base.md append: Always cite file paths with line numbers. sections: style: Keep answers under five sentences. remove: - environment ``` | Field | Behavior | | --- | --- | | `base_file` | Replaces the `base` section with the file's contents. Relative paths resolve against the settings file; `~/` resolves under the home directory. Mutually exclusive with `replace`. CLI override: `--system-prompt`. | | `replace` | Replaces the entire prompt with literal text, dropping the default sections. Mutually exclusive with `base_file`. | | `append` | Appends text to the `base` section. CLI override: `--append-system-prompt` (prefix with `@` to read from a file). | | `sections` | Map of `name: text` entries that replace an existing section or append a new custom section. | | `remove` | List of section names to drop. Removing a section that is not present is a no-op. | For embedding-level prompt customization with Go `fs.FS`, see [Custom Tools & Prompts](/extending/custom-tools-and-prompts). ## Project and user instructions ### `session.project_prompt` Enable per-project instructions with `session.project_prompt: true` (or `--project-prompt`): ```yaml session: project_prompt: true ``` - Reads `AGENTS.md`, or `CLAUDE.md` if `AGENTS.md` is absent, from the session's working directory only — it never walks up to parent directories. - Populates the `project` section and is read per session from that session's working directory. - Capped at 64 KiB (`65536` bytes); longer files are truncated at a UTF-8 rune boundary with a truncation notice. - A directory with neither file adds no section; an unreadable or non-regular file is an error. ### `session.user_prompt` and `session.user_prompt_file` Add operator-level instructions that apply across projects to the `user` section: ```yaml session: user_prompt: true # Or point to an explicit file (enables user instructions on its own): # user_prompt_file: ~/.config/poo/my-instructions.md ``` - Read once when building the runtime, not per session. - `session.user_prompt: true` reads `AGENTS.md` from poo's platform config directory. If that default file does not exist, it is silently skipped. - `session.user_prompt_file` (or `--user-prompt-file`) names an explicit file (supports `~/`) and enables user instructions without setting `session.user_prompt: true`. Because an explicit path is a promise, a missing file fails the build. - Precedence: `--user-prompt-file` > `session.user_prompt_file` > `session.user_prompt`. ## Inspecting the rendered prompt Run `poo prompt` to print the exact rendered system prompt a session would send to the model: ```bash poo prompt --profile code --project-prompt ``` Pass `--pretty` for human-readable output with `---
---` headers and a compact skill summary instead of the raw `` XML: ```bash poo prompt --pretty --profile reviewer ``` `poo prompt` honors `--settings`, `--profile`, `--project-prompt`, `--user-prompt-file`, `--system-prompt`, and `--append-system-prompt`, and works without a configured chat model. --- # Feeds & Daemon Most agent harnesses only move when a user types a prompt. `poo` can also run **feeds** — long-lived external commands or MCP resource subscriptions that push asynchronous inputs into a session as `feed:`. Paired with `poo daemon`, a session becomes a durable, lease-backed resident process that sleeps while idle, wakes when something happens, and resumes across restarts. ## What feeds are A feed is a source that runs beside a session and emits messages into it. Feeds come in two forms: - **Command feeds** (declared in `feeds` manifests): long-lived processes started through the session's executor whose stdout carries one JSON message per line. - **MCP resource feeds** (declared in `mcp.json`'s `poo` block): subscriptions to an MCP server's `resources/subscribe` URI that drain updates into the same delivery and filter pipeline. See [MCP Servers](/capabilities/mcp-servers) for server setup and relaunch behavior. Every feed input is delivered to the model as untrusted outside input wrapped in a `` XML element: ```xml Tests failed in pkg/auth; should I revert the fixture change? ``` - `name` is the feed's label: `` for always-on or unscoped feeds, or `[=]` for scoped optional subscriptions. - `from` is omitted when the message has no sender. - `&` and `<` are escaped in the text body (and `"`, `\n`, `\r` in attributes) so payload content cannot close the element. - Lifecycle transitions are recorded as `feed.started` and `feed.ended` in the [session log](/reference/session-log-v0). ### Command feed stdout protocol A command feed writes one JSON object per line to stdout: ```json {"text": "PR #42 has a new review comment.", "from": "alice"} ``` A message may attach an image beside its text, or send an image alone with `text` omitted: ```json {"text": "Build dashboard snapshot", "image": {"path": "shot.png", "media": "image/png"}} ``` Protocol rules: - `text` is required unless `image` is present. `from` is optional; `id` is reserved and ignored; unknown fields are ignored; blank lines are skipped. - Maximum line length is **1 MiB**. - `image.path` is required (relative paths resolve against the feed command's working directory). `image.media` is optional; when present, the file's magic bytes must match it. Images are capped at **5 MB** and refused if unreadable, mismatched, oversized, or if the session's model does not accept image input. - Protocol violations fail the attempt immediately, including malformed JSON, lines over 1 MiB, missing text or image, and refused inputs. `poo` stops the command, discards remaining output, and reaps the process. - Stderr is written to the session's structured log (up to **64 KiB** per attempt) and never shown to the model. ## Feed manifests Feed manifests are JSON, YAML (`.yaml`/`.yml`), or TOML (`.toml`) files loaded from `feeds.paths`, `$XDG_CONFIG_HOME/poo/feeds/` (unless disabled), `POO_FEEDS_PATH`, and `--feeds-path`. ```json { "version": 1, "feeds": { "inbox": { "description": "Messages from the team queue.", "command": ["my-cli", "inbox"], "env": { "QUEUE_URL": "env:QUEUE_URL", "SESSION_ID": "session:id", "QUEUE_MODE": "batch" }, "restart": true, "on_idle": "wake", "max_pending": 32 } } } ``` Key fields: - `version`: must be `1`. - Feed name: matches `^[a-z0-9][a-z0-9_-]*$` and must be unique across all loaded feed manifests and MCP resource feeds. - `command`: required argv array. - `description`: rendered in the jobs prompt so the model knows what each feed provides. - `env`: added on top of the CLI registry's benign environment variables (never inheriting variables scrubbed by `tools.env.scrub`). Values may be literals, `env:NAME` (from the scrubbed host environment), `session:id` (the session's native ID, preserved across resumes), or `scope:NAME` (for optional feeds). Unresolved references fail the attempt before the command starts. - `max_pending`: caps undelivered queued inputs for the feed (default `16`). Past the cap, the oldest undelivered input is dropped unread. See the [Manifests Reference](/reference/manifests#feed-manifests) for the complete schema and validation rules. ## Restart policy Set `"restart": true` to restart a command feed after its process exits or hits a protocol failure: - Backoff starts at **1s** and doubles on each consecutive exit or failure, capped at **60s**. - An attempt that stays up for **60s or longer** resets the backoff timer. - `cancel_job` and session close always cancel any pending restart. - **Exception:** if a [command filter](#command-filter-external-script) fails, the feed is **suspended** and does not restart regardless of `restart`. ## Idle wake behavior `on_idle` controls whether a feed input can start a new run when the session is idle: | `on_idle` | Behavior when session is idle | |---|---| | `wake` | Starts a new run to handle the incoming feed message. | | `hold` | Queues the message until a run is already active. | | *(omitted)* | Inherits `jobs.on_idle` for always-on feeds; defaults to `hold` for `optional: true` feeds. | Whenever a run starts (from a `wake` feed, a background job, or client input), it drains all queued inputs — including held ones. To guard against runaway autonomous loops, set `jobs.max_unattended_wakes` in settings to cap consecutive woken runs with no client input in between (`0` disables the cap). ## Optional feeds (`subscribe_feed` and `cancel_job`) A feed marked `"optional": true` does not start when the session opens. Instead, the model starts instances on demand with `subscribe_feed` and stops them with `cancel_job`. Optional feeds can declare a `scope` — string fields (with optional regex `pattern`s) that the model supplies when subscribing and that bind into `env` via `scope:`: ```json { "version": 1, "feeds": { "git-feedback": { "description": "Feedback on one repository's pull requests.", "command": ["git-feedback", "--watch"], "optional": true, "scope": { "url": {"type": "string", "pattern": "^https://"} }, "env": { "GIT_FEEDBACK_URL": "scope:url" }, "on_idle": "wake", "restart": true } } } ``` How subscriptions work: - **Starting an instance:** the model calls `subscribe_feed` with `{"feed": "git-feedback", "scope": {"url": "https://github.com/org/repo"}}`. Scope values are validated against the manifest schema; missing fields, unknown fields, or pattern mismatches are returned as tool refusals. - **Origin and job ID:** scoped instances are identified as `feed:[=]` with fields sorted by name and values query-escaped (e.g., `feed:git-feedback[url=https%3A%2F%2Fgithub.com%2Forg%2Frepo]`). Unscoped optional feeds use `feed:`. - **Idempotency:** subscribing to the same feed and scope reaches the existing instance instead of starting a duplicate. If the instance was stopped or suspended, `subscribe_feed` starts it again. - **Instance cap:** a session runs at most **8** feed instances at once (counting running, restarting, and suspended instances). A ninth distinct subscription is refused until one is stopped with `cancel_job`. - **Inspecting and stopping:** `jobs` lists all running and suspended feeds with tool type `feed`. `cancel_job` accepts the feed's job ID (`feed:` or `feed:[...]`) and stops it. See [Built-in Tools & Jobs](/capabilities/tools-and-jobs). - **Reload behavior:** when a session reloads, always-on feeds start automatically. **Durable** sessions also restore active optional subscriptions from the session log; **logged** sessions do not (the model must call `subscribe_feed` again). ## Filtering before delivery A feed's `filter` block screens records before they enter the session queue. A manifest may configure either a **question filter** or a **command filter**, never both. ### Question filter (decision model) A question filter asks the session's [decision model](/capabilities/decision-model) a yes/no question about each message's text: ```json "filter": { "question": "Does this event report a failed required check or an unclear status?", "min_no_probability": 0.95 } ``` - Phrase `question` so **yes** means deliver. `min_no_probability` must be `> 0.5` and `<= 1`. - The decider sees only the feed name, sender, and message text — never the conversation history. - A message is dropped only when `P(no)` (multiplied by label mass, if the endpoint reports one) meets or exceeds `min_no_probability`. Dropped messages never enter the queue and cannot wake an idle session. - **Fails open:** messages pass through unfiltered when screening cannot run. This includes sessions with no decision model (warns once), failed calls, or calls exceeding the **1.5s** budget. Image-only messages and messages whose sender plus text exceeds **8 KiB** also pass through. **Runtime question override:** `subscribe_feed` accepts an optional `prompt` to set or replace a feed instance's question without restarting it. It also accepts an optional `min_no_probability`, defaulting to the manifest's threshold or `0.6`. Passing an empty `prompt` clears the override and restores the manifest's question. Setting a `prompt` is refused if the feed uses a command filter or if the session has no decision model. ### Command filter (external script) A command filter runs an external command once per source record, transforming or dropping it before delivery: ```json "filter": { "command": ["/path/to/excerpt", "--max", "2000"] } ``` - The source JSON record is written to the filter's stdin. - The filter writes a stream of JSON record objects to stdout (compact or pretty-printed). Empty stdout drops the record; multiple objects fan one source record out into multiple inputs. - Output records accept `text`, `from`, `image`, and an optional structured `data` object (only command-filtered feeds carry `data`). - Runs under the same executor, working directory, and environment as the feed command. - Caps: **1 MiB** per record on input and output, and at most **4 MiB** and **256 records** per filter invocation. - **Fails closed:** a nonzero exit, invalid JSON output, or exceeding any cap fails the attempt and **suspends** the feed (ignoring `restart`). `poo` writes filter diagnostics to a log file beside the session and wakes the session with a fault report (``). Optional feeds can be restarted with `subscribe_feed`; always-on and MCP resource feeds remain suspended until session close or resume. ## Profile feed declarations and `feeds.defaults` - **`feeds.defaults`** (default `true`): controls whether `$XDG_CONFIG_HOME/poo/feeds/` loads automatically alongside `feeds.paths`. A profile's `feeds_defaults` overrides `feeds.defaults` and is inherited from its `base` profile. See [Manifests Reference](/reference/manifests#defaults-and-profile-interaction). - **`profiles..feeds`**: declares feed names that a profile expects to be present (inherited and merged from `base`). This is a **presence assertion**, not a switch — `feeds.paths` and defaults still decide what loads, and an MCP resource feed satisfies the name as well. If a declared feed is not loaded, `poo` emits a warning rather than failing the build. See [Profiles & Prompts](/configuration/profiles-and-prompts). ## `poo daemon` `poo daemon` hosts a long-lived, feed-driven session without reading stdin. It is designed to run under a supervisor (`systemd`, `launchd`, a container entrypoint, or a background terminal) and keep a session alive across restarts. ```sh poo daemon --session ops-inbox --working-dir /srv/app ``` Key behaviors: - **Durable by default:** unless `--session-mode` or `session.mode` is set, `poo daemon` selects `durable` mode so runs, pending inputs, and optional feed subscriptions survive crashes. See [Sessions & Durability](/operations/sessions-and-durability). - **Lease-backed ownership:** the daemon acquires the session's lease (or takes it over if the previous owner died). If another owner takes over the lease while the daemon is running, `poo daemon` exits immediately with code `1` rather than writing into another owner's session. - **No wire client:** permission asks cannot prompt an interactive user; the asker chain is `[decide]` (active only when a decision model is configured). - **Clean shutdown:** `SIGINT` or `SIGTERM` stops feeds, flushes session records, releases the lease, and exits `0`. ### Flags In addition to shared and endpoint flags (`--settings`, `--profile`, `--feeds-path`, `--mcp-path`, `--cli-registry-path`, etc.): | Flag | Default | Description | |---|---|---| | `--session ` | generated ID | Session ID to load (taking over a dead owner's lease) or create if it does not exist. | | `--auto-resume` | `true` | Resume an unsettled pending run on load. Overrides `session.durable.auto_resume`. | | `--working-dir ` | current dir | Working directory for the session's tools and feeds. | ### Lifecycle stderr `poo daemon` logs one lifecycle fact per line to stderr: ```text poo daemon: started poo daemon: session ops-inbox poo daemon: 1 feed(s) poo daemon: idle ``` When taking over a session with an unsettled run: ```text poo daemon: started poo daemon: session ops-inbox poo daemon: 1 feed(s) poo daemon: the session was taken over: a run was left unsettled poo daemon: resumed run_01J... ``` On shutdown or lease loss: - `poo daemon: shutdown` (on `SIGINT` / `SIGTERM`) - `poo daemon: the lease was lost: a takeover owner now holds the session` ### Exit codes | Code | Meaning | |---|---| | `0` | Clean shutdown after `SIGINT` or `SIGTERM`. | | `1` | Operational failure: store open/create/resume error, failed pending-run resume, broken session, or lost lease. | | `2` | Usage or configuration error: invalid flags, bad working directory, invalid settings, or invalid session ID. | See [Limits & Exit Codes](/operations/limits-and-exit-codes) for exit codes across all `poo` subcommands. ## End-to-end example This example wires an Avenor inbox feed and CLI delegation tools into a durable daemon session that wakes whenever a child agent sends a question. **1. Feed manifest (`feeds.json`):** ```json { "version": 1, "feeds": { "avenor-inbox": { "description": "Receive Avenor messages", "command": ["avenor", "feed", "broker"], "env": { "AVENOR_BIND_HOST": "poo", "AVENOR_BIND_SESSION": "session:id" }, "on_idle": "wake", "restart": true } } } ``` **2. Settings (`settings.yaml`):** ```yaml feeds: defaults: false paths: [./feeds.json] cli_registry: defaults: false paths: [./examples/avenor/tools.json] jobs: max_unattended_wakes: 10 session: mode: durable durable: lease_ttl_s: 30 ``` **3. Start the daemon:** ```sh poo daemon --settings settings.yaml --session avenor-coordinator ``` `poo daemon` prints its startup lines to stderr, starts `avenor feed broker` with `AVENOR_BIND_SESSION=avenor-coordinator`, and waits idle: ```text poo daemon: started poo daemon: session avenor-coordinator poo daemon: 1 feed(s) poo daemon: idle ``` When `avenor feed broker` prints a JSON line to stdout, `poo` wakes the idle session and delivers `` to the model. The model can then reply via its registered tools. If the daemon is stopped with `SIGTERM` and started again with `--session avenor-coordinator`, it reattaches to the same session ID, restarts `avenor-inbox`, and resumes any unsettled run. --- # Context Compaction Long sessions eventually exceed a model's context window or an endpoint's prompt limit. `poo` handles this through pluggable **compaction strategies** configured under `context.strategy` (default: `mine`). ## Transparent history Compaction in `poo` changes only the **view** sent to the model — never what the session recorded. - **Nothing is rewritten silently.** Every replacement starts with a visible marker (`[Context compacted: turns 1-N reconstructed below]` or `[Context compacted: turns 1-N summarized below]`), provider windows append `[context compacted by provider]`, and tool-result rewrites preserve their handle with a compacted marker. - **The store stays whole.** Every original turn and tool result remains in the session log intact and recoverable. - **Retention pointers and file lists.** Replacement strategies append a list of files touched in the covered turns (`read`, `edit`, `write`). This keeps the model from re-reading those files. `mine` and `pointer` also append a retention pointer with the session ID and replaced turn range. When enabled, it names the `history` tool to search or read those turns back on demand. - **One form per compaction.** Core validates every compaction before applying it. A compaction takes exactly one of four forms: a turn-range replacement (`Replace`), a tool-result rewrite (`Rewrite`), a provider-native window (`Window`), or a run-ending handoff (`End`). If a compaction fails or is rejected, the run continues uncompacted when the next request still fits, or settles with `context_exhausted` when it does not. See [Sessions & Durability](/operations/sessions-and-durability) for how session logs are persisted and replayed. ## When compaction fires (the fit rule) Every strategy compacts when the next request no longer fits its budget. `poo` tracks two limits from the active model's metadata (see [Models & Catalog](/configuration/models-and-catalog)): - **`context_limit`** — the model's total context window (prompt + output). - **`input_limit`** — the largest prompt the endpoint accepts, if lower than `context_limit`. The effective prompt ceiling (`PromptLimit`) is the smaller of the two (ignoring whichever is unset). After at least one turn has been sent, the fit rule triggers when either condition holds: 1. **Window room is short:** `estimated_input + output_need + 256 > context_limit` 2. **Input cap is exceeded:** `estimated_input + 256 > input_limit` Where `256` is the fixed token reserve (`OutputReserve`), and `output_need` is the larger of the run's `OutputLimit` and the strategy's fork output limit (for strategies that fork: `mine`, `pointer`, and `handoff`). Because a fork re-sends the whole current window, its output limit counts toward the fit rule. Additional guards: - **Over-window start:** Block strategies (`mine`, `pointer`, `summary`) also fire immediately, even before a turn completes. They trigger if the view leaves under `256` tokens of output room (`MinOutputTokens`) or exceeds `input_limit`. - **At least two live turns:** Block strategies never compact a single live turn; there must be older turns behind the active work. - **Must restore room:** Block strategies check whether the replacement (plus its marker, file list, and retention pointer) would actually end the shortage. On a window too small for the verbatim tail plus replacement to recover room, compaction is skipped rather than looping every turn. Similarly, `native` declines to repeat if the provider's last compacted input already left the window short, letting the request gate settle `no_output_room`. - **Small-window tail cap:** The verbatim tail (`keep_recent_tokens`) is automatically capped at 50% of `PromptLimit` so small-window models can still compact. ### Optional early trigger (`ratio`) Setting `ratio` (a float between `0` and `1`) under `context.mine`, `context.pointer`, `context.summary`, or `context.handoff` adds an earlier trigger when `estimated_input >= ratio * PromptLimit` (after at least one turn). When unset, the fit rule alone decides. ::: warning Removed keys: `notice_ratio` and `hard_ratio` `context.notice_ratio` and `context.hard_ratio` have been removed and have no effect. A settings file that still sets them loads with a warning. Use the fit rule (default) or a strategy-specific `ratio` instead. ::: ## Strategy comparison | Strategy | How it works | When to use | Requirements | Trade-offs | |---|---|---|---|---| | `mine` *(default)* | Forks the chat model for advisory pointers, then reads the covered transcript in a fresh request to reconstruct task-shaped working context. | General-purpose long sessions where task state matters more than chronological order. | Model must handle two side requests (fork + ask). | Higher compaction token cost (reads covered transcript); best fidelity for complex work. | | `pointer` | Forks the chat model for JSON search queries and notes. Runs literal searches over retained history and composes context from matches and seed without reading the full transcript. | Very long sessions or when using a smaller-window `roles.compaction` model. | Readable session history for query extraction; falls back to `mine` on failure. | Bounded compose input; can miss unqueried details (recoverable via `history` tool). | | `summary` | Single fresh request reads the covered turns and writes a structured chronological checkpoint. | Conventional summarization with a smaller output budget and no fork pass. | Model must handle one side request (ask). | No fork pass and no retention pointer; chronological summary can lose non-linear details. | | `handoff` | Forks the chat model to write a continuation note, then ends the run (`context_exhausted`) with the handoff text. | Orchestrators that prefer starting fresh sessions from an explicit handoff rather than mutating history. | Caller must handle `context_exhausted` and seed a new session. | Terminates the run; does not continue in-place. | | `native` | Asks the provider's own compaction endpoint to produce an opaque compacted window and installs it as the view. | When using a provider that supports server-side state compaction. | Model declares `ops: [chat, compact]` and uses a transport implementing `NativeCompactor` (currently `openai-codex`). | Provider-locked; opaque state cannot be transferred across models or providers. | | `none` | Disables compaction completely. | Short runs, benchmarks, or callers managing context externally. | None. | Run settles `context_exhausted` (`no_output_room` or `prompt_limit`) once the window fills. | ## Strategies in detail ### `mine` (default) `context.strategy: mine` reconstructs the covered turns into a task-shaped working context using two requests: 1. **Pointer pass (fork):** Re-sends the last main request on `roles.chat` and asks what the replacement must preserve (turns, file paths, error strings, open threads). The pass is best-effort: if the fork fails, is truncated, or returns a tool call, `mine` proceeds without pointers because the transcript still holds everything. 2. **Mining pass (ask):** Sends the covered transcript, any prior replacement, and the fork's pointers to `roles.compaction` (or `roles.chat` if unset). Tool results are capped and reasoning blocks are stripped. A truncated reply or tool call is rejected rather than installed. The replacement includes the marker line, the reconstruction, a list of read/modified files, and a retention pointer naming the session and replaced turns. ```yaml context: strategy: mine mine: # ratio: 0.85 # optional early trigger; fit rule decides when unset keep_recent_tokens: 12000 # default: 12000 max_tokens: 32768 # default: 32768 # pointer_max_tokens: 16384 # optional; defaults to window-scaled output limit ``` | Key | Default | Description | |---|---|---| | `ratio` | unset (`0`) | Optional share of `PromptLimit` for an early trigger. | | `keep_recent_tokens` | `12000` | Tokens of newest history kept verbatim (capped at 50% of `PromptLimit`). | | `max_tokens` | `32768` | Output token limit for the mining request. | | `pointer_max_tokens` | window-scaled | Output token limit for the fork pass. Defaults to `8192` (`< 64k` window), `16384` (`64k–128k` or unknown), or `32768` (`>= 128k`). | ### `pointer` `context.strategy: pointer` keeps `mine`'s fork but makes the pointers load-bearing so the covered transcript is never read whole: 1. **Pointer pass (fork):** Asks the chat model for a JSON object of literal search `queries` (capped at 8) and `notes`. Requests JSON response format when supported; if the endpoint refuses the parameter, retries once without it. Replies are parsed leniently. If malformed prose returns, a small reformat ask on `roles.compaction` tries to recover JSON before treating the text as `notes`. 2. **Extraction:** Runs each query as a literal search (`regexp.QuoteMeta`) over the store's retained history, deduplicating matches up to `snippet_budget` bytes (cut cleanly on UTF-8 rune boundaries). 3. **Compose pass (ask):** Sends only the orientation seed (the last three non-empty user messages), extracted snippets, notes, and any prior replacement to `roles.compaction`. Because the full transcript is never sent, the compaction model's window bounds only the compose request, not the session's total size. **Fallback to `mine`:** If the compose request fails, hits `max_tokens`, returns a tool call, or returns empty text, `pointer` falls back to `mine` with the same `ratio`, `keep_recent_tokens`, `max_tokens`, and `pointer_max_tokens`. If `escalate_after` is set to a positive integer `N`, once the session has run `N` compactions, all subsequent compactions delegate directly to the full-span `mine` fallback. ```yaml context: strategy: pointer pointer: # ratio: 0.85 # optional early trigger; fit rule decides when unset keep_recent_tokens: 12000 # default: 12000 max_tokens: 32768 # default: 32768 # pointer_max_tokens: 16384 # optional; defaults to window-scaled output limit snippet_budget: 32768 # default: 32768 (bytes) # escalate_after: 3 # optional; default 0 (never escalate) ``` | Key | Default | Description | |---|---|---| | `ratio` | unset (`0`) | Optional share of `PromptLimit` for an early trigger. | | `keep_recent_tokens` | `12000` | Tokens of newest history kept verbatim. | | `max_tokens` | `32768` | Output token limit for the compose request. | | `pointer_max_tokens` | window-scaled | Output token limit for the fork (and reform) pass. Same window scaling as `mine`. | | `snippet_budget` | `32768` | Maximum total bytes of retained-history snippets collected across queries. | | `escalate_after` | `0` (off) | Number of compactions a session runs before delegating all later compactions to `mine`. | ### `summary` `context.strategy: summary` is the conventional single-request checkpoint strategy. It skips the fork pass and sends covered turns (plus any prior summary) to `roles.compaction` (or `roles.chat`). It replaces those turns with the summary, marker line, and file list, without a retention pointer. ```yaml context: strategy: summary summary: # ratio: 0.85 # optional early trigger; fit rule decides when unset keep_recent_tokens: 20000 # default: 20000 max_tokens: 4096 # default: 4096 ``` | Key | Default | Description | |---|---|---| | `ratio` | unset (`0`) | Optional share of `PromptLimit` for an early trigger. | | `keep_recent_tokens` | `20000` | Tokens of newest history kept verbatim. | | `max_tokens` | `4096` | Output token limit for the summarization request. | ### `handoff` `context.strategy: handoff` refuses to compact in-place. When triggered, it forks the last main request on `roles.chat` and asks the model for a handoff note. It then ends the run with `context_exhausted`, carrying that note in the settle detail. A truncated or empty reply is rejected. The caller can then seed a fresh session with the handoff note. ```yaml context: strategy: handoff handoff: # ratio: 0.85 # optional early trigger; fit rule decides when unset max_tokens: 2048 # default: 2048 ``` | Key | Default | Description | |---|---|---| | `ratio` | unset (`0`) | Optional share of `PromptLimit` for an early trigger. | | `max_tokens` | `2048` | Output token limit for the handoff fork request. | ### `native` `context.strategy: native` asks the provider's transport to compact its own conversation state and installs the returned provider window (followed by `[context compacted by provider]`) as the model's view. System instructions remain intact. `native` is opt-in and has strict capability checks: - The active model must declare `compact` in its `ops` list (`ops: [chat, compact]`). - Its transport must implement `NativeCompactor`. In this repository, only the `openai-codex` Responses transport implements native compaction. - Settings validation refuses `context.strategy: native` on unsupported transports such as Chat Completions. Mid-session model switches are re-checked when compaction runs: switching to a model without `ops: [..., compact]` refuses native compaction rather than calling an incapable provider. ```yaml models: openai-codex/gpt-6.1-sol: endpoint: openai-codex model_id: gpt-6.1-sol api: responses ops: [chat, compact] roles: chat: openai-codex/gpt-6.1-sol context: strategy: native ``` `native` exposes no `context.native` sub-keys in settings; it triggers strictly on the fit rule. ### `none` `context.strategy: none` disables compaction. The session runs until the request gate blocks a request for `no_output_room` or `prompt_limit`, settling the run with `context_exhausted`. ```yaml context: strategy: none ``` ## The `compaction` role `roles.compaction` assigns a dedicated model to a strategy's own standalone requests (`Ask`), defaulting to `roles.chat` when unset (see [Roles and Required Operations](/configuration/models-and-catalog#roles-and-required-operations)): ```yaml roles: chat: openai-codex/gpt-6.1-sol compaction: opencode-go/glm-5.3 ``` - **What moves to `roles.compaction`:** The summarization request (`summary`), the mining request (`mine`), and the compose and reformat requests (`pointer`). The model must serve the `chat` operation and is built through the same catalog and transport machinery as other roles. - **Why the fork stays on `roles.chat`:** The pointer pass (`mine`, `pointer`) and handoff pass (`handoff`) fork the last main request byte-for-byte with appended instructions. Only the chat model's transport can reuse that cached prefix and see the exact window the chat model just worked in. Forks therefore always run on `roles.chat`. ## Related pages - [Settings Reference](/reference/settings) — complete schema for `context.*` and `roles.compaction` - [Models & Catalog](/configuration/models-and-catalog) — configuring `context_limit`, `input_limit`, `max_output`, and `ops` - [Sessions & Durability](/operations/sessions-and-durability) — session log retention and replay - [Limits & Exit Codes](/operations/limits-and-exit-codes) — `context_exhausted`, `no_output_room`, and `prompt_limit` - [Built-in Tools & Jobs](/capabilities/tools-and-jobs) — the `history` tool for reading retained turns --- # Decision Model `poo` supports a dedicated **decision model** (`roles.decider`) alongside the chat model (see [Roles and Required Operations](/configuration/models-and-catalog#roles-and-required-operations)). Instead of free-form prose, it takes a state payload and typed questions and returns a probability distribution over the allowed answers. Questions can be `Bool` (yes/no), `Choice` (up to 26 named options), or `Score` (2 to 10 levels). Every call through a session's decider is wrapped by `decide.Recorded` (`poo/decide`), which writes a `decision` record to the [session log](/reference/session-log-v0). Each record includes the caller origin, `state_hash`, questions, answers, outcome (`ok`, `deferred`, or `invalid`), latency, and wire request count. ## Configuring `roles.decider` A model assigned to `roles.decider` must declare `ops: [systemone]` (or `decisions`). Models that serve only chat turns are rejected at construction time. ### Built-in TypeSafe provider `poo` ships a built-in `typesafe` decisions provider (`https://api.typesafe.ai/v1`) serving `typesafe/jev-latest` and `typesafe/jev-preview`. Jev answers decision questions only and serves no chat turns. Authenticate with `poo login typesafe` or set `TYPESAFE_API_KEY` in the environment (see [Providers & Auth](/configuration/providers-and-auth)), then assign the role: ```yaml roles: chat: opencode-go/glm-5.3 decider: typesafe/jev-latest decider: timeout_ms: 1500 ``` The TypeSafe endpoint rejects a request-level `instructions` field and has no OpenAI-shaped `/models` list. Its built-in definition therefore sets `instructions_per_question: true` (folding call framing into each question) and `skip_probe: true`. ### Custom decision endpoints and models To point `roles.decider` at a newer TypeSafe model or a self-hosted `systemone`-compatible endpoint, declare the endpoint and model with `ops: [systemone]`: ```yaml endpoints: my-decider: endpoint: https://api.typesafe.ai/v1 api_key_env: TYPESAFE_API_KEY skip_probe: true instructions_per_question: true models: my-decider/jev-next: endpoint: my-decider model_id: jev-next ops: [systemone] inputs: [text] context_limit: 64000 roles: chat: opencode-go/glm-5.3 decider: my-decider/jev-next ``` | Key | Type | Default | Description | | --- | --- | --- | --- | | `roles.decider` | string | unset | Model name (`provider/model`) for the decider role. Must serve `systemone` or `decisions`. | | `decider.timeout_ms` | int | unset | Global per-call latency budget in milliseconds (minimum `1` when set). | | `endpoints..instructions_per_question` | bool | `false` | Fold request-level framing into each question for endpoints that reject a top-level `instructions` field. | | `models..ops` | string[] | `[]` | Operations served by the model; include `systemone` for decision models. | ## Where `poo` uses the decision model Today, three built-in subsystems call `roles.decider` when it is configured. ::: info Growing surface This subsystem set is not the end of the road. `poo` is under active development, and more decision-backed capabilities, integrations, and hooks will be added over time. Custom Go binaries can also call `poo/decide.Decider` directly from their own [hooks](/extending/architecture). ::: ### 1. Permission asker (`perm/decide`) The `decide` permission asker (`poo/perm/decide`) sits in the [permission asker chain](/operations/permissions-and-safety) to judge unmatched side-effecting tool calls automatically. When asked, it sends one `Bool` question (`allow`) along with a bounded evidence payload framed as data, not instructions: - Up to 20 recent conversation turns (`DefaultEvidenceTurns`), with message text capped at 512 chars, tool inputs at 256 chars, and tool outputs at 512 chars. - The working directory and the pending call's tool name, summary, class, reason, and permitted arguments. The asker compares the returned probabilities against two thresholds: - `P(yes) >= permission.decide.allow` → **allow** (default `0.85`). - `P(no) >= permission.decide.deny` → **deny** (default `0.99`). - Anything in between — as well as timeouts, errors, panics, or invalid probability distributions — **defers** to the next asker in `permission.askers` (or `permission.fallback`). A deferral never grants permission. ```yaml roles: chat: opencode-go/glm-5.3 decider: typesafe/jev-latest permission: askers: [decide, wire] fallback: deny decide: allow: 0.85 deny: 0.99 timeout_ms: 1500 ``` Setting `decide` in `permission.askers` or configuring any `permission.decide.*` key requires `roles.decider` to be set. | Key | Type | Default | Description | | --- | --- | --- | --- | | `permission.decide.allow` | float | `0.85` | Minimum `yes` probability (`0`–`1`) to allow a call. | | `permission.decide.deny` | float | `0.99` | Minimum `no` probability (`0`–`1`) to deny a call. | | `permission.decide.timeout_ms` | int | `1500` | Per-call latency budget for the permission asker, in milliseconds. | ### 2. Feed record filtering A [feed manifest](/capabilities/feeds-and-daemon) can declare a question `filter` to screen incoming messages before they enter the session. The model can also set one dynamically on a running feed: ```yaml filter: question: "Is this message actionable for the active repository?" min_no_probability: 0.8 ``` For each emitted record, `poo` asks the decision model one `Bool` question (`yes` = deliver, `no` = drop) over `{ feed, from, text }` with a `1500ms` timeout and an 8 KiB combined sender+text limit. A message is dropped only when `P(no)` (multiplied by `label_mass` if reported) is at least `min_no_probability` (valid range `(0.5, 1]`; default `0.6` for model-set prompts). Question filters **fail open** and deliver messages unfiltered when screening cannot run. That includes sessions with no decider (logged once per feed attempt), image-only messages, and payloads over 8 KiB. Messages also pass through when the decider times out or defers. ### 3. Large CLI and MCP catalog search (`find_tool`) Sessions with [CLI Registry](/capabilities/cli-registry) manifests and [MCP servers](/capabilities/mcp-servers) can accumulate dozens or hundreds of entries. When the catalog exceeds 30 entries (`cli.FindThreshold`) and a decision model is configured, `poo` offers `find_tool` instead of dumping the full catalog into the system prompt. When the model calls `find_tool` with a natural-language `intent`, `poo` asks the decision model one `Bool` question per offered entry. Requests batch up to 64 questions each, with up to 4 requests in flight. `find_tool` returns the top 8 matching entries ranked best-first with their schemas. If the search fails or the decider is unavailable, `find_tool` returns a short notice instead of dumping the catalog. --- # CLI Registry & Script Tools You do not need to build a custom Go binary to give `poo` new tools. Drop a JSON manifest into `~/.config/poo/cli-registry/`, or point `cli_registry.paths` at a manifest directory. `poo` compiles the argument schema and validates calls before starting a process. It then runs the command through the session's executor, sandbox, permissions, and background jobs. The manifest format is powered by `github.com/sdougbrown/cli-registry` (`poo/cli` and `poo/tool/cliregistry`). ## Walkthrough: wrapping a CLI without recompiling Suppose you have `writetighter` on `PATH` and want the model to lint prose with `writetighter lint`. Create a manifest at `~/.config/poo/cli-registry/writetighter.json`: ```json { "version": 1, "tools": { "tighten-lint": { "description": "Run writetighter lint on a file or directory to catch prose issues.", "command": ["writetighter", "lint"], "inputSchema": { "type": "object", "properties": { "path": { "type": "string", "description": "File or directory to lint." }, "kind": { "type": "string", "enum": ["pr", "plan", "doc", "commit"], "description": "Document kind for rule selection." } }, "required": ["path"], "additionalProperties": false }, "bindings": [ { "property": "kind", "style": "space", "flag": "--kind" }, { "property": "path", "style": "positional" } ], "output": { "mode": "raw" } } } } ``` Start a session with a side-effecting profile (such as `code`): - Because the manifest sits in `~/.config/poo/cli-registry/`, `poo` loads it automatically with no settings change. - Because the catalog has 30 or fewer entries, `tighten-lint` is promoted to a direct tool: the model calls `tighten-lint({"path": "docs/README.md", "kind": "doc"})` directly. - `poo` validates the arguments against `inputSchema` before spawning a process, builds `["writetighter", "lint", "--kind", "doc", "--", "docs/README.md"]`, and runs it through the session's executor. ::: tip Protecting flag-like values Separate-value flag bindings (`style: "space"`) reject values that start with `-` at validation time so a model cannot inject extra flags. `equals` bindings (`--flag=value`) stay inside a single argv element, and `positional` bindings are separated with `--`. ::: ## Manifest discovery and `cli_registry.defaults` `poo` loads manifests from two sources, in order: 1. **Default user directory**: `$XDG_CONFIG_HOME/poo/cli-registry/` (typically `~/.config/poo/cli-registry/`). A missing directory is ignored. 2. **Configured paths**: `cli_registry.paths` in settings, plus any paths added by `POO_CLI_REGISTRY_PATH` (OS path-list separated) or repeatable `--cli-registry-path` flags on `poo run`, `poo serve`, and `poo prompt`. Relative paths in `cli_registry.paths` resolve against the working directory; paths starting with `~/` resolve under the home directory. Duplicate tool names across two manifests fail the load and name both files. ```yaml cli_registry: paths: - ./tools/registry - ~/shared-manifests/git.json defaults: true # default; set false to ignore ~/.config/poo/cli-registry/ ``` To isolate a project, binary, or test from ambient user manifests, set `cli_registry.defaults: false`. A profile can override that setting with `cli_registry_defaults`: ```yaml cli_registry: defaults: false profiles: personal: base: code cli_registry_defaults: true ``` ## Direct tools vs. `call_cli` (the 30-entry threshold) How registered entries appear to the model depends on the catalog size after availability filtering: | Catalog size | Tools offered | Prompt catalog section | |---|---|---| | `1` to `30` entries | One direct tool per entry (manifest name + `inputSchema`) | None (the tool list already carries every schema) | | `> 30` entries with a [decision model](/capabilities/decision-model) | `call_cli` + `find_tool` | Search guidance pointing to `find_tool` | | `> 30` entries without a decision model | `call_cli` | Full catalog listing every entry and argument hint | Both shapes execute through the exact same runner, executor, sandbox, timeout, environment resolution, and observation cap. When behind `call_cli`, the model invokes an entry by name: ```json { "command": "tighten-lint", "args": { "path": "docs/README.md", "kind": "doc" } } ``` With a decision model configured, `find_tool` takes `{"intent": "..."}` and asks the decider one yes/no question per entry. It returns the top 8 matches with their argument schemas and dispatcher (`call_cli` or `call_mcp`). ### Collision behavior Direct-tool promotion is **all or nothing**. The entire catalog stays behind `call_cli` instead of promoting if any of the following is true: - The catalog has more than 30 entries. - Any entry's name collides with a built-in/linked tool, a core tool (`jobs`, `cancel_job`, `subscribe_feed`, `finish`, `call_cli`, `find_tool`), or another tool the profile already offers. A manifest never shadows an existing tool. - The profile explicitly names `call_cli` or `find_tool` itself. ::: info Reserved `background` argument Direct tools support `background: true` by default. If a manifest's `inputSchema` already defines a property named `background`, that tool keeps its own argument and runs foreground-only rather than failing the session. ::: ## Disabling the registry To turn off the CLI registry for a session or profile without deleting manifests, disable `call_cli`: ```yaml tools: disabled: [call_cli] ``` Disabling `call_cli` suppresses both direct-tool promotion and `call_cli` itself. ## Availability gating (`profile_side_effecting`) Without availability rules, `poo` offers the registry only to side-effecting profiles (such as `code`, not `search`). This default protects read-only profiles because arbitrary CLI commands can modify state. Manifests can declare an Umpire `availability` block to gate entries per profile. `poo` supplies one boolean condition: - `profile_side_effecting` (`boolean`): `true` when the profile offers any side-effecting tool, `false` for read-only profiles. Once manifests declare `availability` conditions: - Read-only profiles (such as `search`) earn the registry and receive only the entries whose rules leave them available. - Profiles with no tools at all still receive no registry entries. - Declaring any condition other than `profile_side_effecting`, or declaring `profile_side_effecting` as a type other than `boolean`, fails the build. ## Execution, environment, and permissions Every registered command runs where `bash` runs: - **Executor & sandbox**: Runs through the session's configured executor (local or [bubblewrap](/operations/sandbox)), in the session's working directory unless the manifest fixes a directory. - **Environment**: Manifest `env` bindings accept literals, `env:NAME`, and `session:id`. `env:NAME` reads from the session's scrubbed environment, so variables removed by `tools.env.scrub` or excluded by `tools.env.passthrough` are unavailable. `session:id` resolves at call time to the session's ID and stays stable across resume. See [`examples/avenor/tools.json`](https://github.com/sdougbrown/poo/blob/main/examples/avenor/tools.json) for a multi-tool manifest using `session:id` and `stdin`/`equals`/`positional` bindings. - **Permissions**: Registered tools are statically `side_effecting`. Behind `call_cli`, the primary argument is `command`, so [permission rules](/operations/permissions-and-safety) can match by command prefix. When promoted to direct tools, rules match by the tool's own name. - **Background jobs**: Registered tools accept `background: true` and support `/bg` promotion in the REPL. ## Non-CLI JSON script tools A registered tool does not have to wrap an existing CLI. Using a `json` stdin binding and `output.mode: "json"`, any script in any language becomes a typed tool: ```json { "version": 1, "tools": { "sum_pair": { "description": "Sum a pair of numbers.", "command": ["python3", "fn_notes.py"], "inputSchema": { "type": "object", "properties": { "data": { "type": "object", "properties": { "a": { "type": "number" }, "b": { "type": "number" } }, "required": ["a", "b"], "additionalProperties": false } }, "required": ["data"], "additionalProperties": false }, "bindings": [ { "property": "data", "style": "json" } ], "output": { "mode": "json" } } } } ``` The contract is three rules: 1. **Stdin**: `style: "json"` serializes an object- or array-valued property as JSON onto the script's stdin. The bound property must be a concrete `object` or `array` in `inputSchema`, and a tool may have at most one `stdin` or `json` binding. An optional `flag` is emitted only when the property is present. 2. **Stdout**: `output.mode: "json"` parses the script's stdout as JSON and returns it directly as the tool result (bypassing the `bash` exit-code envelope). Any stderr written on a successful exit is appended after a newline. 3. **Errors**: A nonzero exit (outside `output.success_exit_codes`) returns a recoverable error envelope containing stdout, stderr, and the exit code. ::: warning `null` and over-cap JSON results Two edge cases fall back to the standard exit-code envelope. This happens when stdout decodes to JSON `null`, or when the serialized result exceeds the observation cap. If a script can return an empty result, return an object such as `{"result": null}` instead of bare `null`. ::: Non-CLI script tools join the exact same catalog, 30-entry promotion threshold, schema validation, permission policy (`side_effecting`), sandbox, and background job machinery as CLI entries. The `cli-registry` repository also ships a small Python helper (`helpers/python/poo_fn.py`) and runnable example (`examples/fn.json` + `examples/fn_notes.py`), though any executable that reads JSON from stdin and writes JSON to stdout works. ## Related - [MCP Servers](/capabilities/mcp-servers) — connect persistent stdio MCP servers and resource feeds - [Built-in Tools & Jobs](/capabilities/tools-and-jobs) — built-in tools, observation caps, and background jobs - [Manifests Reference](/reference/manifests) — full manifest schemas for CLI registry, feeds, and MCP - [Build Your Own Binary](/extending/custom-binary) — when you actually want a custom Go binary with custom tools --- # MCP Servers `poo` runs Model Context Protocol (MCP) servers as session-owned stdio child processes. Loading an `mcp.json` manifest **declares** which servers exist; a profile's `mcp_servers` list **selects** which ones a session actually starts. The model calls server tools through `call_mcp`, searches them beside CLI registry commands with `find_tool`, and can receive asynchronous messages from server resources through `poo` resource feeds. ## Loading `mcp.json` manifests `poo` reads standard `mcp.json` files (the same `mcpServers` format used by Claude Code and other harnesses) from: 1. **Default user directory**: `$XDG_CONFIG_HOME/poo/mcp/` (typically `~/.config/poo/mcp/`), loaded when `mcp.defaults` is absent or `true`. A missing directory is not an error. 2. **Configured paths**: `mcp.paths` in settings (files or directories), plus `POO_MCP_PATH` (OS path-list separated) and repeatable `--mcp-path` flags on `poo run`, `poo serve`, and `poo prompt`. Directories contribute their `.json` files and skip non-`.json` files; an explicit file path that is not `.json` fails the load. Relative paths resolve against the working directory; `~/` resolves under the home directory. ```yaml mcp: paths: - examples/avenor-mcp defaults: false # ignore ~/.config/poo/mcp/ ``` A profile can override `mcp.defaults` with `mcp_defaults`. ### Manifest rules - Top-level `mcpServers` is required. Each key is the server name (letters, digits, `-`, and `_`). - `poo` reads `command` (required), `args`, `env`, `type`, and `url`. Other top-level keys and entry fields are ignored so one `mcp.json` can be shared across harnesses. - Only `stdio` transport is supported. Entries with `type` set to `http`, `sse`, or `streamable-http` (or a `url` with no `type`) are skipped with a warning naming the server. Any other `type` value fails the load. - Duplicate server names across files and duplicate JSON object keys within a file both fail the load. ## Profile opt-in (`mcp_servers`) Loading a manifest starts nothing. A session starts only the servers named in its profile's `mcp_servers` list: ```yaml profiles: avenor: base: code mcp_servers: [avenor] profile: avenor ``` `mcp_servers` adds to the base profile's selection, deduplicated in order of first appearance. Selecting a server name that no loaded manifest defines produces a warning and skips it. A binary that does not link `call_mcp` fails the build if a profile selects any server. ### Process lifecycle and trust - **Session-owned**: Each selected server starts when the session is created or resumed (with the session's ID and working directory) and stops when the session closes. - **Startup budget**: Startup is bounded at **30 seconds** per server, including the MCP handshake and initial tool listing. A server that fails to start fails session creation or resume. - **Unsandboxed host process**: MCP servers start directly on the host — not through the session's executor or sandbox — and run as the user running `poo`. They inherit the host environment minus `tools.env.scrub`, plus the manifest's resolved `env`. Select an MCP server with the same trust boundary as installing a program. ## Launch template variables `command`, each element of `args`, and each `env` value support template expansion, resolved **at server launch** (not when settings load): | Syntax | Resolution | |---|---| | `${NAME}` | Host environment variable `NAME`. Missing variable fails launch naming the server and variable. Can re-introduce a variable removed by `tools.env.scrub`. | | `${NAME:-default}` | Host environment variable `NAME`, or `default` if unset. | | `${session:id}` | The session's ID (stable across session resume). Cannot take a default. | | `$$` | Literal `$`. | Syntax errors — unterminated `${`, empty variable name, a default on `session:id`, or any `session:` variable other than `id` — fail manifest load. ## Calling tools: `call_mcp` and `find_tool` The model reaches MCP tools through a single dispatcher, `call_mcp`, using `/` qualified names: ```json { "name": "avenor/spawn", "args": { "prompt": "Run the test suite and report failures.", "dir": "/path/to/repo" } } ``` - **Permissions**: `call_mcp` is `side_effecting` and its primary argument is `name`. A [permission rule](/operations/permissions-and-safety) can allow or deny an entire server by prefix (for example `command_prefix: "avenor/"`) without listing individual tools. - **Hints vs. permissions**: MCP tool annotations (`readOnlyHint`, `destructiveHint`) appear in the prompt catalog and `find_tool` results as `(read-only)` or `(destructive)` hints for the model. They never change the call's permission class. - **Background jobs**: `call_mcp` supports `background: true` and `/bg` promotion in the REPL. - **Outputs**: Text responses are elided in the middle if they exceed the observation cap. `structuredContent` rides along when it is valid JSON under the same cap (otherwise omitted with a note). Returned images become attachments when the active model accepts `image` input and the image fits within 5 MB. Otherwise, a note explains what was omitted. - **Errors**: Unknown `/` names are refused before calling. A stopped server returns `server is down` as a recoverable error. A transport failure mid-call is reported and **never retried**, because the server may already have executed side effects. ### `find_tool` integration When a session has a [decision model](/capabilities/decision-model): - If the MCP offering exceeds 30 tools, the prompt points the model at `find_tool` instead of listing every tool inline. - `find_tool` searches MCP tools and CLI registry commands together over a live snapshot of the session's offering. Each hit includes the tool's argument schema and tells the model which dispatcher (`call_mcp` or `call_cli`) and argument (`name` or `command`) to use. - Because the snapshot is live, a down or relaunching server contributes no stale hits. Once it relaunches, its newly listed tools are immediately searchable. ## Resource feeds (`poo` block) A manifest can include a top-level `poo` block to turn an MCP resource into a session feed. Unlike `mcpServers`, the `poo` block is **strict**: unknown fields fail the load. ```json { "mcpServers": { "avenor": { "command": "avenor", "args": ["mcp", "--bind-host", "poo", "--bind-session", "${session:id}"] } }, "poo": { "servers": { "avenor": { "feeds": { "avenor-inbox": { "resource": "avenor://inbox", "on_idle": "wake", "description": "Messages from Avenor children.", "filter": { "command": ["jq", "-c", ".text | fromjson | .messages[] | {from, text}"] } } } } } } } ``` Fields under `poo.servers..feeds.`: - `resource` (required): Resource URI to subscribe to. - `description`: Shown in the `jobs` prompt section. - `on_idle`: `wake` or `hold` (inherits `jobs.on_idle` when omitted). - `filter`: Optional [feed filter](/capabilities/feeds-and-daemon) using either `command` or `question`. A `command` filter fans one resource read into zero, one, or many inputs. A `question` filter screens each record with the decision model. How resource feeds run: - The server must advertise `resources/subscribe` in its handshake, or session creation fails. - After subscribing, `poo` reads the resource once immediately (draining any backlog queued before subscription) and reads it again on each resource-updated notification. - Each text content block is emitted as a record with the server name as `from` and the text verbatim (empty text and binary contents are skipped). Reads are drained at-most-once. - Declared `command` filters run through the session's executor and working directory. Standard feed caps apply: 1 MiB per record, and 4 MiB or 256 records per filter run. - Feed names must be lowercase letters, digits, `-`, and `_`, and must be unique across all MCP servers and configured command feeds. Two feeds cannot subscribe to the same server resource. - Running resource feeds appear in `jobs` as `feed:` and can be stopped with `cancel_job`. ## Bounded auto-relaunch If a running MCP server exits unexpectedly during a session, `poo` relaunches it automatically: - **Backoff**: First retry waits **1 second**, doubling on each consecutive failure up to **30 seconds**. - **Reset**: A generation that stays up for at least **60 seconds** resets the failure counter. - **Exhaustion**: After **5 consecutive failures**, the server is marked down for the remainder of the session: - `call_mcp` calls to that server return `server is down`. - Any resource feeds attached to that server suspend with fault `filter_exited` (`server stopped after 5 relaunches`). - The session itself keeps running; resuming the session starts with a fresh relaunch budget. - **Re-sync**: On a successful relaunch, `poo` re-lists the server's tools (updating `call_mcp` and `find_tool` live; the initial prompt catalog is not re-rendered) and re-subscribes its resource feeds. ## Example: Avenor over MCP The repository includes a complete working example in [`examples/avenor-mcp/`](https://github.com/sdougbrown/poo/tree/main/examples/avenor-mcp): - [`examples/avenor-mcp/mcp.json`](https://github.com/sdougbrown/poo/blob/main/examples/avenor-mcp/mcp.json) launches `avenor mcp --bind-host poo --bind-session ${session:id}` and subscribes to `avenor://inbox` with a `jq` filter that fans out batched messages and attaches reply instructions for asks. - [`examples/avenor-mcp/settings.yaml`](https://github.com/sdougbrown/poo/blob/main/examples/avenor-mcp/settings.yaml) loads `examples/avenor-mcp`, selects `mcp_servers: [avenor]` on a profile, and disables ambient `mcp`, `feeds`, and `cli_registry` defaults so the MCP inbox does not contend with the older CLI+feed example in `examples/avenor/`. ```sh poo run --settings examples/avenor-mcp/settings.yaml \ "spawn a child to run the test suite, then answer its questions" ``` ## Related - [CLI Registry & Script Tools](/capabilities/cli-registry) — wrap local CLIs and scripts without an MCP server - [Feeds & Daemon](/capabilities/feeds-and-daemon) — command feeds, filters, and idle wake behavior - [Built-in Tools & Jobs](/capabilities/tools-and-jobs) — `jobs`, `cancel_job`, and background execution - [Manifests Reference](/reference/manifests) — complete manifest reference --- # Codemode Codemode lets the model write a short script to orchestrate tool calls instead of issuing them one turn at a time. Intermediate tool outputs stay inside the script, and only what the script prints and returns enters the conversation context. In `poo`, codemode is not a privileged escape hatch: it is wired through `poo`'s nested-call seam (`poo.NestedCaller`). Every tool call a script makes passes through the same permission engine, doom-loop detector, and session log as a direct call from the model. ## How it works 1. The model invokes the `codemode` tool with a `script` argument. 2. `poo` runs the script inside a sandboxed engine (`poo/codemode.Engine`) that exposes no host filesystem, network, or timers — only the session's offered tools. 3. Each tool call the script makes is dispatched through `poo.NestedCaller`: - **Permissions:** Every nested call is judged individually by the [permission policy and asker chain](/operations/permissions-and-safety). A refusal or error is returned to the script as structured data (`outcome`, `is_error`) rather than crashing the run. - **Doom-loop detection:** Repeated identical or near-identical calls inside a script count toward the session's doom-loop thresholds. - **Session logging:** Each nested call is recorded in the [session log](/reference/session-log-v0) with mode `"nested"` and the parent `codemode` call's handle. - **Single-level nesting:** A script cannot invoke `codemode` itself. 4. Nested tool calls keep up to 1,000,000 characters of output internally so the script can filter or summarize large results. Only the script's printed lines and final return value are sent back to the model, bounded by `output_cap_chars` and the session's observation cap. 5. If a script fails or times out partway through, `poo` still reports the call count and prior printed output. The model can then see what already ran. ## Engines `poo` ships two engines behind the `poo/codemode.Engine` interface. A custom binary that links no engine offers no `codemode` tool; see [Build Your Own Binary](/extending/custom-binary) for wiring engines. ### QuickJS (default) `poo/codemode/quickjs` runs QuickJS-NG compiled to WebAssembly under `wazero`. It requires no Node.js installation, mounts an inert null filesystem, and provides no network or timer APIs. A script is the body of an async JavaScript function: ```js const files = await Promise.all([ tools.read({ path: "README.md" }), tools.read({ path: "go.mod" }), ]); return files.map((r) => (r.is_error ? r.text : r.text.split("\n")[0])); ``` Key primitives: - `await tools.(args)` invokes a session tool and resolves to `{ handle, tool, outcome, text, is_error, structured }`. `structured` is a native JSON value (or `null` when absent; invalid JSON remains a string). - `Promise.all([...])` batches calls together. A batch executes concurrently when every call in it is read-only; otherwise calls run in submission order. - `await parallel(() => [...])` overlaps independent calls, including writes. Tool promises must be created synchronously inside the callback and returned once each: ```js const [a, b] = await parallel(() => [ tools.edit({ path: "a.txt", old: "draft", new: "final" }), tools.edit({ path: "b.txt", old: "draft", new: "final" }), ]); ``` If two `poo` writes overlap on the same resolved path in one process, one returns `is_error: true` with `structured: { code: "edit_conflict" }`. `poo` does not detect shell command conflicts or roll back a batch. - `print(value)` appends a line to the script's output; `return value` returns a JSON value. - Batches run in submission order, with at most 16 calls per batch. ### Starlark `poo/codemode/starlark` runs scripts in Starlark, a deterministic Python-like dialect with no file, network, clock, module-loading, or recursion capabilities, and an explicit execution-step budget (`exec_steps`). Enable it with `tools.codemode.engine: starlark`: ```yaml tools: codemode: engine: starlark exec_steps: 250000 ``` Starlark builtins: - `call(name, args)` runs one tool call and returns a dict with `handle`, `tool`, `outcome`, `text`, `is_error`, and `structured`. - `gather([(name, args), ...])` runs a batch of up to 16 calls in list order (concurrently when all calls are read-only, sequentially otherwise). - `json.decode(text)` and `json.encode(value)` convert between JSON strings and Starlark values. - `print(x)` records an output line. - `exit(value)` ends the script and returns `value` as JSON. ## Background execution `codemode` supports background execution like other [background-capable tools](/capabilities/tools-and-jobs). Pass `background: true` on the tool call to run the script as a background job: - The script's nested tool calls continue running after the originating turn ends, up to the job's timeout (`jobs.timeout_s`). - Its output and return value arrive as a job result when the script finishes. - Nested calls inside a batch cannot themselves request background jobs. ## Configuration Configure codemode under `tools.codemode` in your settings file (see [Settings Reference](/reference/settings)): ```yaml tools: codemode: engine: quickjs # or "starlark" timeout_s: 120 # seconds per run script_max_bytes: 65536 output_cap_chars: 16384 ``` | Key | Type | Default | Description | | --- | --- | --- | --- | | `tools.codemode.engine` | string | `"quickjs"` | Script runtime: `"quickjs"` or `"starlark"`. | | `tools.codemode.timeout_s` | int | `120` | Wall-clock limit for one script run, in seconds. | | `tools.codemode.script_max_bytes` | int | `65536` | Maximum accepted script length in bytes (64 KiB). | | `tools.codemode.output_cap_chars` | int | `16384` | Maximum printed characters retained before truncation (16 KiB). | | `tools.codemode.exec_steps` | int | `10000000` (Starlark) | Execution step budget. Supported by Starlark only; setting it with QuickJS (or an unset engine) is a configuration error. | To disable codemode in a session or profile, add `codemode` to `tools.disabled` or `profiles..tools.disabled`. --- # Skills Skills are reusable task instructions stored as `SKILL.md` files on disk. Instead of injecting every skill's full body into the system prompt, poo uses progressive disclosure. The prompt lists a compact catalog of skill names, one-line descriptions, and file paths. The model reads a skill's `SKILL.md` with `read` only when its description matches the task. Offering thirty skills costs thirty catalog entries in the system prompt rather than thirty full documents. ## Directory layout and `SKILL.md` format Each configured skills directory is scanned one level deep for subdirectories containing a `SKILL.md` file. Symlinks to directories are followed, so shared skill collections work without copying files. ```text ~/.agents/skills/ release-checklist/ SKILL.md scripts/check.sh sql-review/ SKILL.md ``` A `SKILL.md` begins with YAML front matter delimited by `---`: ```markdown --- description: Run the pre-release verification checklist before tagging a version. --- # Release Checklist 1. Run `go test ./...` and confirm a clean working tree. 2. Check `./scripts/check.sh` against the target tag. ``` - **Skill name:** Derived from the subdirectory name (for example, `release-checklist`). - **`description`:** Required for a skill to appear in the catalog. Multi-line descriptions are collapsed to a single line, trimmed to the first sentence, and capped at 200 runes. - **Relative references:** Skills can reference companion files such as `scripts/check.sh`. The prompt instructs the model to resolve relative paths against the skill's directory (the parent of `SKILL.md`). - **Filtering and errors:** - A subdirectory without `SKILL.md`, without YAML front matter, or with an empty `description` is silently skipped. - A `SKILL.md` whose YAML front matter fails to parse causes the build to fail. - **Name collisions:** Directories are scanned in order (`user_path` or `default` first, then `skills.paths`, then `POO_SKILLS_PATH`). When two directories define the same skill name, the first directory wins. The rendered catalog is sorted alphabetically by skill name. ## Configuration Configure skill discovery under `skills` in your settings file: ```yaml skills: default: true paths: - .agents/skills - ~/team-skills ``` | Field | Type | Behavior | | --- | --- | --- | | `skills.default` | bool | When `true`, loads skills from `~/.agents/skills`. If that directory does not exist, it is silently ignored. Mutually exclusive with `skills.user_path`. | | `skills.user_path` | string | Path to your personal skills directory (supports `~/`). If the path is missing or not a directory, poo emits a warning and skips it. Mutually exclusive with `skills.default`. | | `skills.paths` | list of strings | Additional skill directories, resolved relative to the working directory (or `~/`). Missing or non-directory paths are dropped with a warning rather than failing the build. | You can also append skill directories via the `POO_SKILLS_PATH` environment variable (OS path-list separated). Inspect the resulting `skills` prompt section with [`poo prompt --pretty`](/configuration/profiles-and-prompts#inspecting-the-rendered-prompt). ## Hiding a skill from model invocation Set `disable-model-invocation: true` in a skill's front matter to keep it out of the model's `` catalog: ```markdown --- description: Force-push and rewrite release tags after a botched publish. disable-model-invocation: true --- ``` The model is never told the skill exists and will not proactively invoke it. A user can still explicitly ask the model to read and follow that `SKILL.md` file when needed. ## Interaction with restricted `read` When `tools.read.restrict_to_working_dir: true` confines the `read` tool to the session's working directory (see [Permissions & Safety](/operations/permissions-and-safety)), skill files typically live outside that directory (such as `~/.agents/skills`). poo automatically registers every loaded skill directory as an additional read root for the session's `read` tool: - The model can read any `SKILL.md` and companion files inside loaded skill directories even when `read` is restricted to the working directory. - This applies to every loaded directory, even when none of its skills appear in the catalog. Even if every skill sets `disable-model-invocation: true`, the directory stays readable so a user can direct the model to follow it. - `tools.protected_paths` is still enforced and continues to block protected files. --- # Built-in Tools & Jobs `poo` ships a focused set of built-in tools. Profiles choose which tools a session offers; settings can narrow file-tool reach, tune limits, or remove individual tools with `tools.disabled`. ## Built-in tools overview | Tool | Class | Primary arg | Backgroundable | Purpose | |---|---|---|---|---| | `bash` | `side_effecting` | `command` | Yes (`background: true`, `/bg`) | Run one command via `/bin/bash -c` | | `read` | `read_only` | `path` | No | Read text line ranges, images, or audio | | `edit` | `side_effecting` | `path` | No | Exact-string replacement (or file creation) | | `write` | `side_effecting` | `path` | No | Create a new file (refuses existing files) | | `grep` | `read_only` | `pattern` | No | RE2 regex search across a directory tree | | `fetch` | `read_only` | `url` | No | HTTP(S) GET with HTML-to-Markdown conversion | | `history` | `read_only` | `pattern` | No | Read or search retained session turns | | `finish` | `read_only` | — | No | Opt-in typed JSON result validated by schema | | `jobs` | `read_only` | — | No | List running jobs, held results, and feeds | | `cancel_job` | `read_only` | — | No | Stop a running job or feed | ## `bash` Runs a shell command via `/bin/bash -c` in the session's working directory, inside its own process group. When a call finishes, times out, or is cancelled, `poo` signals the entire process group (`SIGTERM`, then `SIGKILL` after a 2-second grace period). **Arguments:** - `command` (string, required): Shell command to execute. - `timeout` (number, optional): Foreground timeout in milliseconds. Clamped to 10 minutes (`600000` ms), and can shorten — never exceed — `tools.bash.timeout_s`. Defaults to 120 seconds when unconfigured. Background calls use `jobs.timeout_s` instead. - `description` (string, optional): Human-readable summary for the event stream and transcript. Permission asks always show the raw `command`, never `description`. **Output & caps:** - Captures up to **1 MiB** of output; excess output is drained and flagged with `truncated: true`. - Observations are capped at `min(30000, floor(0.06 × context_limit × 3.5))` characters. Longer output is elided in the middle (`output_head`, `output_tail`, `elided_chars`, `hint`). - Returns a JSON envelope with `returncode` (`null` if killed/timed out) and `timed_out`. Timeouts and signal kills are marked as recoverable errors so the model does not mistake partial output for success. **Settings:** ```yaml tools: bash: timeout_s: 120 executor: local # or bwrap (see Sandboxing) env: scrub: [OPENAI_API_KEY, ANTHROPIC_API_KEY] # passthrough: [PATH, HOME, TERM] # exclusive allowlist ``` ## `read` Reads text files by line range, or returns image and audio files as native model attachments. **Arguments:** - `path` (string, required): File path (relative to working directory or absolute). - `offset` (integer, optional): 1-indexed starting line (default `1`). - `limit` (integer, optional): Number of lines to return (default `2000`). **Text behavior:** - Lines longer than `2000` characters are truncated so minified files cannot flood context. - Output is capped at `min(70000, floor(0.10 × context_limit × 3.5))` characters. - Prefixes output with `[ · lines – of ]` (and `· capped` when truncated). - Non-media binary files (containing a NUL byte in the first 8 KiB) are refused with a hint to use `grep` or a command. **Image and audio attachments:** `read` sniffs file headers before the binary check: - **Images**: Returned as `image` attachments up to **5 MB** when the active model declares `image` in `inputs`. - **Audio**: `audio/wav` (`RIFF…WAVE`) and `audio/mpeg` (`ID3` or MP3 frame header) returned as `audio` attachments up to **25 MB** when the active model declares `audio` in `inputs`. - If the active model does not support that modality or the file exceeds the size limit, `read` returns a one-line text description. This avoids sending an attachment the provider would reject. **Reach & protection:** - `tools.read.restrict_to_working_dir: true` confines reads to the working directory (configured [skills](/capabilities/skills) roots remain readable). - `tools.read.ask_outside_working_dir: true` routes reads outside the working directory through the permission asker. - `tools.protected_paths` blocks matching paths before opening the file. ## `edit` Replaces an exact string in a file, or creates a missing file when `old` is empty. **Arguments:** - `path` (string, required): Target file path. - `old` (string, required): Exact text to replace. Empty string creates a missing file; rejected if the file already exists. - `new` (string, required): Replacement text. - `replace_all` (boolean, optional): Replace every occurrence instead of requiring a unique match. **Safety guarantees:** - Fails loudly if `old` is not found or matches more than once without `replace_all: true`. - Writes atomically and preserves the existing file's permission mode. - Guards against concurrent edits to the same file (`{"code": "edit_conflict"}`). - Honors `tools.edit.restrict_to_working_dir`, `tools.edit.ask_outside_working_dir`, and `tools.protected_paths`. ## `write` Creates a new file with the given content, creating missing parent directories as needed. **Arguments:** - `path` (string, required): Path of the file to create. - `content` (string, required): File contents. `write` refuses to overwrite an existing file and directs the model to `edit`. It uses the same concurrent-write reservation (`edit_conflict`) and respects `tools.write.restrict_to_working_dir`, `tools.write.ask_outside_working_dir`, and `tools.protected_paths`. ## `grep` Searches files in a directory tree using Go's RE2 regular expression engine — no external `ripgrep` binary required. **Arguments:** - `pattern` (string, required): RE2 regular expression. May be empty only when `mode` is `files_with_matches` (lists files). - `path` (string, optional): Directory to search (defaults to working directory). - `glob` (string, optional): Path filter matched against paths relative to the search root (e.g., `*.go`). - `mode` (string, optional): `content` (default, matching lines), `files_with_matches`, or `count`. **File selection & limits:** - Inside a git work tree, `grep` asks `git ls-files --cached --others --exclude-standard` so `.gitignore` rules apply. The `git` invocation isolates config and disables hooks/fsmonitor (`core.fsmonitor=false`, `core.hooksPath=/dev/null`, scrubbed environment). - Outside a git work tree, `grep` walks the directory and skips dot-directories. - Symlinks, binary files (NUL byte in first 8 KiB), and `tools.protected_paths` are skipped (the footer reports how many protected files were skipped). - Defaults to `250` results, `2000` characters per line, and the session's observation cap. - Honors `tools.grep.restrict_to_working_dir` and `tools.grep.ask_outside_working_dir`. ## `fetch` Performs a read-only HTTP(S) `GET` request and returns the response body as text. **Arguments:** - `url` (string, required): `http://` or `https://` URL. - `format` (string, optional): `markdown` or `raw`. Defaults to `markdown` for `text/html` and `application/xhtml+xml` responses, and `raw` for all other text types (`text/*`, JSON, XML, JavaScript, or valid UTF-8). **Behavior:** - Follows up to **5 redirects**. - Non-text / binary bodies return headers and metadata only. - Output is capped at `tools.fetch.max_bytes` during download and elided to the observation cap when rendered. **Private-host guard:** `fetch` validates resolved IP addresses at dial time and dials the validated IP directly to prevent DNS rebinding. It also checks hosts on every redirect and when an environment proxy (`HTTP_PROXY` / `HTTPS_PROXY`) is active: - **Blocked by default (liftable)**: Loopback (`127.0.0.0/8`, `::1`) and private ranges (RFC 1918, `fc00::/7`). Set `tools.fetch.allow_private_hosts: true` to allow them. - **Always blocked (never liftable)**: Link-local addresses (including cloud metadata `169.254.169.254`), unspecified addresses, `0.0.0.0/8`, `100.64.0.0/10` (CGNAT), `198.18.0.0/15`, and `fec0::/10`. **Settings:** ```yaml tools: fetch: timeout_s: 30 # default: 30 max_bytes: 4194304 # default: 4 MiB user_agent: "poo-fetch" # default: poo-fetch allow_private_hosts: false # default: false ``` ## `history` Reads or searches turns retained in the session's store, including turns that [context compaction](/capabilities/compaction) replaced in the model's active view. **Arguments (mutually exclusive):** - `turn` (integer): 1-indexed turn number to read whole (truncated to the observation cap). - `pattern` (string): RE2 regular expression to search across retained turns (up to `250` matches, `2000` characters per line, capped at the observation cap). ## `finish` An opt-in read-only tool for headless runs that require structured JSON output instead of freeform prose. Enable it by setting `finish.schema_file` in settings (relative to the settings file, or `~/` under home): ```yaml finish: schema_file: ./result-schema.json ``` `poo` wraps your schema in `{"result": }` and exposes `finish` to the model. On call: - Arguments are validated against the schema (`type`, `properties`, `required`, `enum`, `items`, `additionalProperties`). - Validation errors are returned as recoverable tool errors so the model can fix its payload and call `finish` again. - A valid call records the structured result and settles the run as finished. ## `jobs` and `cancel_job` Automatically registered by the core whenever a session has backgroundable tools or feeds (cannot be removed via `tools.disabled`): - `jobs` (no arguments): Lists all running background jobs, held job results, and session feeds (`feed:` or `feed:[scope]`) with status and elapsed time. - `cancel_job` (`{"job": "j3"}` or `{"job": "feed:inbox"}`): Stops a running job (delivering its partial output as its result) or stops a running/suspended feed. --- ## Background jobs Long-running commands and RPCs can run asynchronously as session-owned background jobs. ### Starting a background job (`background: true`) Any tool that allows background execution — `bash`, `call_cli` (and promoted CLI registry tools), `call_mcp`, and `codemode` — accepts an extra `"background": true` argument: ```json { "command": "go test ./...", "background": true } ``` - The call returns immediately with a job handle (for example `j1`). - There is no `wait_job` tool: the model ends its turn and receives the job's result later as an incoming message. - Starting a duplicate background job with the same tool and canonical arguments as an already-running job is refused. - A job belongs to the **session**, not the run: it keeps running after the turn ends and survives run cancellation or interrupts. Only `cancel_job`, the job timeout, or closing the session stops it. ### Promoting a running call (`/bg`) In `poo repl`, typing `/bg` while a foreground `bash`, `call_cli`, or `call_mcp` call is running detaches it into a background job without restarting the process: - The promoted job survives run cancellation. - **Timeout caveat**: A promoted `bash` call keeps its original foreground timeout rather than switching to `jobs.timeout_s`. Pass `background: true` at launch when a command needs the full job timeout. ### Job settings (`jobs.*`) ```yaml jobs: max_running: 64 # default: 64 concurrent jobs per session timeout_s: 1800 # default: 1800s (30 minutes) per job on_idle: wake # wake (default) or hold max_unattended_wakes: 0 # default: 0 (unlimited) ``` | Setting | Default | Behavior | |---|---|---| | `jobs.max_running` | `64` | Maximum concurrent background jobs per session. Further background calls are refused until a job finishes or is cancelled. | | `jobs.timeout_s` | `1800` | Per-job wall-clock timeout in seconds (30 minutes). | | `jobs.on_idle` | `wake` | What happens when a job result arrives while the session is idle. `wake` starts a new run with the result; `hold` queues it until the next run starts. | | `jobs.max_unattended_wakes` | `0` | Maximum consecutive woken runs with no client input in between (`0` = no limit). Once reached, subsequent results are held (`wake_limit`) until the user sends input. | ## Related - [CLI Registry & Script Tools](/capabilities/cli-registry) — add custom tools via JSON manifests - [MCP Servers](/capabilities/mcp-servers) — connect stdio MCP servers and resource feeds - [Feeds & Daemon](/capabilities/feeds-and-daemon) — long-lived event feeds and idle wake policies - [Permissions & Safety](/operations/permissions-and-safety) — rules, askers, protected paths, and doom-loop detection - [Sandboxing (bwrap)](/operations/sandbox) — isolate `bash` and CLI registry commands with bubblewrap --- # Permissions & Safety Every tool call passes through the permission policy (`poo/perm`) before it executes. The policy runs as the first before-tool hook and resolves each call to either **allow** or **deny**. Calls configured to **ask** block on the asker chain until an asker answers or the chain falls back. ## Evaluation Order The policy evaluates each tool call in a fixed order: 1. **Doom-loop detection** — checks exact and near repeat counts first, including for malformed calls that failed argument preparation. 2. **Policy rules** — checks `permission.rules` in order; the first matching rule wins. 3. **Outside-working-dir asks** — if the tool sets `ask_outside_working_dir: true` and the target path resolves outside the working directory, routes the call to `ask` (bypassing both read-only auto-allow and `permission.unmatched`). 4. **Read-only auto-allow** — any remaining unmatched `read_only` tool call is allowed. 5. **Unmatched action** — any remaining unmatched `side_effecting` tool call takes `permission.unmatched`. ## Permission Rules Rules live under `permission.rules` and are evaluated top to bottom. Each rule must specify `action` (`allow`, `ask`, or `deny`) and match either a `tool` name or a `class` (`read_only` or `side_effecting`), never both. ```yaml permission: unmatched: ask fallback: deny rules: - tool: bash command_contains: ["rm -rf", "sudo", "curl | sh"] action: ask - tool: bash command_prefix: "git status" action: allow - tool: fetch command_prefix: "docs.example.com" action: allow - tool: fetch command_prefix: "https://api.example.com/v1/" action: allow - class: read_only action: allow ``` ### Rule Fields | Field | Applies to | Description | |---|---|---| | `tool` | Exact tool name | Matches a single tool (e.g., `bash`, `edit`, `fetch`). Mutually exclusive with `class`. | | `class` | Tool class | Matches `read_only` or `side_effecting` tools. Mutually exclusive with `tool`. | | `command_prefix` | Named `tool` only | Matches the prefix of the tool's primary argument (`command` for `bash`, `url` for `fetch`). Mutually exclusive with `command_contains`. | | `command_contains` | Named `tool` only | List of non-empty substrings; matches if any substring appears anywhere in the tool's primary argument. Mutually exclusive with `command_prefix`. | | `action` | Required | `allow`, `ask`, or `deny`. | ### Prefix Matching and URL Hostname Rules For non-URL arguments such as `bash` commands, `command_prefix` trims leading whitespace and performs a plain lexical prefix check. Because compound shell commands match their leading segment (`git status && rm -rf x` matches `git status`), `command_prefix` is a heuristic rather than a security boundary. For tools whose primary argument is an absolute `http` or `https` URL (such as `fetch`), `command_prefix` uses canonical URL matching: - **With a scheme** (`https://api.example.com/v1/`): matches only that scheme, host (or its subdomains), and path prefix. - **Without a scheme** (`docs.example.com`): acts as a **hostname rule**. The call's own scheme decides, so a single rule covers both `http` and `https` URLs for that host and its subdomains. - Query strings and fragments are ignored during comparison. Adjacent hosts (such as `evil-docs.example.com`) do not match. ### Substring Matching (`command_contains`) `command_contains` matches when any listed substring appears anywhere in the tool's primary argument after trimming leading whitespace. ::: warning Tripwire, not a safety boundary `command_contains` is plain text matching. A command spelled around a substring — using extra spaces, split flags, quoting, or shell variables — will not match. Use `command_contains` as a tripwire to prompt on risky patterns, and pair it with a [bubblewrap sandbox](/operations/sandbox) when hard isolation is required. ::: ## Unmatched Calls and Fallback | Setting | CLI Flag | Default | Valid Values | Purpose | |---|---|---|---|---| | `permission.unmatched` | `--permission-unmatched` | `ask` | `allow`, `ask`, `deny` | Action for a `side_effecting` call that no rule matches. | | `permission.fallback` | `--permission-fallback` | `deny` | `allow`, `deny` | Decision when the asker chain is exhausted, times out, or has no available asker. | A policy can produce an `ask` via `unmatched: ask`, an `ask` rule, `ask_outside_working_dir`, or an explicit doom-loop `ask`. If no configured asker can ever answer in the current mode, poo emits a load-time warning naming the `fallback` decision. ## Asker Chain When a call resolves to `ask`, the policy queries the askers listed in `permission.askers` in order. Each asker can return `allow`, `deny`, or `defer` (errors, panics, timeouts, and unavailable askers all defer to the next link). The entire chain is bounded by `permission.chain_timeout_s` (default `120` seconds). Setting `permission.askers: []` explicitly configures an empty chain, sending every ask straight to `permission.fallback`. Omitting `askers` uses the binary's default chain. ```yaml permission: askers: [decide, wire] chain_timeout_s: 120 fallback: deny decide: allow: 0.85 deny: 0.99 timeout_ms: 1500 ``` ### Built-in Askers - **`decide`** — queries the configured decision model (`roles.decide`) with recent conversation turns, the working directory, and the tool call arguments. If the model's `yes` probability meets `permission.decide.allow` (default `0.85`), the call is allowed; if `no` meets `permission.decide.deny` (default `0.99`), it is denied. Any lower confidence, error, or timeout (`permission.decide.timeout_ms`, default `1500` ms) defers to the next asker. Skipped automatically if no decision model is configured. - **`wire`** — sends a `permission/ask` request to a connected `poo serve` client (such as `poo repl`) that declared the `permission_answers` capability. Default per-asker budget is `60` seconds (capped by the remaining chain timeout). Defers if no capable client is connected. ## Doom-Loop Detection The core tracks consecutive repeats of tool calls and hands the counts to the permission policy before rules are checked: ```yaml permission: doom_loop: threshold: 3 near_threshold: 5 action: ask ``` | Field | Default | Description | |---|---|---| | `threshold` | `3` | Exact repeat count (same tool and arguments) that triggers the doom-loop action. | | `near_threshold` | `5` | Near repeat count (same call shape) that triggers the doom-loop action. | | `action` | `ask` | Action taken when either threshold is reached: `allow`, `ask`, or `deny`. | When `action` is `allow` (or an asker allows the call), the repeat counter resets. When denied, the model receives a refusal message stating how many times the call was repeated so it can change approach. ## Protected Paths `tools.protected_paths` lists path globs that file tools refuse to read, search, edit, or write: ```yaml tools: protected_paths: - "**/.env" - "**/.env.*" - "~/.ssh/**" ``` Protected paths apply regardless of `restrict_to_working_dir` or `ask_outside_working_dir`. Under the `local` bash executor, `tools.protected_paths` only guards the built-in file tools — `bash` commands can still read any path the host process can. Under the `bwrap` executor, protected paths inside bound directories are masked with empty mounts. See [Sandboxing (bwrap)](/operations/sandbox) for details. ## Working Directory Boundaries By default, file tools (`read`, `grep`, `edit`, `write`) can access paths outside the session's working directory. You can confine them or require approval per tool: ### Restrict to Working Directory ```yaml tools: read: { restrict_to_working_dir: true } grep: { restrict_to_working_dir: true } edit: { restrict_to_working_dir: true } write: { restrict_to_working_dir: true } ``` `restrict_to_working_dir: true` rejects paths outside the working directory before the permission policy runs. Restricted `read` is still permitted to read the session's configured skill directories. ### Ask Outside Working Directory ```yaml tools: read: { ask_outside_working_dir: true } grep: { ask_outside_working_dir: true } edit: { ask_outside_working_dir: true } write: { ask_outside_working_dir: true } ``` `ask_outside_working_dir: true` keeps outside paths reachable, but routes calls whose resolved path lies outside the working directory through the asker chain. This runs after `permission.rules` are evaluated and overrides both `permission.unmatched` and the `read_only` auto-allow. If both `restrict_to_working_dir` and `ask_outside_working_dir` are enabled on the same tool, the restriction runs first. Only paths the restriction still permits outside the working directory (such as skill directories on `read`) reach the ask. ::: tip File tool limits do not confine `bash` Neither `restrict_to_working_dir` nor `ask_outside_working_dir` restricts `bash` commands. For process and filesystem isolation, run commands through the [bubblewrap sandbox](/operations/sandbox). ::: ## Child Environment Filtering `tools.env` controls which environment variables child processes (such as `bash` commands) inherit from the session: ```yaml tools: env: scrub: - OPENAI_API_KEY - ANTHROPIC_API_KEY - AWS_SECRET_ACCESS_KEY ``` - **`tools.env.scrub`** — removes the listed variable names from the child environment while passing through everything else. - **`tools.env.passthrough`** — restricts the child environment to *only* the listed variable names, dropping all others. Separately, a launcher can set `POO_CREDENTIAL_ENV` (colon-separated variable names on Unix) to keep credential variables available to manifests via `env:NAME` bindings while withholding them from `bash` commands. See [Sandboxing (bwrap)](/operations/sandbox) for launcher credential details. --- # The sandbox Poo runs the commands a model asks for through an **executor**. The executor decides where the command runs. There are two: | Executor | Package | What it contains | |---|---|---| | `local` (default) | `poo/tool/bash` | nothing: the command runs in poo's own process space, and it can reach anything poo can | | `bwrap` | `poo/exec/bwrap` | a bubblewrap sandbox: a namespace of its own, with a filesystem of its own | The `bwrap` executor is Linux-only, and it is opt-in: a binary links the executors it wants, and a session picks one by name. A name the binary does not link is a configuration error, and so is a `bwrap` that cannot start. Neither falls back to the local executor. ## What the `bwrap` executor contains The command runs in a bubblewrap sandbox with: - **Every namespace it can have.** The command does not see the host's processes, its cgroups or its host name. - **A fresh `/proc`, `/dev` and `/tmp`.** The command sees its own processes and nobody else's. - **The system directories, read-only:** `/usr`, `/bin`, `/lib`, `/lib64` and `/etc` by default. The settings may name a different list. - **The working directory, read-write.** It is the only place the command can write, beside the extra read-write binds the settings name. - **The network**, unless the settings cut it (`tools.bwrap.network: false`). The network is the host's, and with it the resolver's directory (`/run/systemd/resolve`) is mounted read-only, because `/etc/resolv.conf` is often a link into it. - **The fetch tool is not a command**, and the sandbox does not see it: the fetch runs in poo's own process, over the host's network, whatever `tools.bwrap.network` says. What bounds it is the tool's own guard: loopback and private addresses are refused unless `tools.fetch.allow_private_hosts` says otherwise, and link-local and the reserved ranges are refused whatever the settings say. A session that must not reach the network disables the tool (`tools.disabled: [fetch]`). `$HOME` is not mounted. The operator's files are not the command's, unless a bind names them. ### Protected paths A protected path inside a bound directory is masked: a directory behind an empty tmpfs, a file behind an empty device. The executor asks the matcher about every bind, so this covers the working directory, the read-only system directories and the extra read-write binds alike. The command reads nothing where the configuration protects something. A protected path outside every bound directory is not in the sandbox at all. A protected path that is a link is masked where the link points, because a mount cannot land on a link. The expansion of a bind is reused by the commands that follow, so a large read-only bind is walked once, not once per command. The `local` executor cannot do this. Protected paths stop the file tools from wandering; with the `local` executor, `bash` reaches everything the process can. The paths are the settings' `tools.protected_paths`, and `examples/code.settings.yaml` shows the setting with a commented example: the operator's own secrets, protected from a model that goes looking. ### What ends the sandbox The sandbox ends when the command ends, and the kernel ends a namespace when its init dies. A descendant that leaves the process group (`setsid`, a double fork into a new session) therefore dies with the call, which is the escape the `local` executor cannot close. A background job runs in a sandbox of its own, and `cancel_job` or `session/close` stops it the same way. The sandbox ends with poo as well. The helper that runs the command is the sandbox's init, and it holds one end of a pipe whose other end poo holds: the kernel closes it when poo ends, and the helper takes the command down and exits, which ends the namespace. The executor also starts bubblewrap with `--die-with-parent` and the parent-death signal, so the bubblewrap process does not outlive poo either. A poo that is killed without a teardown therefore leaves no sandbox behind. The `local` executor has no such tie, so a command it runs outlives a killed poo. ## Launcher credentials A launcher can set `POO_CREDENTIAL_ENV` to the names of credentials poo's feeds or registered tools need. Separate names with the operating system's path-list separator (`:` on Linux and macOS). The variable lists names, not their values; the launcher supplies the values separately. The session environment keeps these values, so a feed or a registered tool can receive one through an explicit manifest `env:NAME` binding. A `bash` command does not inherit the declared names in its environment. A registered tool that receives a credential can still use or disclose it, so trust its manifest and command. This differs from `tools.env.scrub`, which removes names from the session environment too. A feed or tool binding cannot resolve a name removed there or excluded by `tools.env.passthrough`. Environment scrubbing is not process isolation: with the `local` executor, a command can read poo's environment through procfs as described below. ## Registered tools A registered tool — whether the session offers it directly or runs it through `call_cli` — runs where a bash command runs: through the session's executor, with the sandbox's binds and the protected paths it masks. - **The command is the one its manifest names**, and the executor wraps it the way it wraps a shell command. A `bwrap` session runs it in the sandbox, and a protected path is masked there. - **Its directory** is the manifest's when the manifest fixes one, and the session's working directory otherwise. - **Its environment** is the session's environment, already scrubbed: the benign names the tool needs (`PATH`, `HOME`, `LANG`, `LC_ALL`, `TMPDIR`) come from it, then the variables the manifest declares, with an `env:NAME` reference resolved against the scrubbed environment, and a `session:id` reference resolved to the session's own ID at the call. A name the scrub removed, or a `tools.env.passthrough` list left out, is a reference the call cannot honour, and it fails naming the variable. A manifest can explicitly pass a credential declared through `POO_CREDENTIAL_ENV` using an `env:NAME` binding. - **Its arguments** were checked against the manifest's schema before the process started, so a malformed call never runs. The same check, in the library, refuses a value that begins with a dash when the manifest passes it as an argument of its own (`style: space`), because a command whose flag takes no value would read it as another flag. The rule belongs to `cli-registry` (`specs/argv.md` there): the call fails its validation, naming the property, before argv exists. Bind the property `equals` to pass a value that looks like one — a dash-leading value inside one `--flag=value` element is not an option, even when it spells one the manifest fixes itself. - **Its lifetime** is the plan's timeout, enforced by poo, and the run's context: a timeout, an interrupt, a cancel, a close or `--no-wait-jobs` stops the tool and everything it started in its process group. - **The output is bash's envelope**: both streams, the exit status, null for a killed process, and the partial output of a timeout. The `local` executor still cannot hide what it does not own: a tool it runs can read poo's own environment through `/proc/$PPID/environ`, because the process that started it is poo. The `bwrap` executor closes that, because the tool's parent is inside the sandbox's pid namespace. Scrubbing stops a manifest reference; only isolation stops procfs. ## What the `bwrap` executor does not contain **It is not a security boundary against hostile code.** - **The kernel is the host's.** The sandbox is a namespace, not a kernel: a kernel bug is reachable from inside it. - **The network is the host's**, unless it is cut. With the network on, the command can reach anything the host can reach, and the host can reach the command's ports. - **The user is the host's user**, in a user namespace. The files the user owns are readable whenever they are bound. - **A bind is a hole.** A read-write bind hands the command the directory it names, whatever is in it. The sandbox is for keeping a model's commands inside the task: the working directory, the fixtures, and nothing else. It is not for running code you do not trust. ## Running all of poo inside a sandbox The executor keeps the model's commands apart from poo. When the whole process has to be contained -- a run on a shared machine, a run that must not see the operator's files at all -- run poo itself inside bubblewrap or a container. That is the portable option, and the only one on macOS, where namespaces are not available to an unprivileged process. A whole-process sandbox for a poo run: ```sh bwrap \ --unshare-all --share-net --die-with-parent --new-session \ --ro-bind /usr /usr --symlink usr/bin /bin --symlink usr/sbin /sbin \ --symlink usr/lib /lib --symlink usr/lib64 /lib64 \ --ro-bind /etc /etc \ --ro-bind-try /run/systemd/resolve /run/systemd/resolve \ --proc /proc --dev /dev --tmpfs /tmp \ --bind "$PWD" /work \ --chdir /work \ --setenv HOME /tmp \ -- poo run --working-dir /work --log /work/session.jsonl "..." ``` The container is the same idea with a different tool: ```sh docker run --rm -it --network none -v "$PWD:/work" -w /work ghcr.io/sdougbrown/poo \ poo run --working-dir /work --log /work/session.jsonl "..." ``` The eval harness does the first of these: `poo-eval run --isolation bwrap` wraps the whole `poo` process, and `poo-eval run --executor bwrap` wraps the model's commands in a sandbox of their own, bound to the task's workdir. The two are layers, not alternatives: a run may use both, and each closes what the other leaves open. --- # Sessions & Durability Poo persists session transcripts, tool outcomes, permission decisions, and run state as append-only records. For the exact on-disk record schemas, see [Session Log v0](/reference/session-log-v0). ## Persistence Modes Configure persistence with `session.mode` (or `--ephemeral` on the CLI): | Mode | Persistence | Crash Behavior on Reload | |---|---|---| | `logged` (default) | Writes one JSONL file per session under `session.dir` (`~/.local/state/poo/sessions` by default). | Truncates torn tails; settles unfinished runs, in-flight tool calls, and jobs as `interrupted`. | | `ephemeral` | Keeps records in memory for the lifetime of the process. Writes nothing to disk. | Cannot be loaded or resumed. | | `durable` | Persists records (JSONL or SQLite) under `session.dir` with lease-based ownership. | Truncates torn tails and builds a continuation plan to resume the unsettled run instead of settling it interrupted. | ```yaml session: mode: durable dir: ~/.local/state/poo/sessions durable: store: sqlite lease_ttl_s: 30 max_resumptions: 3 auto_resume: false ``` ## Storage Backends: JSONL vs. SQLite Logged sessions always use the file-backed JSONL store. Durable sessions select a backend via `session.durable.store`: | Backend | Setting Value | Files on Disk | Locking / Ownership | |---|---|---|---| | **File (JSONL)** | `file` (default) | `/.jsonl`, `/.lock` (and `/.lease` when leased) | `flock` for `logged`; lease file + short critical-section `flock` for `durable`. | | **SQLite** | `sqlite` | `/sessions.db` (WAL journaling) | Row-based leases in the `leases` table; every write and lease transition runs in an immediate transaction. | SQLite stores session metadata in `sessions`, append-only records in `records`, and ownership leases in `leases` with indexed queries. ## Locking and Lease TTLs Poo enforces single-writer exclusivity on every open session: - **File lock (`flock`)** — Used by `logged` sessions. Opening a session acquires an exclusive non-blocking `flock` on `.lock` and holds it until the store closes. If the process crashes, the OS kernel releases the lock immediately so another process can recover the session. - **Lease authority (`lease_ttl_s`)** — Used by `durable` sessions (and all SQLite-backed sessions). Opening a session acquires a lease with a unique 16-byte fencing token and a TTL configured by `session.durable.lease_ttl_s` (default `30` seconds). A background heartbeat renews the lease every `TTL / 3` seconds. - While the lease is live, another process attempting to open the session is refused with `ErrSessionLocked`. - If the owner dies or stops heartbeating past `expires_at`, a new owner can take over the lease. The takeover logs a warning naming the previous owner and expiry time. - Once a lease is lost or taken over, the previous owner is fenced by its token. Subsequent writes fail with `ErrLeaseLost`, and late releases leave the new owner's lease untouched. ## Crash Recovery and Resumption Loading a stored session (`session/load` over the wire, `session.Resume` in Go, or `poo repl --continue` / `--resume`) scans the session log and recovers any incomplete state. ### Logged Recovery 1. Any torn trailing JSONL line from a mid-write crash is truncated. 2. Unsettled runs are marked `interrupted`. 3. In-flight tool calls and background jobs without results receive an `interrupted` outcome (`outcome unknown; the process stopped during this call` / `...this job`) so the model knows the effect is uncertain. 4. Undelivered job results are re-queued for the session. ### Durable Recovery (`auto_resume` and `max_resumptions`) Instead of settling the latest unfinished run as interrupted, `durable` mode runs the `DurablePlanner` to build a continuation plan: - **Tool calls** — `read_only` calls, `idempotent` tools, and side-effecting calls whose start record never landed are scheduled for replay. Side-effecting calls that already started are settled as `interrupted` so the model can decide how to proceed. - **Permission asks** — Asks whose wall-clock deadline has not passed remain live and are re-armed; expired asks are resolved using their recorded `fallback` decision. - **Partial output & compaction** — Partial assistant messages and uncommitted compactions are discarded cleanly; the run resumes at the appropriate phase (`requesting`, `streaming`, `executing`, or `waiting`). - **Session jobs & feeds** — Running jobs and in-flight feed attempts died with the previous process and are ended as `interrupted`; feed subscriptions are restored. Two settings control resumption behavior: - **`session.durable.max_resumptions`** (default `3`) — Maximum number of times a single run may be resumed across crashes. Once reached, the planner stops continuing the run and settles it as `interrupted` with `resumption_limit` to prevent infinite crash loops. - **`session.durable.auto_resume`** (default `false`) — When `false`, a loaded durable session holds its continuation plan idle until explicitly resumed. When `true`, loading the session automatically resumes the unsettled run. ## Explicit Log Path (`--log`) On `poo run`, `--log ` writes the session log to a specific file path instead of `session.dir`. ```bash poo run --log ./traces/build-fix.jsonl "Fix the failing unit tests" ``` `--log` always creates a new file and refuses to extend or overwrite an existing file. ## Managing Sessions ### Listing Sessions `poo sessions list` inspects the configured session directory (override with `--session-dir`): ```bash poo sessions list poo sessions list --json ``` Table columns: `ID`, `CREATED`, `PROFILE`, `RUNS`, `REASON`, `SIZE`, and `LOCKED`. ### Pruning and Retention Retention is opt-in — without a configured policy or CLI flags, `poo sessions prune` deletes nothing and exits with a usage error. Configure defaults in settings under `session.retention`: ```yaml session: retention: max_age_days: 30 max_sessions: 200 ``` Run `poo sessions prune` to apply the configured policy or override it with flags: ```bash # Preview what would be deleted poo sessions prune --dry-run # Delete sessions with no activity in the last 14 days, keeping at most 50 poo sessions prune --older-than 14 --keep 50 ``` | Setting | CLI Flag | Description | |---|---|---| | `session.retention.max_age_days` | `--older-than ` | Delete sessions whose last activity is older than this many days. | | `session.retention.max_sessions` | `--keep ` | Keep at most this many most recently active sessions. | | — | `--dry-run` | Print sessions that would be deleted without removing them. | Sessions currently held by another process (`LOCKED: true`) are always skipped during pruning. --- # Limits & Exit Codes `poo` enforces explicit per-run limits and maps every run outcome to a distinct process exit code. Scripts, CI jobs, and supervisors can distinguish natural completion from budgets, provider failures, and configuration errors. ## Run Limits Configure run limits under `limits` in your settings file (see [Settings Reference](/reference/settings)). Every limit must be non-negative (`>= 0`). Setting a budget to `0` disables it, except `max_continuations`, where `0` selects the default (`3`). | Setting | Type | Default | CLI Flag (`poo run`) | Settle Reason (Exit Code) | Description | |---|---|---|---|---|---| | `limits.max_tokens_per_run` | int | `0` (off) | — | `budget_exhausted` (`14`) | Total token budget for a single run (settle source `max_run_tokens`). | | `limits.max_duration_s` | int (seconds) | `0` (off) | — (see `--timeout` below) | `budget_exhausted` (`14`) | Wall-clock duration budget for a run, evaluated between turns (settle source `max_duration`). | | `limits.max_turns` | int | `0` (off) | `--max-turns` | `max_turns` (`11`) | Maximum number of model turns per run. | | `limits.max_continuations` | int | `3` | — | `hook_continue_limit` (`12`) | Maximum `BeforeSettle` hook continuations allowed in one run. | | `limits.truncation_retries` | int | `1` | `--truncation-retries` | `output_truncated` (`10`) | Consecutive output-limit truncations the run asks the model to retry more concisely before settling. Set to `0` to settle on the first truncation. | ```yaml version: 1 limits: max_tokens_per_run: 500000 max_duration_s: 300 max_turns: 25 max_continuations: 3 truncation_retries: 1 ``` ### `limits.max_duration_s` vs. `poo run --timeout` These two controls are distinct: - **`limits.max_duration_s`** is a run budget. The session checks elapsed time at turn boundaries and settles cleanly with `budget_exhausted` (exit code `14`, detail source `max_duration`). - **`poo run --timeout `** sets a Go context deadline on the invocation. When the deadline expires, the in-flight request or tool call is cancelled immediately and the run settles with `cancelled` (exit code `130`, detail source `cancel:deadline`). ## Settle-Reason Exit Codes (`poo run`) Every settled run records a closed, typed `Reason` (defined in `reason.go`). `poo run` exits with the code for that reason: | Exit Code | Settle Reason(s) | Meaning | |---|---|---| | `0` | `end_turn`, `finished`, `stop_requested` | Run completed normally: the model stopped on its own (`end_turn`), called the `finish` tool with a valid result (`finished`), or stopped at a hook/stop condition's request (`stop_requested`). | | `1` | *(unclassified / operational)* | Operational failure with no settle-reason code of its own (for example, transport setup failure, session start failure, or an unknown settle reason). | | `2` | *(usage / configuration)* | Command refused its arguments, settings, working directory, or a system prompt that failed to render. | | `10` | `output_truncated` | Provider stopped at the output-token limit and all `truncation_retries` were spent. | | `11` | `max_turns` | Run reached `limits.max_turns` / `--max-turns`. | | `12` | `hook_continue_limit` | `BeforeSettle` hooks requested more continuations than `limits.max_continuations`. | | `13` | `context_exhausted` | Context window filled and could not be compacted further. | | `14` | `budget_exhausted` | Run exhausted `limits.max_tokens_per_run` or `limits.max_duration_s`. | | `15` | `invalid_turns` | Model produced unusable turns (for example, unparseable or missing tool calls) for the maximum consecutive turns allowed. | | `20` | `provider_error` | Provider request failed and could not be retried, or the retry budget was spent. | | `21` | `tool_fatal` | A tool returned a fatal error (`ErrFatal`), indicating an unusable environment. | | `22` | `hook_error` | An executable hook failed or missed its deadline. | | `23` | `store_error` | Session store failed; the session is marked broken. | | `24` | `provider_limit` | Provider refused the request for quota or plan reasons (the session itself is not broken). | | `130` | `cancelled` | Run was cancelled by `SIGINT`/`SIGTERM` or `--timeout`. | ::: tip Signal handling in `poo run` The first `SIGINT` or `SIGTERM` cancels the active run so it can settle cleanly and exit `130`. A second interrupt forces immediate session teardown (bounded to 250 ms) and exits `130`. ::: ### Precedence and Multi-Run Exit Codes - **Arbitration order:** When multiple settle candidates occur on the same turn, higher-severity reasons win. `cancelled` beats all other reasons, followed by failures (`store_error`, `hook_error`, `tool_fatal`, `provider_limit`/`provider_error`), then limits (`context_exhausted`, `hook_continue_limit`, `max_turns`, `budget_exhausted`, `invalid_turns`), and finally natural stops (`finished`, `stop_requested`, `output_truncated`, `end_turn`). - **Background job wakes:** When `poo run` waits for background jobs (unless `--no-wait-jobs` is set), job completions can wake follow-up runs within the same session. `poo run` combines exit codes across all settled runs so the **first non-zero exit code wins**; exit `0` requires every settled run to succeed. ## `poo daemon` Exit Codes `poo daemon` hosts a long-lived durable session driven by feeds (see [Feeds & Daemon](/capabilities/feeds-and-daemon) and [CLI Reference](/reference/cli#poo-daemon)). Its exit codes report daemon lifecycle status to a process supervisor: | Exit Code | Meaning | |---|---| | `0` | Clean shutdown after `SIGINT` or `SIGTERM` (feeds stopped, records flushed, lease released). | | `1` | Operational failure or **lost lease**. Happens if another process takes the lease, the store fails to open or resume, or resuming a pending run breaks the session. | | `2` | Usage, argument, settings, or invalid `--session` ID error. | --- # Architecture Poo is a modular Go agent harness designed as a library first. The core package owns the agent loop, tool registry, hook points, event stream, and session lifecycle. Everything else—tools, executors, providers, persistence stores, and the wire server—is an opt-in package wired at compile time. What a binary does not link cannot be reached at runtime. ## Package layout Packages are grouped by subsystem: ### Core and contracts | Package | Role | |---|---| | `poo` | Core agent loop FSM, tool registry, hooks, event stream, and session lifecycle | | `poo/prompt` | System prompt vocabulary: named sections, variants, and template environment | | `poo/decide` | Decision-model contract: questions, answers, `Decider`, and recording wrapper | | `poo/exec` | Executor contract (`Executor`, `Command`, `Process`), registry, and env scrubbing | | `poo/protect` | Protected-path matcher shared by tools and permission policy | | `poo/pootest` | Exported test helpers: scripted transport, in-memory sink, stub decider, scripted compactor | ### Tools and execution | Package | Role | |---|---| | `poo/tool/*` | Opt-in tools: `read`, `edit`, `write`, `grep`, `bash`, `cliregistry`, `callmcp`, `codemode`, `fetch`, `finish` | | `poo/exec/bwrap` | Linux bubblewrap sandboxing executor | | `poo/codemode/*` | Opt-in codemode engines (`quickjs`, `starlark`) | | `poo/profile/*` | Named tool profiles (`code`, `search`, etc.) with default prompt and permission posture | ### Providers, permissions, and persistence | Package | Role | |---|---| | `poo/provider/*` | Provider seam, model catalog (`provider/catalog`), and wire transports (OpenAI, Anthropic, etc.) | | `poo/perm` | Permission engine: tool call policy, doom-loop detection, and asker chain | | `poo/perm/decide` | Permission asker backed by a decision model | | `poo/session` | Session persistence seam: store, versioned codec, history projection, and locking | | `poo/session/sqlite` | Opt-in SQLite session store | ### Capabilities and integrations | Package | Role | |---|---| | `poo/cli` | CLI registry catalog and manifest loader | | `poo/feed` | Feed manifest loader, environment builder, and stdout record runner | | `poo/mcp` | MCP client: server lifecycle, tool dispatch, resource feeds, and relaunch loop | | `poo/mcp/manifest` | `mcp.json` manifest loader, launch templates, and resource feed declarations | | `poo/skill` | Skill directory discovery and `SKILL.md` frontmatter loader | ### Server, wire, and CLI | Package | Role | |---|---| | `poo/wire/protocol` | Public JSON-RPC 2.0 wire contract: method names, error codes, and request/result DTOs | | `poo/wire` | JSON-RPC 2.0 server over stdio | | `poo/wire/conformance` | Black-box protocol conformance suite and exported fake provider endpoint | | `poo/server` | `wire.Factory` implementation bridging `config` and `wire` | | `poo/config` | Opt-in settings loading, schema validation, and runtime assembly | | `poo/cmd/poo` | Reference headless CLI and `poo serve` binary | ## Stdlib-only core rule The core package (`poo`) depends only on the Go standard library plus `poo/prompt`, `poo/decide`, and `poo/scopeschema`—each of which imports only the standard library. Several contract packages are also strictly standard-library-only so clients and extensions can depend on them without pulling in the rest of the module: - `poo/wire/protocol` - `poo/prompt` and `poo/prompt/agentsmd` - `poo/decide` - `poo/exec` - `poo/protect` - `poo/caps` - `poo/scopeschema` - `poo/mcp/wire` `internal/depcheck` enforces these boundaries during `go test`. It inspects each checked package's non-test dependency closure via `go list -e -deps -json`. The test suite fails if any package imports an unapproved internal or third-party dependency. For example, only `poo/mcp` may import the MCP Go SDK. A binary that omits an MCP launcher never links that SDK. See [Build Your Own Binary](/extending/custom-binary#the-closure-gate) for how custom binaries enforce their own dependency exclusions. ## Session FSM A session moves through a closed set of explicit states (`poo.State`). Consumers add behavior through hooks rather than introducing new states. | State | Meaning | |---|---| | `idle` | The session has no active run. | | `requesting` | The run is requesting a response from the provider. | | `streaming` | The provider's response stream is arriving. | | `executing` | The run is executing tool calls requested by the model. | | `compacting` | The run is compacting the conversation view before the next request. | | `waiting` | The run is open while waiting on background jobs it started. | | `settling` | The run is finalizing and recording its settle outcome. | | `settled` | The run has completed; a new prompt transitions back to `requesting`. | All state changes pass through a single transition function checked against the legal transition table (`poo.IsLegal`): | From | Allowed next states | |---|---| | `idle` | `requesting` | | `requesting` | `streaming`, `executing`, `compacting`, `requesting`, `waiting`, `settling` | | `streaming` | `executing`, `requesting`, `compacting`, `waiting`, `settling` | | `executing` | `executing`, `requesting`, `compacting`, `waiting`, `settling` | | `compacting` | `requesting`, `waiting`, `settling` | | `waiting` | `requesting`, `compacting`, `settling` | | `settling` | `settled` | | `settled` | `requesting` | Once a run enters `settling` or `settled`, background work from the ending run cannot move it backwards; only a subsequent run moves `settled` back to `requesting`. ## Hook points Hooks extend the session lifecycle without altering the FSM. Every hook receives a `poo.HookContext` carrying the session ID, run ID, turn number, read-only `HistoryView`, `ContextBudget`, and optional `Decider`. Hooks may append to history through their return decisions, never mutate prior messages in place. | Option / Interface | When it runs | Decisions / Effect | |---|---|---| | `WithSessionStart` (`SessionStartHook`) | Once when the session is built, before the first run | Append messages, edit system prompt sections (`StartDecision`) | | `WithBeforeRun` (`BeforeRunHook`) | At the start of every run, before the first provider request | Append messages, edit system prompt sections (`StartDecision`) | | `WithPolicy` (`PolicyHook`) | Before all other `BeforeTool` hooks; reserved for the permission engine | `Allow()` or `Deny(detail)` only; exempt from hook deadline | | `WithBeforeTool` (`BeforeToolHook`) | After argument preparation and policy check, before tool execution | `Allow()`, `Deny(detail)`, or `ShortCircuit(ToolResult)` | | `WithAfterTool` (`AfterToolHook`) | After a tool call finishes, before the model sees the result | `Keep()`, `Annotate(text)`, `Replace(ToolResult)`, or `Redact(ToolResult)` | | `WithAfterTurn` (`AfterTurnHook`) | At the end of every turn, including interrupted turns | `AppendMessages(...)` or `StopTurn(detail)` | | `WithBeforeSettle` (`BeforeSettleHook`) | When the model stops on its own | `Accept()`, `Continue(Message)`, or `StopSettle(detail)` | | `WithStopCondition` (`StopCondition`) | At every turn end after the tool batch finishes | Ends the run when matched | | `WithObserver` (`Observer`) | On every session event, in order | Read-only observation; never settles a run | | `WithSessionAttach` (`AttachFunc`) | Once during live session construction (including resume), before feeds or runs | Attach session-owned subsystems (such as MCP servers) and return a close function | Hooks that are safe to re-run after a crash mid-hook on durable sessions may implement `poo.IdempotentHook`. Hooks that do not implement it are never re-executed on recovery. ## Provider-neutral message model The core maintains a single provider-neutral message representation for all supported wire APIs. It carries text, tool calls, tool results, reasoning or thinking blocks, opaque provider blocks, and image attachments. Transports translate this model to and from Chat Completions, OpenAI Responses, and Anthropic Messages without leaking provider-specific types into the core. For the exact round-trip mapping across all three APIs, see [Wire API Mapping](/reference/wire-api-mapping). --- # Build Your Own Binary Poo is a library first. A consumer composes only the packages it wants into its own binary—selecting the tools, executors, profiles, and providers it links. Anything the binary omits is not reachable at runtime because it is not compiled into the executable. `cmd/poo` is one such composition. `wire/conformance/testdata/readonly` is the smallest: it serves the `search` profile, `read`, `grep`, and the OpenAI transport, with no shell and no tool capable of mutating state. ## Wiring `server.New` and `wire.Serve` `server.New` takes loaded settings, linked tools, executors, and profiles, and returns a `*server.Server` that implements `wire.Factory`. Pass it to `wire.Serve` to expose the JSON-RPC 2.0 protocol over stdio: ```go settings, err := config.Load(*settingsPath) if err != nil { return err } srv, err := server.New(server.Options{ Settings: settings, WorkingDir: dir, DefaultProfile: search.Name, Tools: map[string]config.ToolFactory{ "read": func(config.ToolOptions) poo.Tool { return read.New() }, "grep": func(config.ToolOptions) poo.Tool { return grep.New() }, }, Profiles: []profile.Profile{search.Profile()}, Build: poo.BuildInfo{Name: "poo-readonly", Version: version}, }) if err != nil { return err } return wire.Serve(wire.Options{ In: os.Stdin, Out: os.Stdout, Factory: srv, Build: protocol.Build{ Name: "poo-readonly", Version: version, PooVersion: version, }, }) ``` ### `wire.Factory` `wire.Factory` is the seam between the wire transport (`poo/wire`) and your binary's runtime configuration. The wire server never reads settings or constructs sessions directly; it delegates to the factory: - `Profiles()`, `DefaultProfile()`, `Capabilities()`, `Roles()`: reported during the `poo/initialize` handshake. - `Create(...)` and `Load(...)`: construct or resume a `*poo.Session` for a client request, receiving a `wire.FactoryEnv` with the server's `Observer` and permission `Client`. - `Configure(...)`: applies between-run session updates (model, reasoning, prompt variant, etc.). - `Models(...)` and `Settings(...)`: serve `models/list` and `settings/get`. `server.New` implements `wire.Factory` on top of `config.Build`, caching runtimes per profile/model combination while keeping each session's store, prompt overrides, and permission asks isolated. ## Profiles, executors, and session options ### Profiles and tools `server.Options.Profiles` lists the profiles the binary offers, and `server.Options.Tools` maps tool names to `config.ToolFactory` constructors. Each map key must match the name returned by the tool's `Spec()`. A profile, permission rule, or manifest that references an unlinked tool fails validation with a typed error. Use `server.Options.SessionTools` to mutate each runtime the factory builds before creating a session. For example, it can add `finish` for structured output when settings opt into a schema no profile lists. ### Executors Register only the command executors your binary links using `exec.NewRegistry`: ```go registry := exec.NewRegistry() registry.Register("local", func(exec.Options) (exec.Executor, error) { return bash.NewLocal(), nil }) ``` Pass `registry` in `server.Options.Executors`. An executor is resolved only when a profile offers `bash` (or runs feeds or CLI registry commands). A read-only binary passes `nil` and cannot spawn commands. If settings request an executor name that is not registered, `config.Build` returns `exec.ErrUnknownExecutor` rather than falling back to another executor. ### Overrides and manifest paths `server.Options.Overrides` carries CLI flag overrides (such as `FeedsPaths`, `CLIRegistryPaths`, and `MCPPaths`). `server.New` automatically merges environment overrides (`POO_FEEDS_PATH`, `POO_CLI_REGISTRY_PATH`, `POO_MCP_PATH`, `POO_SKILLS_PATH`) via `config.EnvOverrides`. A binary that calls `config.Build` directly must call `config.EnvOverrides` itself if it wants environment path support. For manifest-driven capabilities that do not require linking custom Go tools, see: - [CLI Registry & Script Tools](/capabilities/cli-registry) - [Feeds & Daemon](/capabilities/feeds-and-daemon) - [MCP Servers](/capabilities/mcp-servers) - [Manifests Reference](/reference/manifests) ### Permission askers `permission.askers` distinguishes between an absent list and an explicit empty list: - **Absent**: uses the binary's default chain (`[wire]` in `server.New` / `poo serve`). - **Explicit empty list (`[]`)**: configures a chain with no askers, so any `ask` decision goes straight to the configured fallback. A chain may name an asker the runtime cannot provide, such as `wire` in headless `poo run`. That asker is dropped with a schema-backed warning (`fairWhen` on `has_wire_client`) instead of failing the settings file. Over the wire, the `wire` asker only sends `permission/ask` requests to a client that declared `capabilities.permission_answers: true` in `poo/initialize`. Otherwise every ask falls back and `session/create` / `session/load` include a warning explaining the missing capability. ## Inspecting linked packages Check which tool packages a binary actually links with `go list`: ```sh go list -deps ./cmd/my-poo | grep 'poo/tool' ``` ## The closure gate The main security and footprint guarantee of composing your own binary is what it does *not* link. Enforce this in CI with a closure test that inspects `go list -deps`: ```go deps := listDeps(t, "./wire/conformance/testdata/readonly") for _, excluded := range []string{ "tool/bash", "tool/edit", "tool/cliregistry", "tool/codemode", "tool/fetch", "codemode/starlark", "codemode/quickjs", "exec/bwrap", "mcp", "tool/callmcp", } { if slices.Contains(deps, modulePath+"/"+excluded) { t.Errorf("the read-only binary links %s", excluded) } } ``` `internal/depcheck/closure_test.go` implements this gate for the reference read-only binary. Always assert both **exclusions** (forbidden packages and third-party SDKs are absent) and **inclusions** (intended packages are present). Otherwise, a broken target that imports nothing could vacuously pass the exclusion check. --- # Custom Tools & Prompts When building a custom binary, you can inject Go tools directly into the runtime. You can also replace or extend embedded system prompt sections and supply custom command executors. ::: tip No-rebuild alternatives To add tools without compiling Go, use [CLI Registry & Script Tools](/capabilities/cli-registry) or [MCP Servers](/capabilities/mcp-servers). The CLI registry also supports JSON stdin/stdout scripts in any language. See the [Manifests Reference](/reference/manifests) for schemas. ::: ## Injecting Go tools ### The `poo.Tool` interface Every Go tool implements `poo.Tool`: ```go type Tool interface { Spec() ToolSpec Prepare(raw json.RawMessage, env PrepareEnv) (Prepared, error) Call(ctx context.Context, in Prepared, env ToolEnv) (ToolResult, error) } ``` - `Spec()` returns `poo.ToolSpec`: the tool's `Name`, `Description`, JSON `Schema`, side-effect `Class` (`ClassReadOnly` or `ClassSideEffecting`), optional `PrimaryArg` (used by doom-loop detection), `Background` mode (`BackgroundNever`, `BackgroundAllowed`, or `BackgroundAlways`), and `Idempotent` flag (whether a durable session may safely replay an interrupted call). - `Prepare(raw, env)` decodes and validates raw JSON arguments with no side effects. Return `*poo.ErrInvalidArgs` (via `poo.InvalidArgsf`) for recoverable validation errors so the model can correct its call. The returned `poo.Prepared` provides `Summary() string` for transcripts and events. - `Call(ctx, in, env)` executes the prepared call using `poo.ToolEnv` (working directory, scrubbed `Env`, `SessionID`, `RunID`, `Handle`, `JobID`, `Decider`, `History`, `Nested` caller, and `Settings`). Optional interfaces a tool or its `Prepared` value may implement: | Interface | Implemented by | Purpose | |---|---|---| | `poo.PromptContributor` | `Tool` | Contributes a `tools.` system prompt section when the tool is linked and offered | | `poo.PromptVariantContributor` | `Tool` | Provides variant-specific prompt text keyed by variant name | | `poo.AskSummaryer` | `Prepared` | Supplies permission-ask text independent of model-authored summaries | | `poo.CanonicalKeyer` | `Prepared` | Returns a canonical JSON key for doom-loop comparison | | `poo.EvidenceArgumenter` | `Prepared` | Selects which arguments a decision model may inspect | | `poo.BackgroundShorthander` | `Tool` | Translates shorthand syntax (such as trailing `&`) into a managed background job | | `poo.BackgroundableCaller` | `Tool` | Reports that a running synchronous call can be moved into a background job | ### Registering with `config.ToolFactory` Pass tool constructors in `server.Options.Tools` (or `config.BuildOptions.Tools`): ```go type ToolFactory func(ToolOptions) poo.Tool type ToolOptions struct { Executor exec.Executor Scrub exec.Scrub ProtectedPaths *protect.Set Registry *cli.Catalog Search bool Inputs []poo.Modality CodemodeEngine string ToolNames []string Offered cli.Offerings MCP []MCPRunning } ``` - The map key is the name used by profiles, permission rules, and the wire protocol, and must match `Spec().Name`. - `ToolNames` lists the tools the session offers so refusal messages only reference tools the model can actually call. - `Offered` exposes the live snapshot of registered CLI commands and running MCP server tools. - `MCP` holds the session's started MCP servers in selection order (empty at build time; populated when a session starts its servers). For tools with pluggable engines such as `codemode`, wire the engine you link inside the factory: ```go "codemode": func(config.ToolOptions) poo.Tool { return codemode.New(starlark.New()) }, ``` Unlinking a tool removes its schema and its prompt section from the binary entirely. To omit a linked tool per project without rebuilding, use `tools.disabled` in settings. Note that `poo/config` does not import any tool package, so settings files still decode and validate even when a tool is not linked. ## Custom prompt directories (`PromptFS`) Each built-in prompt section lives in an embedded markdown file beside the package that owns it. A custom binary can override any section by embedding a directory and passing it via `server.Options.PromptFS` (or `config.BuildOptions.PromptFS` when calling `config.Build` directly): ```go //go:embed prompts var promptDir embed.FS prompts, err := fs.Sub(promptDir, "prompts") if err != nil { return err } srv, err := server.New(server.Options{ // ... PromptFS: prompts, }) ``` ### Directory layout and section names Files are named after the sections in `prompt.Order()` (`base`, `profile`, `catalog`, `environment`, `project`) and `tools.` for tool-owned sections. Subdirectories represent dot prefixes, and variants are sibling files with a variant suffix: ```text prompts/ base.md profile.md environment.md tools/bash.md tools/bash.small-local.md ``` - `profile.md` replaces a profile's own `profile.Profile.Prompt` prose (rendered immediately after `base`). - A default section file (e.g. `tools/bash.md`) replaces the default text while preserving any embedded variants not explicitly overridden. - Unknown section names or non-markdown files fail on load, naming the offending file. - A linked tool's section loads for all profiles, but only profiles offering that tool render it. ### Templates and validation Each markdown file is parsed as a Go `text/template` and receives the same data struct as the section it replaces: - `environment.md`: `{{.Cwd}}`, `{{.OS}}`, `{{.Date}}`, `{{.Model}}` - `catalog.md`: `{{.Search}}` (bool), `{{.Count}}` (int), `{{.Call}}`, `{{.Find}}`, and `{{.Entries}}` (`{{.Name}}`, `{{.Description}}`) - `tools/jobs.md`: `{{.Feeds}}` (`{{.Name}}`, `{{.Description}}`) A single trailing newline at EOF is stripped during rendering; an extra blank line preserves a trailing newline. Templates are syntax-checked at load time and rendered when a session is constructed (or reconfigured with a new model or variant). A render failure prevents session creation (`config.Error` with code `invalid_value` on `system_prompt` in CLI mode, or `invalid_settings` on `session/create` over the wire). On `session/configure`, a render error rejects the change and leaves the session unchanged. ### Prompt layer precedence Layers apply in order, with later layers winning: 1. Embedded defaults 2. Binary's `PromptFS` directory 3. Settings (`system_prompt.*`, CLI `--system-prompt` / `--append-system-prompt`) 4. User instructions (`BuildOptions.UserPromptFile` / `session.user_prompt_file`, process-wide) 5. Project instructions (`AGENTS.md`, read per session from the session's working directory) `system_prompt.replace` clears the `PromptFS` sections; if the session offers registry tools, the embedded catalog section is restored after replacement. The [Skills](/capabilities/skills) catalog is a separate section rendered between `catalog` and `environment`. See [Profiles & Prompts](/configuration/profiles-and-prompts) for operator-level prompt settings. ## Custom executors (`poo/exec`) Tools that run subprocesses (`bash`, `call_cli`, feeds) never spawn OS processes directly—they delegate to an `exec.Executor`: ```go type Executor interface { Name() string Start(ctx context.Context, c Command, out io.Writer) (Process, error) } type Process interface { Wait() (exitCode int, err error) Kill() Stopped() bool } ``` `exec.Command` carries `Argv`, `Dir`, scrubbed `Env`, optional `*string` `Stdin`, and optional `Stderr` (when `nil`, stdout and stderr are merged into `out`). When `ctx` is cancelled, the executor must stop the command and its process tree, and `Stopped()` must report `true` after `Wait()` returns. If `Stdin` cannot be written completely before the child exits, `Wait()` reports `exec.ErrStdinIncomplete` alongside the exit error (unless the command was stopped). Register custom executors in an `exec.Registry` and pass it to `server.Options.Executors`: ```go registry := exec.NewRegistry() registry.Register("my-sandbox", func(opts exec.Options) (exec.Executor, error) { return newMySandbox(opts.Masker, opts.Sandbox) }) ``` `exec.Options` supplies `Masker` (for expanding protected paths to mask inside mounts) and `Sandbox` (`Network`, `ROBinds`, `RWBinds`). See [Sandboxing (bwrap)](/operations/sandbox) for the built-in Linux bubblewrap implementation. --- # Wire Protocol `poo serve` exposes a JSON-RPC 2.0 control protocol over stdin and stdout, framed as one JSON object per line (NDJSON). The public contract lives in `poo/wire/protocol`. ## Handshake (`poo/initialize`) `poo/initialize` must be the first request on the stream. Calling any other method before the handshake succeeds returns JSON-RPC error `-32002` (`data.code: "not_initialized"`). The client sends its supported `protocol_versions` (currently `[1]`), name, version, and `capabilities`: ```json {"jsonrpc":"2.0","id":1,"method":"poo/initialize","params":{"protocol_versions":[1],"client":{"name":"my-client","version":"0.1.0","capabilities":{"permission_answers":true}}}} ``` If no protocol version is shared, the server returns `-32001` (`protocol_version_unsupported`). On success, the server returns the negotiated version, `build` metadata, `capabilities` (`decider`, `compaction`, `persistence`, `jobs`, `feeds`, `history_origin`), `profiles`, `default_profile`, and `roles`. ::: info Client capability: `permission_answers` Only a client that declares `capabilities.permission_answers: true` receives `permission/ask` requests from the server. Clients that omit it are never asked—every ask falls back immediately, and `session/create` / `session/load` report a warning. ::: ## Strict parameter decoding Every method decodes its `params` object strictly via `protocol.DecodeParams`: - Omitting an optional field selects its default. - Passing an explicit `null` for `params` or any field returns `-32602` with `data.code: "invalid_params"`. - Passing an unrecognized field at any nesting depth returns `-32602` with `data.code: "unknown_field"`. ## Session methods | Method | Purpose | Key behavior | |---|---|---| | `session/create` | Create a new session | Requires `working_dir`. Optional `mode` must be in the handshake's `capabilities.persistence`. Response is queued before the event observer attaches, so no event arrives before the client learns `session_id`. | | `session/load` | Open a recorded session | Requires `session_id`. Recovers torn tails, reports `recovered_tail`, `interrupted_runs`, `warnings`, and any `pending_run` on durable sessions. | | `session/resume_run` | Continue a durable session's pending run | Starts the pending run asynchronously and returns `{"run_id": "..."}`. Returns `no_pending_run` or `busy` when not applicable. | | `session/get` | Inspect current session state | Returns FSM `state`, `run_id`, active `jobs`, rendered `prompt` state, `reasoning`, `broken`, `pending_run`, and `awaiting` status. | | `session/configure` | Update session settings between runs | Refused with `busy` while a run is active. Re-renders the system prompt if model or variant changes; rejects and preserves prior state on template error. | | `session/history` | Page recorded session history | Accepts `session_id`, optional `before_seq`, and `limit` (capped at `poo.MaxHistoryLimit`). Pages backwards; returns `items` oldest-first and `has_more`. | | `session/close` | Close a session and release locks | Cancels active work, stops feeds/jobs/MCP servers, closes the store, and returns `{}`. | ## Run, job, and catalog methods | Method | Purpose | Key behavior | |---|---|---| | `run/prompt` | Start a new run | Requires `session_id` and `text` (optional `delivered` metadata). Returns `{"run_id": "..."}` immediately; watch progress via `event` notifications or `run/inspect`. | | `run/message` | Send input to an active run | Requires `session_id` and `text`. `mode` is `"steer"` (default), `"interrupt"`, or `"follow_up"`. Returns `{"input_id": "..."}`. | | `run/inspect` | Poll events and optionally wait for settle | Accepts `after_seq` and optional `wait: {"until": "settled", "run_id": "...", "timeout_ms": ...}` (default 30s). Returns `events`, `next_seq`, `has_more`, `state`, and `settled` or `timed_out: true`. | | `run/cancel` | Cancel an active run | Requires `session_id` and `run_id`. Idempotent for already-settled runs; returns `run_not_found` for unknown IDs. | | `run/background` | Move a live tool call to a background job | Requires `session_id`, `run_id`, and `handle`. Returns `{"job": "..."}` or `call_not_backgroundable`. | | `job/cancel` | Stop a background job or feed | Requires `session_id` and `job` (e.g. `j1` or `feed:inbox`). Idempotent for unknown or finished jobs. | | `models/list` | Return the effective model catalog | Accepts optional `refresh: true`. Returns `{"models": [...]}`. | | `settings/get` | Return effective merged settings | Returns the post-override settings object. | ## Server notifications and requests ### Event notifications (`event`) The server pushes every session event as a JSON-RPC notification with `method: "event"`. `protocol.Event` marshals as a flat JSON object containing `session_id`, session-monotonic `seq`, `type`, `at`, and the event's own fields: ```json {"jsonrpc":"2.0","method":"event","params":{"session_id":"01J...","seq":4,"type":"message.delta","at":"2026-01-01T00:00:00Z","run_id":"r1","text":"hello"}} ``` Event types cover the full lifecycle: - **Runs & turns**: `run.started`, `run.settling`, `run.settled`, `turn.started`, `turn.ended`, `turn.interrupted`, `message.delta`, `provider.retry` - **Inputs**: `input.queued`, `input.delivered`, `input.dropped`, `input.held` - **Tools & permissions**: tool call/result events and permission ask/decision events - **Jobs & feeds**: `job.started`, `job.ended`, `feed.started`, `feed.ended` Clients should ignore unknown event types for forward compatibility within protocol version 1. ### Permission asks (`permission/ask`) Unlike `event` notifications, a permission ask is a **server-initiated JSON-RPC request** with an `id` equal to `params.ask_id`: ```json {"jsonrpc":"2.0","id":"ask-1","method":"permission/ask","params":{"session_id":"01J...","run_id":"r1","ask_id":"ask-1","tool":"bash","summary":"rm -rf build","class":"side_effecting","reason":"policy"}} ``` For doom-loop asks, `reason` is `"doom_loop"` and `repeat_count` includes `exact` and `near` counts. The client responds with the matching `id` and a `protocol.AskResult`: ```json {"jsonrpc":"2.0","id":"ask-1","result":{"decision":"allow"}} ``` `decision` must be `"allow"` or `"deny"`. An optional `message` string on a denial is shown to the model in the tool result and recorded in the session log. ## `poo/wire/protocol` package `poo/wire/protocol` imports only the Go standard library so external Go clients can depend on the wire contract without importing `poo` or any of its runtime packages. It exports: - Envelope types: `Request`, `Response`, `Notification`, `Error`, `ErrorData` - Method constants (`MethodInitialize`, `MethodSessionCreate`, `MethodRunPrompt`, `MethodPermissionAsk`, `MethodEvent`, etc.) - Parameter and result DTOs for every method, plus `Event` with symmetric flat `MarshalJSON`/`UnmarshalJSON` - JSON-RPC error codes (`-32700` to `-32603`, `-32000` `CodeServerError`, `-32001` `CodeVersionUnsupported`, `-32002` `CodeNotInitialized`) - Machine-readable `ErrorData.Code` constants (`session_not_found`, `session_locked`, `busy`, `invalid_settings`, `unknown_model`, `unknown_profile`, `unknown_field`, etc.)—clients should branch on `error.data.code` rather than parsing `error.message` When embedding `wire.Serve`, transport backpressure and teardown limits are configurable via `wire.Bounds` (defaults: 10,000 queued messages, 16 MiB queue bytes, 10s write stall, 5s drain). --- # Conformance & Testing Poo ships two exported testing packages: `poo/wire/conformance` for black-box protocol verification and client integration tests against real binaries, and `poo/pootest` for in-process Go unit tests against `poo.Session`. ## Wire conformance suite (`poo/wire/conformance`) `poo/wire/conformance` is a black-box test suite. It launches a compiled binary with a temporary settings file pointing at a local fake OpenAI-compatible endpoint. It then drives the binary strictly over stdin and stdout. It imports only the Go standard library and `poo/wire/protocol`. ```go func TestMyBinarySpeaksTheProtocol(t *testing.T) { report := conformance.Run(t, conformance.Target{ Binary: binary, Args: []string{"serve"}, Profile: "search", Env: []string{"MY_POO_ID=conformance"}, }) if len(report.Skipped) > 0 { t.Logf("skipped: %v", report.Skipped) } } ``` ### Target requirements - `Target.Binary` must be a compiled executable path (build your command before calling `conformance.Run`). - The suite passes `--settings ` on every invocation and `--ephemeral` for the ephemeral-session flow, so your binary must accept both flags. - `Target.Profile` must name a profile the binary announces in `poo/initialize` (defaults to `"code"` when empty). - `Target.Env` appends child-only environment variables (useful for binaries that require an identity or socket path) without mutating the test process's environment. - `Target.Fixtures` lets you supply custom `ScriptedAnswer` turns, model name, and context limit to exercise tools unique to your binary. ### Adaptive flows and forward compatibility Flows adapt to what the binary announces in its handshake: - Bash-scripting flows run only when `bash` is offered. - Typed-result flows run only when `finish` is offered. - Feed flows run only when `capabilities.feeds` is `true`. `conformance.Run` returns a `Report` listing the flows that ran and any that were skipped. A full-featured binary can assert `len(report.Skipped) == 0` in CI. Responses are decoded under the protocol's forward-compatibility rules. Unexpected fields on known DTOs fail the test unless covered by an announced capability. Unknown capability keys and unknown event types are tolerated. ## Fake endpoint for client tests (`conformance.NewFakeEndpoint`) Wire clients can test against a real `poo` binary without running the full conformance suite by importing `conformance.NewFakeEndpoint`: ```go endpoint := conformance.NewFakeEndpoint( conformance.ScriptedAnswer{Text: "hello from poo"}, conformance.ScriptedAnswer{ToolCalls: []conformance.ToolCall{ {Name: "bash", Arguments: map[string]any{"command": "echo hi"}}, }}, ) defer endpoint.Close() settings := filepath.Join(dir, "settings.json") if err := endpoint.WriteSettings(settings, "conformance-model", 32768, nil); err != nil { return err } // Launch the binary with `--settings settings` and drive it over stdio. ``` `ScriptedAnswer` supports: - `Text`: complete assistant reply text. - `Chunks`: explicit delta chunks for testing streaming behavior. - `ToolCalls`: ordered `conformance.ToolCall` entries (`Name`, `Arguments`). - `Status` and `Error`: HTTP status and `ProviderError` body for rate-limit and error-handling tests. - `Delay`: artificial latency before responding (useful for testing `run/message` interrupts or `run/cancel`). - `FailAfterDelta`: emit initial text then break the stream mid-response. When scripted turns are exhausted, the endpoint repeats its final turn so clients do not need to script every follow-up request. Call `endpoint.RequestBodies()` to inspect the exact HTTP request bodies the binary sent in order, and `endpoint.Close()` when finished. ## In-process test helpers (`poo/pootest`) `poo/pootest` exports in-process test doubles for Go unit tests that construct a `poo.Session` directly. It imports only `poo`, `poo/decide`, and the standard library. ### Scripted transport (`pootest.Transport`) `pootest.Transport` implements `poo.ChatTransport` over a fixed sequence of `pootest.Turn` values (`Text`, `Thinking`, `Calls`, `Finish`, token counts, `Blocks`, `Err`, and mid-stream `Fail`). - Unlike `FakeEndpoint`, `pootest.Transport` returns `pootest.ErrScriptExhausted` when turns run out so a one-turn test fails fast instead of looping. - Supports recording every `poo.ChatRequest` and rendered prompt snapshot, scripting fork turns (for compaction or sub-requests), and scripting native compaction responses. ### In-memory record sink (`pootest.Sink`) `pootest.NewSink()` provides a thread-safe, in-memory `poo.RecordSink` and `ReadRecords` reader: - Stamps sequence numbers and timestamps onto every accepted `poo.Record`. - `WaitRecords(ctx, name, n)` blocks until at least `n` records of type `name` are recorded (avoiding polling loops in tests). - `FailAt(n)` and `SetError(err)` inject store write failures on the *n*-th append (defaulting to `pootest.ErrSinkFailed`). ### Stub decider (`pootest.StubDecider`) `pootest.NewStubDecider(probability)` implements `decide.Decider`, assigning `probability` to the first option of each question and splitting the remainder evenly across the rest: - `SetChoice(name)` pins the returned choice; `SetError(err)` injects decision failures. - `Calls()`, `Questions()`, and `States()` inspect every decision request made during the test. - Pair with `pootest.NewRecordingSink()` to capture `decide.Decision` records. ### Scripted compactor (`pootest.Compactor`) `pootest.NewCompactor(should, compaction)` implements `poo.Compactor` with a fixed decision and compaction payload: - `SetShouldAfter(turns)` delays returning `true` from `ShouldCompact` until the view has at least `turns` turns. - `SetError(err)` injects compaction errors. - `Fork` and `ForkJSON` call the session's `poo.ForkFunc` while recording `ForkCall` arguments; `Calls()`, `Views()`, and `Forks()` inspect all invocations. --- # Prior Art `poo` builds on concrete ideas from earlier agent harnesses and deliberately rejects others. This page records what was studied, what `poo` adopted, and where it diverges. ## `mini-swe-agent` - **Source:** [SWE-agent/mini-swe-agent](https://github.com/SWE-agent/mini-swe-agent) - **Version studied:** `v2.4.6` (`04d809ceab9df28f9adaed044884180159172930`) - **Areas studied:** default and interactive agent loops, local shell execution, exception control flow, YAML config templates, and tool-call parsing. ### Adopted - **Bash as the primary verb.** `mini-swe-agent` treats shell execution as the main way to act on a repo. `poo` keeps `bash` central in the `code` [profile](/configuration/profiles-and-prompts) and adds `read`, `grep`, `edit`, and `write` so read-only binaries can omit `bash` entirely. - **Stateless shell per call.** Every command runs in a fresh subshell; `cd` and exported variables do not persist across calls. `poo`'s system prompt states this contract explicitly. - **Linear, append-only history.** Nothing rewrites the model's view of history silently. Compaction always writes a visible replacement and leaves the session store intact. - **Observation envelope with head/tail elision.** Above a context-relative cap, `poo` renders the head and tail of command output with an elision count. The envelope hints at `grep`, `sed`, `head`, or `tail` to inspect smaller slices. - **Section-based prompt structure.** `poo` splits the operating contract, tool rules, and environment context into named [prompt sections](/configuration/profiles-and-prompts). It keeps `mini-swe-agent`'s shell guidance while using native tool calls where supported. - **Process-group kill on timeout.** Timed-out commands kill their entire process group (with a grace period before `SIGKILL`) so no orphaned child processes survive. ### Rejected - **Bash as the only tool.** Read-only builds cannot link `bash` at all, so file inspection needs dedicated read-only tools. - **Magic-string completion.** Instead of ending a run when stdout prints a sentinel string, `poo` provides the typed, schema-validated [`finish` tool](/capabilities/tools-and-jobs). - **Exception-driven control flow.** `poo` uses an explicit [session FSM](/extending/architecture) with a closed [settle-reason enum](/operations/limits-and-exit-codes). The [wire protocol](/extending/wire-protocol), `run/inspect`, and session replay all depend on a known state set. - **Format-error retry counters.** `poo` returns malformed tool calls to the model as recoverable validation errors and bounds retries with `max_continuations`. - **Control messages inside the transcript.** `poo` keeps the message list to model and tool turns and records control outcomes as typed [session log records](/reference/session-log-v0). - **Heavy core dependencies.** `poo`'s core packages (`poo`, `poo/prompt`, `poo/decide`, `poo/wire/protocol`) depend only on the Go standard library, enforced by `internal/depcheck`. Opt-in packages (such as the [REPL](/getting-started/repl), SQLite store, and QuickJS engine) carry their own dependencies only when linked. ## `pi-durable` - **Source:** ["Pi Durable"](https://earendil.com/posts/pi-durable/) (Earendil Engineering, October 2026) - **Areas studied:** storage backends, single-owner locking, durable tasks, prompt sections, extensions, forks, and compaction. ### Adopted - **Single-owner storage authority.** `poo` supports JSONL and SQLite [session stores](/operations/sessions-and-durability) and enforces single-process ownership via file locks and lease TTLs. - **Session-to-run lifecycle.** A session holds a sequence of runs (one active run at a time) behind a clean store, projection, and authority seam. - **Write-ahead durability.** `poo` writes every record as it happens. Loading a `logged` session marks any interrupted run; loading a `durable` session plans and resumes the run from the interrupted phase. - **Section-based prompts.** Like `pi-durable`, `poo` assembles prompts from named sections. Unlike `pi-durable`, `poo` freezes the rendered prompt for the length of a run so provider prompt caches stay valid. - **Structured tool-call records.** Every tool call is recorded with its intent and outcome as it runs. - **Transport-level prefix forks.** [Compaction strategies](/capabilities/compaction) (`mine`, `pointer`, `handoff`) fork the last main request byte-for-byte to reuse the provider's prompt cache without creating a separate conversation branch. - **Handoff notes.** `poo`'s `handoff` compaction strategy mirrors `pi-durable`'s `reset(note)` pattern as an opt-in strategy alongside the default `mine` strategy. ### Rejected - **Task graphs and subagent trees.** `poo` runs one agent loop per session with no built-in subagent tree. Multi-agent orchestration belongs to an external supervisor (such as Avenor via [feeds](/capabilities/feeds-and-daemon) or [MCP](/capabilities/mcp-servers)). - **First-class forked conversations.** Sessions remain linear; forks exist only at the transport layer for compaction passes. - **Runtime-mutable extension registries.** `poo` composes Go extensions at compile time via [`server.New`](/extending/custom-binary). For no-rebuild extensibility, operators drop in declarative [CLI registry](/capabilities/cli-registry) or [MCP](/capabilities/mcp-servers) manifests instead of mutating a running registry. - **Automatic tool replay policies.** `poo` does not tag tools `replay: "safe"` to re-run them automatically after a crash. Recovery records an interrupted outcome so the caller or durable planner can continue safely. - **Typed application-state documents.** `poo` has no built-in document store for plans or todos. - **Silent background compaction.** Compaction never rewrites history behind the model's back. Every strategy writes a visible replacement and leaves stored history intact. ## Related Pages - [Why `poo`?](/getting-started/why-poo) — core philosophy and extensibility ladder - [Architecture](/extending/architecture) — package boundaries, FSM states, and hooks - [Context Compaction](/capabilities/compaction) — compaction strategies and transparent history - [Sessions & Durability](/operations/sessions-and-durability) — JSONL/SQLite stores, leases, and crash recovery --- # CLI Reference Every command, flag, and help text in `poo` comes from a single declaration in `cmd/poo/app.go`. Run `poo --help` or `poo help ` for the exact usage of any command, or `poo --version` for the short build version. ## Front Door A bare `poo` launches the front-door interface linked into the binary — `repl` by default, or whichever linked interface the resolved settings file names under `ui`. If no settings file exists yet, a bare `poo` on a terminal runs the interactive welcome flow; non-interactively, it exits `1`. Three top-level shortcuts dispatch directly without naming a subcommand: | Invocation | Equivalent | Behavior | |---|---|---| | `poo` | `poo repl` (or `ui` setting) | Launches the configured front-door UI with the discovered settings file. | | `poo -p [flags]` | `poo run [flags] -- ` | Runs a one-shot session. `--print` is an alias for `-p`. Accepts `run` and shared flags before or after the prompt; `--` ends flag parsing. | | `poo -c [flags]` | `poo repl --continue [flags]` | Reopens the most recent session in the working directory. `--continue` is the long form. | | `poo --resume [flags]` | `poo repl --resume [flags]` | Reopens the session identified by ``. Mutually exclusive with `-c`/`--continue`. | ```bash # One-shot prompt with flags after the prompt poo -p "Summarize the git log" --max-turns 4 --ephemeral # Reopen the latest session in this directory poo -c # Reopen a specific session by ID poo --resume 0195c8a2-7b1e-7000-8000-000000000001 ``` ## Shared Flags Every subcommand accepts these common flags. Precedence is profile, then settings file, then CLI flags (last writer wins), except repeated manifest path flags append to the settings' paths. See [Settings Discovery](/configuration/settings-discovery) for how `--settings` is resolved when omitted. | Flag | Type | Default | Description | |---|---|---|---| | `--settings` | string | discovered | Path to the settings file (JSON, TOML, or YAML). | | `--system-prompt` | string | — | File holding the system prompt's base section. | | `--append-system-prompt` | string | — | Text appended to the system prompt, or `@file` to read from a file. | | `--permission-unmatched` | string | profile/settings | Action for side-effecting tool calls no rule covers: `allow`, `ask`, or `deny`. | | `--session-dir` | string | settings | Directory where session files are stored. | | `--user-prompt-file` | string | platform config `AGENTS.md` | File holding the user's own instructions. | | `--ephemeral` | bool | `false` | Run without writing a session to disk. | | `--profile` | string | settings / `code` | Profile to run under (for example `base`, `code`, `search`, or a custom profile). | | `--feeds-path` | string (repeatable) | — | Additional feed manifest path. | | `--mcp-path` | string (repeatable) | — | Additional MCP manifest path. | | `--cli-registry-path` | string (repeatable) | — | Additional CLI registry manifest path. | ## Endpoint Flags `run`, `repl`, `serve`, and `daemon` accept these endpoint flags to define or override the `chat` model on the command line. When any endpoint flag is supplied, `--endpoint`, `--model-id`, and a positive `--context-limit` are all required. | Flag | Type | Default | Description | |---|---|---|---| | `--endpoint` | string | — | OpenAI-compatible endpoint URL, e.g. `http://localhost:4000/v1`. | | `--model-id` | string | — | Model identifier sent to the endpoint. | | `--context-limit` | int | `0` | Model's context window in tokens (required and `> 0` when using endpoint flags). | | `--api-key-env` | string | — | Name of the environment variable holding the API key. | | `--tools-mode` | string | `native` | How tool calls are requested: `native`, `text`, or `auto`. | ## Subcommands ### `poo run` Run a single one-shot session. The final answer is written to stdout and progress/diagnostics to stderr. Flags stop at the first non-flag argument, so everything from the first prompt word onward is prompt text. Use `poo -p` to place flags after the prompt. Unless the settings file assigns a `chat` role, `--endpoint`, `--model-id`, and `--context-limit` are required. See [Limits & Exit Codes](/operations/limits-and-exit-codes) for exit codes and signal handling. **Positional arguments:** `prompt...` (required, variadic) **Flags:** Accepts [Shared Flags](#shared-flags), [Endpoint Flags](#endpoint-flags), and: | Flag | Type | Default | Description | |---|---|---|---| | `--permission-fallback` | string | settings | Decision when the permission asker chain is exhausted: `allow` or `deny`. | | `--reasoning-effort` | string | settings | Reasoning level to send: `default` (no field), `off`, `minimal`, `low`, `medium`, `high`, or `xhigh`. | | `--max-turns` | int | `0` (unlimited) | Turn limit for the run. | | `--max-output` | int | model default | Override the model's output-token limit. | | `--truncation-retries` | int | `1` | Consecutive output-limit truncations to retry more concisely before settling (`0` disables retries). | | `--context-strategy` | string | `mine` | Compaction strategy: `summary`, `mine`, `pointer`, `native`, `handoff`, or `none`. | | `--context-keep-recent` | int | strategy default | Verbatim tail retained by block compaction strategies (`summary`, `mine`, `pointer`), in tokens. | | `--log` | string | — | Write session records to a specific JSONL file instead of the session store. | | `--working-dir` | string | current directory | Working directory for tools (must exist). | | `--executor` | string | `local` | Bash tool executor: `local` or `bwrap`. | | `--project-prompt` | bool | `false` | Include the working directory's `AGENTS.md` (or `CLAUDE.md`) in the system prompt. | | `--timeout` | duration | — | Wall-clock context deadline for the run, e.g. `5m`. | | `--no-wait-jobs` | bool | `false` | Exit at the first settle instead of waiting for background jobs; running jobs stop on close. | ```bash poo run --max-turns 12 --timeout 5m --project-prompt "Find and fix the failing unit test." poo run --endpoint http://localhost:4000/v1 --model-id gemma4 \ --context-limit 262144 --log session.jsonl \ "List the Go packages in this repository." ``` --- ### `poo repl` Launch an interactive terminal session with vi keybindings and markdown rendering. Starts `poo serve` as a child process and forwards supplied shared, endpoint, and tool flags to it. Type `/help` inside the REPL for interactive commands. See [Interactive REPL](/getting-started/repl). **Flags:** Accepts [Shared Flags](#shared-flags), [Endpoint Flags](#endpoint-flags), and: | Flag | Type | Default | Description | |---|---|---|---| | `--working-dir` | string | current directory | Working directory for tools. | | `--executor` | string | `local` | Bash tool executor: `local` or `bwrap`. | | `-c`, `--continue` | bool | `false` | Continue the most recent session in the working directory. | | `--resume` | string | — | Resume the session named by this ID. | ```bash poo repl --working-dir ./my-repo --executor bwrap poo repl --resume 0195c8a2-7b1e-7000-8000-000000000001 ``` --- ### `poo serve` Serve the JSON-RPC 2.0 wire protocol over stdin and stdout (one JSON object per line). See [Wire Protocol](/extending/wire-protocol). **Flags:** Accepts [Shared Flags](#shared-flags), [Endpoint Flags](#endpoint-flags), and: | Flag | Type | Default | Description | |---|---|---|---| | `--working-dir` | string | current directory | Working directory for tools. | | `--executor` | string | `local` | Bash tool executor: `local` or `bwrap`. | ```bash poo serve --profile code --working-dir /srv/project ``` --- ### `poo daemon` Host a long-lived, feed-driven session without reading stdin. Defaults the session mode to `durable` when neither `--ephemeral` nor `session.mode` is set, starts all non-optional feeds, and writes lifecycle events one fact per line to stderr. See [Feeds & Daemon](/capabilities/feeds-and-daemon) and [Daemon Exit Codes](/operations/limits-and-exit-codes#poo-daemon-exit-codes). **Flags:** Accepts [Shared Flags](#shared-flags), [Endpoint Flags](#endpoint-flags), and: | Flag | Type | Default | Description | |---|---|---|---| | `--session` | string | generated | Session ID to load, or create if it does not exist. When omitted, a new ID is generated and printed to stderr. | | `--auto-resume` | bool | `true` | Resume a pending unsettled run automatically on load. | | `--working-dir` | string | current directory | Working directory for tools. | ```bash poo daemon --session ops-watcher --working-dir /srv/app poo daemon --session ops-watcher --auto-resume=false ``` --- ### `poo models` List the effective model catalog — combining settings, `models_file`, curated built-ins, and live endpoint probes — or explain where each field of a single model came from. See [Models & Catalog](/configuration/models-and-catalog). **Flags:** Accepts [Shared Flags](#shared-flags) and: | Flag | Type | Default | Description | |---|---|---|---| | `--json` | bool | `false` | Print the model list as JSON. | | `--explain` | string | — | Print each field of the named model and the catalog layer that set it. | ```bash poo models poo models --json poo models --explain codex/gpt-5.4 ``` --- ### `poo roles` Resolve every configured role (`chat`, `decider`, `compaction`, and any additional assigned roles) against the catalog and print the model, provider, and credential source (`env:`, `static`, or `none`). Prints no secrets, trades no credentials, and exits `1` if any assigned role fails to resolve. **Flags:** Accepts [Shared Flags](#shared-flags) only. ```bash poo roles poo roles --settings ./codex.settings.yaml ``` --- ### `poo prompt` Print the exact rendered system prompt a session would send to the model. Does not require a configured chat model. See [Profiles & Prompts](/configuration/profiles-and-prompts). **Flags:** Accepts [Shared Flags](#shared-flags) and: | Flag | Type | Default | Description | |---|---|---|---| | `--project-prompt` | bool | `false` | Include the working directory's `AGENTS.md` (or `CLAUDE.md`) in the prompt. | | `--pretty` | bool | `false` | Format each section under a `--- ---` header and summarize the skill catalog. | ```bash poo prompt --pretty --project-prompt poo prompt --profile search ``` --- ### `poo login` Sign in to a provider and store the credential in `auth_file` (or poo's default `auth.json`). Keys are read from an interactive terminal prompt or stdin — never via a flag. Existing credentials are not overwritten unless confirmed interactively or forced with `--force`. See [Providers & Auth](/configuration/providers-and-auth). **Positional arguments:** `[provider]` (optional). Supported providers: - `codex` — OpenAI Codex (browser OAuth sign-in with loopback callback or URL paste fallback) - `ollama-cloud` — Ollama Cloud (API key) - `opencode` — OpenCode (API key) - `typesafe` — TypeSafe (API key) A bare `poo login` presents the provider list interactively. **Flags:** Accepts [Shared Flags](#shared-flags) and: | Flag | Type | Default | Description | |---|---|---|---| | `--force` | bool | `false` | Replace an existing credential without asking. | | `--no-browser` | bool | `false` | Print the sign-in URL instead of opening a browser. | | `--wait` | int | `300` | Seconds to wait for a browser sign-in callback. | ```bash poo login codex poo login codex --no-browser --wait 600 printf '%s' "$OPENCODE_API_KEY" | poo login opencode --force ``` --- ### `poo auth status` Report the resolved credential file, file format, provider, OAuth client, account ID, expiry, and state (`live`, `refresh needed`, `no readable expiry`, or expired under a read-only file). Prints no secrets and does not refresh tokens. **Flags:** Accepts [Shared Flags](#shared-flags) and: | Flag | Type | Default | Description | |---|---|---|---| | `--json` | bool | `false` | Print the status report as JSON. | ```bash poo auth status poo auth status --json ``` --- ### `poo auth refresh` Refresh the OpenAI Codex credential in the resolved credential file when the access token is within the leeway window of expiring. Exits `0` silently on success (including when no refresh is due) and non-zero on failure. **Flags:** Accepts [Shared Flags](#shared-flags) and: | Flag | Type | Default | Description | |---|---|---|---| | `--leeway` | duration | `5m` | Refresh when this much time or less remains before expiry (must be positive). | | `--force` | bool | `false` | Refresh immediately even if the access token is still fresh. | ```bash poo auth refresh poo auth refresh --leeway 15m poo auth refresh --force ``` --- ### `poo auth import pi` Copy the OpenAI Codex credential from pi's `auth.json` into poo's credential file. Because OAuth refresh rotates the refresh token, only one tool can keep the imported credential alive after the first refresh. Does not modify pi's file. **Flags:** Accepts [Shared Flags](#shared-flags) and: | Flag | Type | Default | Description | |---|---|---|---| | `--from` | string | `pi_auth_file`, then `~/.pi/agent/auth.json` | Source `auth.json` file to copy from. | | `--force` | bool | `false` | Replace an existing credential in poo's file without asking. | ```bash poo auth import pi poo auth import pi --from ~/.pi/agent/auth.json --force ``` --- ### `poo sessions list` List sessions in the session store with columns `ID`, `CREATED`, `PROFILE`, `RUNS`, `REASON`, `SIZE`, and `LOCKED`. See [Sessions & Durability](/operations/sessions-and-durability). **Flags:** Accepts [Shared Flags](#shared-flags) and: | Flag | Type | Default | Description | |---|---|---|---| | `--json` | bool | `false` | Print the session summaries as JSON. | ```bash poo sessions list poo sessions list --json --session-dir /var/lib/poo/sessions ``` --- ### `poo sessions prune` Delete sessions matched by the retention policy (`session.retention` in settings, overridden by flags). Locked sessions are skipped and reported on stderr. Exits `2` if neither settings nor flags specify a retention policy. **Flags:** Accepts [Shared Flags](#shared-flags) and: | Flag | Type | Default | Description | |---|---|---|---| | `--older-than` | int | settings (`max_age_days`) | Delete sessions whose last activity is older than this many days. | | `--keep` | int | settings (`max_sessions`) | Keep this many most recently active sessions. | | `--dry-run` | bool | `false` | Print sessions that would be deleted without deleting anything. | ```bash poo sessions prune --older-than 30 --dry-run poo sessions prune --keep 20 ``` --- ### `poo version` Print the binary's version, VCS revision, commit timestamp, dirty/modified status, and Go toolchain version embedded by the Go build. **Flags:** Accepts [Shared Flags](#shared-flags) and: | Flag | Type | Default | Description | |---|---|---|---| | `--json` | bool | `false` | Print build information as JSON (`version`, `revision`, `time`, `modified`, `go_version`). | ```bash poo version poo version --json poo --version ``` --- # Settings Reference Every key in a poo settings file is optional except `version`. Unknown keys are rejected at load time. See [Settings Discovery](/configuration/settings-discovery) for file lookup order, supported formats, and relative path resolution rules. ## Top-Level Metadata & Interface ### `version` | Key | Type | Default / Behavior | Description | |---|---|---|---| | `version` | `int` | Required (`1`) | Settings format version. Must be `1`. | ### `ui` | Key | Type | Default / Behavior | Description | |---|---|---|---| | `ui` | `string` | Binary's default front door (`repl`) | Interface launched by a bare `poo` invocation. Must be linked into the binary. | ## Profiles See [Profiles & Prompts](/configuration/profiles-and-prompts) for profile inheritance and layering details. ### `profile` & `repl_profile` | Key | Type | Default / Behavior | Description | |---|---|---|---| | `profile` | `string` | Binary's default profile | Profile name used when building a session (`run`, `serve`, etc.). | | `repl_profile` | `string` | Falls back to `profile` / binary default | Profile used by the interactive REPL for new conversations when no flag overrides it. Reopened sessions keep the profile recorded in their log. | ### `profiles_files` | Key | Type | Default / Behavior | Description | |---|---|---|---| | `profiles_files` | `string[]` | Empty | External YAML or JSON files defining reusable profiles under a top-level `profiles` key. Loaded as layers below inline `profiles` (inline wins, then earlier files). Relative paths resolve against the settings file's directory; `prompt_file` and `prompt_append_file` inside a profiles file resolve against that profiles file's directory. | ### `profiles` Map of `` to profile definition object. Each entry defines a named variant of a linked profile or another defined profile. | Key | Type | Default / Behavior | Description | |---|---|---|---| | `profiles..base` | `string` | Required | Name of the linked or defined profile this profile inherits from. | | `profiles..mcp_defaults` | `bool` | Inherits `mcp.defaults` | Overrides whether poo's default `mcp` directory loads for sessions under this profile. | | `profiles..mcp_servers` | `string[]` | Inherits base | MCP server names to start. Appends to the base profile's list (deduplicated, preserving first appearance). Missing servers warn and are skipped. | | `profiles..feeds` | `string[]` | Inherits base | Feed manifest names this profile requires. Appends to the base profile's list (deduplicated). Unloaded feeds warn and are skipped. | | `profiles..feeds_defaults` | `bool` | Inherits `feeds.defaults` | Overrides whether poo's default `feeds` directory loads for sessions under this profile. | | `profiles..cli_registry_defaults` | `bool` | Inherits `cli_registry.defaults` | Overrides whether poo's default `cli-registry` directory loads for sessions under this profile. | | `profiles..prompt_file` | `string` | Empty | File whose text replaces the profile's prompt section. Relative paths resolve against the declaring file's directory. | | `profiles..prompt_append_file` | `string` | Empty | File whose text appends to the profile's prompt section. Mutually exclusive with `prompt_append`. Relative paths resolve against the declaring file's directory. | | `profiles..prompt_append` | `string` | Empty | Inline text appended to the profile's prompt section. Mutually exclusive with `prompt_append_file`. | | `profiles..model_family` | `bool` | `false` | When `true`, includes model-family guidance keyed by the active model's `prompt_variant`. | | `profiles..tools.disabled` | `string[]` | Empty | Tool names disabled for sessions running under this profile. | ```yaml profile: reviewer repl_profile: code profiles_files: - ./team-profiles.yaml profiles: reviewer: base: code prompt_append: "Focus on correctness and edge cases. Do not modify files." model_family: true tools: disabled: [edit, write, bash] ``` ## Endpoints, Models, Roles & Auth See [Models & Catalog](/configuration/models-and-catalog), [Models File Reference](/reference/models-file), and [Providers & Auth](/configuration/providers-and-auth). ### `endpoints` Map of `` to endpoint configuration object. Credentials resolve from `api_key_env` first, falling back to literal `api_key`. | Key | Type | Default / Behavior | Description | |---|---|---|---| | `endpoints..endpoint` | `string` | Required | Base URL for the endpoint (legacy alias: `base_url`). | | `endpoints..api_key_env` | `string` | Empty | Environment variable name holding the API key. Automatically scrubbed from child tool environments. | | `endpoints..api_key` | `string` | Empty | Literal API key stored in settings (fallback when `api_key_env` is unset or empty). | | `endpoints..session_header` | `string` | Empty | HTTP header name that carries the session ID for gateway routing. | | `endpoints..skip_probe` | `bool` | `false` | Skip probing the endpoint for its served model list. | | `endpoints..instructions_per_question` | `bool` | `false` | Fold decision framing into each question instead of sending a request-level `instructions` field. | ### `models` Map of `` to model configuration object. Omitted fields inherit from the curated catalog, `models_file`, or endpoint discovery. | Key | Type | Default / Behavior | Description | |---|---|---|---| | `models..endpoint` | `string` | Required | Name of the endpoint serving this model. | | `models..model_id` | `string` | Required | Model identifier sent to the endpoint. | | `models..api` | `string` | Chat completions | Wire API dialect used to talk to the model (e.g., `responses`). See [Wire API Mapping](/reference/wire-api-mapping). | | `models..tools_mode` | `string` | Model default | How tool calls are requested: `native`, `text`, `auto`, or `none`. | | `models..ops` | `string[]` | Model default | Operations the model serves (e.g., `compact` for native compaction). | | `models..inputs` | `string[]` | Model default | Input modalities the model accepts (e.g., `text`, `image`). | | `models..context_limit` | `int` | Model default | Total context window size in tokens (prompt plus output). | | `models..input_limit` | `int` | Model default | Maximum prompt tokens accepted when smaller than `context_limit`. | | `models..max_output` | `int` | Model default | Maximum tokens the model writes in one response. | | `models..reasoning` | `object` | Model default | How reasoning is controlled on the wire. Contains `mode` (`none`, `toggle`, `effort`, `budget`) and `param` (wire parameter path, e.g., `reasoning_effort` or `chat_template_kwargs.enable_thinking`). | | `models..reasoning_levels` | `string[]` | Model default | Accepted reasoning levels from lowest to highest (e.g., `[off, minimal, low, medium, high, xhigh]`). Sent verbatim as spelled. | | `models..quirks` | `string[]` | Empty | Named transport adaptations applied in order (e.g., `audio_url`). Unknown names warn and are skipped. | | `models..prompt_variant` | `string` | Empty | Variant key used to select model-family prompt sections. | ### `models_file` | Key | Type | Default / Behavior | Description | |---|---|---|---| | `models_file` | `string` | Auto-discovers sibling `models.yaml` or `models.json` | Path to a models file loaded as a catalog layer below inline `endpoints` and `models` (legacy alias: `pi_models_file`). Relative paths resolve against the settings file's directory. | ### `roles` Map of role name to model name (either a key in `models` or `/` from `models_file` / built-in providers). | Key | Type | Default / Behavior | Description | |---|---|---|---| | `roles.chat` | `string` | None | Primary chat model for the session. | | `roles.decider` | `string` | None | Decision model used by the `decide` permission asker and CLI registry filtering. See [Decision Model](/capabilities/decision-model). | | `roles.compaction` | `string` | Falls back to `roles.chat` | Model used for compaction requests (`summary`, `mine`, `pointer`, `handoff`). | ### `auth_file`, `pi_auth_file` & `auth_readonly` | Key | Type | Default / Behavior | Description | |---|---|---|---| | `auth_file` | `string` | Sibling `auth.yaml`/`auth.json` beside `models_file`, else platform config dir | Path to poo's credential file (or a shared read-only file such as `~/.codex/auth.json`). Mutually exclusive with `pi_auth_file`. Relative paths resolve against the settings file's directory. | | `pi_auth_file` | `string` | None | Path to pi's `auth.json`, read and written in pi's format. Must exist. Mutually exclusive with `auth_file`. Relative paths resolve against the settings file's directory. | | `auth_readonly` | `bool` | `false` | When `true`, poo never refreshes, signs in, imports, or writes the credential file. Use when another tool owns token refresh. | ```yaml version: 1 models_file: ./models.yaml auth_file: ~/.codex/auth.json auth_readonly: true endpoints: local: endpoint: http://localhost:4000/v1 api_key_env: LOCAL_API_KEY models: qwen3: endpoint: local model_id: qwen3-coder context_limit: 131072 max_output: 8192 tools_mode: auto roles: chat: qwen3 decider: local/gemma-decider ``` ## Reasoning & Sampling See [Reasoning & Sampling](/configuration/reasoning-and-sampling). ### `reasoning` | Key | Type | Default / Behavior | Description | |---|---|---|---| | `reasoning.chat` | `string` | `default` | Reasoning level for the chat model: `default`, `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, or a positive integer token budget (e.g., `"8192"`). `default` omits the reasoning field; `off` asks the model not to think. | ### `sampling` Map of `` name to per-model sampling overrides. Omitted fields are not sent so the endpoint's default applies. | Key | Type | Default / Behavior | Description | |---|---|---|---| | `sampling..temperature` | `float` | Unset | Sampling temperature. | | `sampling..top_p` | `float` | Unset | Nucleus sampling threshold. | | `sampling..top_k` | `float` | Unset | Number of candidate tokens considered by the sampler. | | `sampling..min_p` | `float` | Unset | Minimum token probability threshold. | ```yaml reasoning: chat: medium sampling: qwen3: temperature: 0.6 top_p: 0.95 ``` ## Decider See [Decision Model](/capabilities/decision-model). ### `decider` | Key | Type | Default / Behavior | Description | |---|---|---|---| | `decider.timeout_ms` | `int` | Decider default | Per-call latency budget for the decider model, in milliseconds. Minimum `1`. | ## Context & Compaction See [Context Compaction](/capabilities/compaction). ### `context` | Key | Type | Default / Behavior | Description | |---|---|---|---| | `context.strategy` | `string` | `mine` | Compaction strategy: `summary`, `mine`, `pointer`, `handoff`, `native`, or `none`. `native` requires a model declaring the `compact` op and a native-compacting transport. | | `context.notice_ratio` | `float` | Removed (ignored) | Removed setting. Accepted for backward compatibility and emits a warning. | | `context.hard_ratio` | `float` | Removed (ignored) | Removed setting. Accepted for backward compatibility and emits a warning. | | `context.handoff.ratio` | `float` | Strategy default | Fraction of the prompt limit (`0`–`1`) that triggers handoff compaction. | | `context.handoff.max_tokens` | `int` | Strategy default | Token limit for the handoff request (`≥ 0`). | | `context.summary.ratio` | `float` | Strategy default | Fraction of the prompt limit (`0`–`1`) that triggers summary compaction. | | `context.summary.keep_recent_tokens` | `int` | Strategy default | Recent history tokens kept verbatim (`≥ 0`). | | `context.summary.max_tokens` | `int` | Strategy default | Token limit for the summary request (`≥ 0`). | | `context.mine.ratio` | `float` | Strategy default | Fraction of the prompt limit (`0`–`1`) that triggers mine compaction. | | `context.mine.keep_recent_tokens` | `int` | Strategy default | Recent history tokens kept verbatim (`≥ 0`). | | `context.mine.max_tokens` | `int` | Strategy default | Token limit for the mining request (`≥ 0`). | | `context.mine.pointer_max_tokens` | `int` | Strategy default | Token limit for the pointer pass (`≥ 0`). | | `context.pointer.ratio` | `float` | Strategy default | Fraction of the prompt limit (`0`–`1`) that triggers pointer compaction. | | `context.pointer.keep_recent_tokens` | `int` | Strategy default | Recent history tokens kept verbatim (`≥ 0`). | | `context.pointer.max_tokens` | `int` | Strategy default | Token limit for the compose request (`≥ 0`). | | `context.pointer.pointer_max_tokens` | `int` | Strategy default | Token limit for the pointer pass (`≥ 0`). | | `context.pointer.snippet_budget` | `int` | Strategy default | Maximum bytes of snippet text collected by queries (`≥ 0`). | | `context.pointer.escalate_after` | `int` | Strategy default | Number of pointer compactions before escalating to full-span fallback (`≥ 0`). | ```yaml context: strategy: mine mine: ratio: 0.75 keep_recent_tokens: 8192 ``` ## Tools & Sandboxing See [Built-in Tools & Jobs](/capabilities/tools-and-jobs), [Codemode](/capabilities/codemode), and [Sandboxing (bwrap)](/operations/sandbox). ### `tools` | Key | Type | Default / Behavior | Description | |---|---|---|---| | `tools.read.restrict_to_working_dir` | `bool` | `false` | Confine `read` to the session's working directory. | | `tools.read.ask_outside_working_dir` | `bool` | `false` | Route `read` targets outside the working directory through the permission asker. | | `tools.grep.restrict_to_working_dir` | `bool` | `false` | Confine `grep` to the session's working directory. | | `tools.grep.ask_outside_working_dir` | `bool` | `false` | Route `grep` targets outside the working directory through the permission asker. | | `tools.edit.restrict_to_working_dir` | `bool` | `false` | Confine `edit` to the session's working directory. | | `tools.edit.ask_outside_working_dir` | `bool` | `false` | Route `edit` targets outside the working directory through the permission asker. | | `tools.write.restrict_to_working_dir` | `bool` | `false` | Confine `write` to the session's working directory. | | `tools.write.ask_outside_working_dir` | `bool` | `false` | Route `write` targets outside the working directory through the permission asker. | | `tools.bash.timeout_s` | `int` | `120` | Per-command wall-clock timeout, in seconds. | | `tools.bash.executor` | `string` | `local` | Command executor linked into the binary (e.g., `local`, `bwrap`). | | `tools.codemode.engine` | `string` | `quickjs` | Script runtime for `codemode`: `quickjs` or `starlark`. | | `tools.codemode.timeout_s` | `int` | Engine default | Wall-clock timeout for one script run, in seconds. | | `tools.codemode.script_max_bytes` | `int` | Engine default | Maximum accepted script size, in bytes. | | `tools.codemode.output_cap_chars` | `int` | Engine default | Maximum printed output characters retained per run. | | `tools.codemode.exec_steps` | `int` | Engine default | Starlark execution step budget. Rejected if non-zero when `engine` is `quickjs`. | | `tools.fetch.timeout_s` | `int` | `30` | Timeout per HTTP fetch, in seconds. | | `tools.fetch.max_bytes` | `int` | Tool default | Maximum response body size read, in bytes. | | `tools.fetch.user_agent` | `string` | Tool default | Custom `User-Agent` header sent by `fetch`. | | `tools.fetch.allow_private_hosts` | `bool` | `false` | Allow loopback and private IP ranges in `fetch` (link-local and reserved ranges remain blocked). | | `tools.bwrap.network` | `bool` | `true` | Share host network inside the `bwrap` sandbox. Set `false` to isolate network access. | | `tools.bwrap.ro_binds` | `string[]` | `/usr`, `/bin`, `/lib`, `/lib64`, `/etc` | Host paths mounted read-only inside the `bwrap` sandbox. | | `tools.bwrap.rw_binds` | `string[]` | Working dir only | Additional host paths mounted read-write inside the `bwrap` sandbox. | | `tools.env.scrub` | `string[]` | Endpoint credential env vars | Environment variable names removed from child processes and session environment. | | `tools.env.passthrough` | `string[]` | Unset (all non-scrubbed vars) | Allowlist of environment variable names kept for child processes; all others are dropped. | | `tools.protected_paths` | `string[]` | Empty | Glob patterns of paths tools must not read or modify (masked inside `bwrap`). | | `tools.disabled` | `string[]` | Empty | Tool names disabled regardless of profile. Naming an unlinked or core-required tool is an error. | ```yaml tools: edit: restrict_to_working_dir: true write: restrict_to_working_dir: true bash: executor: bwrap timeout_s: 60 bwrap: network: false protected_paths: - "**/.env" - "~/.ssh/**" disabled: [fetch] ``` ## Permissions See [Permissions & Safety](/operations/permissions-and-safety). ### `permission` | Key | Type | Default / Behavior | Description | |---|---|---|---| | `permission.unmatched` | `string` | Profile default | Action for a side-effecting call that matches no rule: `allow`, `ask`, or `deny`. | | `permission.fallback` | `string` | `deny` | Decision when the asker chain is exhausted or times out: `allow` or `deny`. | | `permission.askers` | `string[]` | Binary's default chain | Ordered list of askers (`decide`, `wire`). An explicit empty list `[]` skips all askers and goes straight to `fallback`. `decide` requires `roles.decider`. | | `permission.chain_timeout_s` | `int` | `120` | Overall timeout for the asker chain, in seconds. Minimum `1`. | | `permission.doom_loop.threshold` | `int` | Policy default | Exact repeat count that triggers the doom-loop action. Minimum `1`. | | `permission.doom_loop.near_threshold` | `int` | Policy default | Near-repeat count that triggers the doom-loop action. Minimum `1`. | | `permission.doom_loop.action` | `string` | Policy default | Action taken on a doom loop: `allow`, `ask`, or `deny`. | | `permission.decide.allow` | `float` | `0.85` | Probability threshold (`0`–`1`) at which the decider allows a call. Requires `roles.decider`. | | `permission.decide.deny` | `float` | `0.99` | Probability threshold (`0`–`1`) at which the decider denies a call. Requires `roles.decider`. | | `permission.decide.timeout_ms` | `int` | `1500` | Per-call timeout for the `decide` asker, in milliseconds. Minimum `1`. Requires `roles.decider`. | | `permission.rules` | `object[]` | Empty | Ordered permission rules; first match wins. See table below. | ### `permission.rules[]` Each rule must specify **either** `tool` **or** `class` (never both). `command_prefix` and `command_contains` require `tool` and are mutually exclusive. | Key | Type | Default / Behavior | Description | |---|---|---|---| | `tool` | `string` | Empty | Tool name to match (must be linked into the binary). | | `class` | `string` | Empty | Tool class to match: `read_only` or `side_effecting`. | | `command_prefix` | `string` | Empty | Prefix matched against the tool's primary argument (e.g., bash command or fetch URL). A schemeless URL prefix matches both `http` and `https`. | | `command_contains` | `string[]` | Empty | Non-empty substrings matched anywhere in the tool's primary argument (any single match triggers). | | `action` | `string` | Required | Action on match: `allow`, `ask`, or `deny`. | ```yaml permission: unmatched: ask fallback: deny askers: [decide, wire] chain_timeout_s: 60 rules: - class: read_only action: allow - tool: bash command_prefix: "git status" action: allow - tool: bash command_contains: ["rm -rf", "sudo "] action: deny ``` ## System Prompt See [Profiles & Prompts](/configuration/profiles-and-prompts). ### `system_prompt` `base_file` and `replace` are mutually exclusive. | Key | Type | Default / Behavior | Description | |---|---|---|---| | `system_prompt.base_file` | `string` | Empty | File holding the prompt's base section. Relative paths resolve against the settings file's directory; `~/` resolves under `$HOME`. | | `system_prompt.replace` | `string` | Empty | Inline text replacing the entire prompt (except the CLI catalog section when active). | | `system_prompt.append` | `string` | Empty | Text appended to the base prompt section. | | `system_prompt.sections` | `map[string]string` | Empty | Named prompt sections to set or override. | | `system_prompt.remove` | `string[]` | Empty | Named prompt sections to remove. | ## Limits & Background Jobs See [Limits & Exit Codes](/operations/limits-and-exit-codes) and [Built-in Tools & Jobs](/capabilities/tools-and-jobs). ### `limits` A value of `0` disables the limit (except `truncation_retries`, where `0` disables retries and omission uses the default of `1`). | Key | Type | Default / Behavior | Description | |---|---|---|---| | `limits.max_tokens_per_run` | `int` | `0` (off) | Maximum tokens consumed in a single run (`≥ 0`). | | `limits.max_duration_s` | `int` | `0` (off) | Wall-clock time limit for a single run, in seconds (`≥ 0`). | | `limits.max_turns` | `int` | `0` (off) | Maximum model turns in a single run (`≥ 0`). | | `limits.max_continuations` | `int` | `0` (off) | Maximum continuations allowed in a run (`≥ 0`). | | `limits.truncation_retries` | `int` | `1` | Consecutive truncated turns retried before settling `output_truncated`. Set `0` to disable (`≥ 0`). | ### `jobs` | Key | Type | Default / Behavior | Description | |---|---|---|---| | `jobs.max_running` | `int` | Runtime default | Maximum concurrent background jobs (`≥ 0`). | | `jobs.timeout_s` | `int` | Runtime default | Per-job wall-clock timeout, in seconds (`≥ 0`). | | `jobs.on_idle` | `string` | Runtime default | Handling for a job result arriving while the session is idle: `wake` or `hold`. | | `jobs.max_unattended_wakes` | `int` | `0` (no limit) | Maximum consecutive woken runs without client input (`≥ 0`). | ## Structured Output ### `finish` | Key | Type | Default / Behavior | Description | |---|---|---|---| | `finish.schema_file` | `string` | Empty | Path to a valid JSON Schema file used to validate typed final results. Relative paths resolve against the settings file's directory; `~/` resolves under `$HOME`. | ## Manifests & Skills See [CLI Registry & Script Tools](/capabilities/cli-registry), [Feeds & Daemon](/capabilities/feeds-and-daemon), [MCP Servers](/capabilities/mcp-servers), [Skills](/capabilities/skills), and [Manifests Reference](/reference/manifests). ### `cli_registry` Legacy alias: `cliregistry`. | Key | Type | Default / Behavior | Description | |---|---|---|---| | `cli_registry.paths` | `string[]` | Empty | Registry directories. Relative paths resolve against the working directory; `~/` resolves under `$HOME`. | | `cli_registry.defaults` | `bool` | `true` | Load manifests from poo's default `cli-registry` directory under the user config directory. Set `false` to isolate. | ### `feeds` | Key | Type | Default / Behavior | Description | |---|---|---|---| | `feeds.paths` | `string[]` | Empty | Feed manifest directories. Relative paths resolve against the working directory; `~/` resolves under `$HOME`. | | `feeds.defaults` | `bool` | `true` | Load manifests from poo's default `feeds` directory under the user config directory. Set `false` to isolate. | ### `mcp` | Key | Type | Default / Behavior | Description | |---|---|---|---| | `mcp.paths` | `string[]` | Empty | `mcp.json` manifest files or directories. Relative paths resolve against the working directory; `~/` resolves under `$HOME`. | | `mcp.defaults` | `bool` | `true` | Load manifests from poo's default `mcp` directory under the user config directory. Set `false` to isolate. | ### `skills` `default` and `user_path` are mutually exclusive. Missing skill directories are dropped with a warning (silently for `default`). | Key | Type | Default / Behavior | Description | |---|---|---|---| | `skills.default` | `bool` | `false` | When `true`, offer skills from `~/.agents/skills`. Mutually exclusive with `user_path`. | | `skills.user_path` | `string` | Empty | Custom user skills directory (`~/` expanded). Mutually exclusive with `default`. | | `skills.paths` | `string[]` | Empty | Additional skill directories. Relative paths resolve against the working directory; `~/` resolves under `$HOME`. | ## Session Persistence & Prompts See [Sessions & Durability](/operations/sessions-and-durability). ### `session` | Key | Type | Default / Behavior | Description | |---|---|---|---| | `session.mode` | `string` | `logged` | Session persistence mode: `logged`, `ephemeral`, or `durable`. | | `session.dir` | `string` | `~/.local/state/poo/sessions` | Directory where session logs and state live (`~/` expanded). | | `session.project_prompt` | `bool` | `false` | Include the working directory's `AGENTS.md` (or `CLAUDE.md` if absent) in the prompt. Reads only the working directory; never walks up. | | `session.user_prompt` | `bool` | `false` | Load user instructions from the binary's default config path. | | `session.user_prompt_file` | `string` | Empty | Path to a custom user instructions file (`~/` expanded). Setting this enables user instructions without setting `user_prompt: true`. | | `session.retention.max_age_days` | `int` | Unset (opt-in) | Delete sessions whose last activity is older than this many days on prune (`≥ 0`). | | `session.retention.max_sessions` | `int` | Unset (opt-in) | Keep at most this many sessions on prune (`≥ 0`). | | `session.durable.max_resumptions` | `int` | `3` | Maximum crash resumptions before the durable planner gives up. Minimum `1`. | | `session.durable.lease_ttl_s` | `int` | `30` | Session lease duration before expiry, in seconds. Minimum `1`. | | `session.durable.auto_resume` | `bool` | `false` | Automatically resume an unsettled run when a durable session loads. | | `session.durable.store` | `string` | `file` | Durable storage backend: `file` or `sqlite`. | ```yaml session: mode: durable dir: ~/.local/state/poo/sessions project_prompt: true retention: max_age_days: 30 max_sessions: 200 durable: store: sqlite max_resumptions: 3 lease_ttl_s: 30 auto_resume: false ``` --- # Models File Reference A models file declares endpoints and the models each endpoint serves. It populates the catalog's `models_file` layer, below `settings.yaml` and above `curated` and `discovery` (see [Models & Catalog](/configuration/models-and-catalog)). ## Discovery and Format poo locates a models file in this order: 1. The path set by `models_file` in `settings.yaml`. Relative paths resolve against the **settings file's directory**; `~/` resolves under the home directory. 2. Otherwise, if `settings.yaml` was loaded from disk, poo looks for `models.yaml` or `models.json` in the same directory. - If **both** `models.yaml` and `models.json` exist beside `settings.yaml`, loading fails with an error so neither file is silently ignored. - If a models file exists (or is explicitly named) and fails to read or validate, loading fails. Both YAML and JSON are accepted through the same parser (leading UTF-8 BOMs are stripped). A file with a top-level `providers` key is imported as a [pi `models.json`](#pi-models-json-import); otherwise it is parsed as poo's native `models.yaml` format. ## Native `models.yaml` Schema poo decodes `models.yaml` **strictly**: any unknown key is an error. The file must declare at least one endpoint, and each endpoint must declare at least one model. Every model declared under endpoint `` and key `` is registered in the catalog under the name **`/`**. ```yaml endpoints: home: endpoint: http://localhost:4000/v1 api: chat_completions api_key_env: HOME_API_KEY session_header: x-session-id skip_probe: false instructions_per_question: false models: qwen3: model_id: qwen3-32b ops: [chat, systemone] inputs: [text, image] context_limit: 131072 input_limit: 65536 max_output: 16384 tools_mode: auto reasoning: mode: toggle param: chat_template_kwargs.enable_thinking reasoning_levels: [off, high] prompt_variant: qwen quirks: [think_tags] sampling: temperature: 0.7 top_p: 0.9 top_k: 40 min_p: 0.05 ``` ### Top-Level Keys | Key | Type | Required | Description | | :--- | :--- | :--- | :--- | | `endpoints` | `map` | Yes | Map of endpoint names to endpoint definitions. Must be non-empty. | ### Endpoint Keys (`endpoints.`) | Key | Type | Required | Description | | :--- | :--- | :--- | :--- | | `endpoint` | `string` | Yes | Base URL of the endpoint (e.g. `http://localhost:4000/v1`). | | `api` | `string` | No | Wire API spoken by the endpoint: `chat_completions` (default when omitted), `responses`, or `anthropic_messages`. Inherited by models under this endpoint. | | `api_key_env` | `string` | No | Environment variable holding the API key. Also matched against stored key providers in the auth file (see [Providers & Auth](/configuration/providers-and-auth)). | | `api_key` | `string` | **Refused** | **Always rejected.** See [Literal `api_key` Refusal](#literal-api-key-refusal). | | `session_header` | `string` | No | HTTP header name that carries the session ID on requests (for gateways that route a conversation's requests together). | | `skip_probe` | `bool` | No | When `true`, skips discovery probing for this endpoint. Use for endpoints without a discoverable model list. | | `instructions_per_question` | `bool` | No | When `true`, folds decider instructions into each question instead of sending a request-level `instructions` field. | | `models` | `map` | Yes | Map of model keys to model definitions. Must be non-empty. | ### Model Keys (`endpoints..models.`) | Key | Type | Required | Description | | :--- | :--- | :--- | :--- | | `model_id` | `string` | No | Wire model identifier sent to the endpoint. Defaults to the map key ``. | | `ops` | `string[]` | No | Supported operations: `chat`, `systemone`, `decisions`, `compact`. Defaults to `[chat]` if no layer sets it. | | `inputs` | `string[]` | No | Supported input modalities: `text`, `image`, `audio`. Unknown modality names fail load. | | `context_limit` | `int` | No | Total context window in tokens. | | `input_limit` | `int` | No | Maximum prompt tokens accepted by the endpoint when smaller than `context_limit`. | | `max_output` | `int` | No | Maximum output tokens per response. | | `reasoning` | `object` | No | Reasoning control object with `mode` (`none`, `toggle`, `effort`, `budget`) and `param` (dot-path string). See [Reasoning & Sampling](/configuration/reasoning-and-sampling). | | `reasoning_levels` | `string[]` | No | Accepted reasoning levels, lowest first (e.g. `[off, low, medium, high, xhigh]`). | | `tools_mode` | `string` | No | Tool-calling mode: `native`, `text`, `auto`, or `none`. | | `prompt_variant` | `string` | No | Prompt section variant key (used by model-family prompt guidance). | | `quirks` | `string[]` | No | Ordered list of transport quirks (e.g. `think_tags`, `audio_url`). See [Transport Quirks](/configuration/reasoning-and-sampling#transport-quirks). | | `sampling` | `object` | No | Model sampling defaults: `temperature`, `top_p`, `top_k`, `min_p` (floats). | ### Literal `api_key` Refusal A models file is designed to be shared or checked into version control. Writing a literal `api_key` on any endpoint in `models.yaml` fails load with an error. Instead: - Set `api_key_env: MY_API_KEY` on the endpoint, or - Store the credential in poo's auth file (`poo login`), or - If you must write a literal key, put it on the endpoint in `settings.yaml` (which overrides the models file's endpoint). ## pi `models.json` Import When a models file has a top-level `providers` key (or is a `models.json` written by `pi`), poo translates it into the `models_file` catalog layer under `/`. - **Forward compatibility**: pi fields that poo does not map are ignored rather than rejected. - **Required fields**: at least one provider; each provider must have `baseUrl` and a non-empty `models` array; each model must have `id`. ### Field Mapping | pi field | poo mapping / rule | | :--- | :--- | | `providers..baseUrl` | `endpoint` | | `providers..api` | `""` or `openai-completions` → default (`chat_completions`); `anthropic-messages` → `anthropic_messages`; `openai-codex-responses` → `responses` (allowed **only** for provider `openai-codex`). Any other API name is refused. | | `providers..apiKey` | `$VAR` → `api_key_env: VAR`. Values starting with `!` (shell commands) are ignored. Literal keys are copied into `settings.Endpoints[]` (never stored in the catalog layer) unless `settings.yaml` already defines that endpoint. If empty or ignored, poo checks the resolved auth file for an `api_key` entry under ``. | | `models[].id` | `model_id` (and `/` catalog name) | | `models[].input` | `inputs` (validated against `text`, `image`, `audio`) | | `models[].contextWindow` | `context_limit` | | `models[].maxTokens` | `max_output` | | `models[].reasoning` + `models[].compat.supportsReasoningEffort` | When both are `true`, sets `reasoning: { mode: effort, param: reasoning_effort }`. | | `models[].thinkingLevelMap` | When `reasoning` and `supportsReasoningEffort` are both `true`: non-null keys in canonical order (`off`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`) become `reasoning_levels`. If `thinkingLevelMap` is omitted, defaults to `[off, low, medium, high]`. | ## `builtin-models.yaml` and `POO_BUILTIN_MODELS` poo embeds `config/builtin-models.yaml` in the binary using the exact same `models.yaml` schema. It provides definitions for built-in providers whose endpoints do not expose a full model list or require provider metadata (`session_header`, `skip_probe`, `api`, `reasoning_levels`): - `openai-codex` (Responses API, `skip_probe: true`) - `ollama-cloud` (`OLLAMA_API_KEY`) - `opencode`, `opencode-go`, `opencode-anthropic`, `opencode-go-anthropic` (`OPENCODE_API_KEY`, `session_header: x-opencode-session`) - `typesafe` (`TYPESAFE_API_KEY`, `skip_probe: true`, `instructions_per_question: true`, `ops: [systemone]`) ### Gating and Precedence - Built-in providers are added only when a credential file exists at the resolved auth path. - Each built-in endpoint is gated on its own credential. `openai-codex` requires an `openai-codex` entry in the credential file. Endpoints with `api_key_env` require that key via environment variable, auth file, or a literal in `settings.yaml`. - Your `models.yaml` or `models.json` folds **over** the built-ins by name, so you can override any built-in endpoint or model without losing the others. ### Overriding with `POO_BUILTIN_MODELS` Set the `POO_BUILTIN_MODELS` environment variable to a YAML or JSON file path (in the same `models.yaml` schema) to replace the embedded `builtin-models.yaml`: ```bash POO_BUILTIN_MODELS=/path/to/custom-builtins.yaml poo models ``` When `POO_BUILTIN_MODELS` is set, poo always reads and validates that file even without a credential file. A missing or invalid file fails the load immediately. --- # Manifests Reference `poo` loads three external manifest types: **feeds**, **CLI registry** (`cli_registry`), and **MCP servers** (`mcp.json`). All three share a discovery model and XDG default directories, while differing in format support, strictness, and how entries activate. ## Comparison | Aspect | `feeds` | `cli_registry` | `mcp.json` (+ `poo` block) | |---|---|---|---| | **Purpose** | Long-lived event sources (`feed:`) | Typed CLI and script tools (`call_cli`) | Stdio MCP servers (`call_mcp`) and MCP resource feeds | | **Formats** | `.json`, `.yaml`, `.yml`, `.toml` | `.json`, `.yaml`, `.yml`, `.toml` | `.json` only (non-`.json` files skipped in dirs; rejected if named directly) | | **Top-level envelope** | `version: 1`, `feeds: {...}` | `version: 1`, `tools: {...}`, optional `availability` | `mcpServers: {...}`, optional `poo: {...}` | | **Unknown fields** | Rejected everywhere | Rejected everywhere | Ignored at top level and inside `mcpServers.`; **rejected** inside `poo` | | **Duplicate keys** | Rejected | Rejected | Rejected everywhere in file | | **Duplicate names across files** | Load error (names both files) | Load error (names both files) | Load error for duplicate server names or resource feed names | | **Default XDG directory** | `$XDG_CONFIG_HOME/poo/feeds/` | `$XDG_CONFIG_HOME/poo/cli-registry/` | `$XDG_CONFIG_HOME/poo/mcp/` | | **Settings keys** | `feeds.paths`, `feeds.defaults` | `cli_registry.paths`, `cli_registry.defaults` | `mcp.paths`, `mcp.defaults` | | **Profile override** | `profiles..feeds_defaults` | `profiles..cli_registry_defaults` | `profiles..mcp_defaults` | | **Env var** | `POO_FEEDS_PATH` | `POO_CLI_REGISTRY_PATH` | `POO_MCP_PATH` | | **CLI flag (repeatable)** | `--feeds-path` | `--cli-registry-path` | `--mcp-path` | | **Activation** | Always-on feeds start automatically; `optional: true` starts via `subscribe_feed` | Offered on profiles with a side-effecting tool (filtered by `availability`) | Declared only; started only when named in `profiles..mcp_servers` | ## Discovery and default XDG directories For each manifest kind, `poo` discovers files from: 1. The default XDG directory (when defaults are enabled): - `$XDG_CONFIG_HOME/poo/feeds/` - `$XDG_CONFIG_HOME/poo/cli-registry/` - `$XDG_CONFIG_HOME/poo/mcp/` 2. Paths listed in `.paths` in settings. 3. Paths from `POO_FEEDS_PATH`, `POO_CLI_REGISTRY_PATH`, or `POO_MCP_PATH` (OS path-list separated; scrubbed from child processes). 4. Repeatable CLI flags: `--feeds-path`, `--cli-registry-path`, `--mcp-path`. Discovery rules: - A missing default XDG directory is ignored, not an error. - Paths starting with `~/` resolve under the user's home directory. Relative paths resolve against the binary's working directory (where the process starts), not a per-session working directory. - Every path may be a file or a directory. Discovered files are deduplicated and sorted deterministically. - Loading is all-or-nothing: a schema error, duplicate name, or missing explicit path fails the build and names the offending file. ## `*.defaults` and profile interaction Whether a manifest kind's default XDG directory loads is decided by a two-level precedence chain: 1. **`profiles.._defaults`** (wins when set; inherited from the profile's `base` if omitted) 2. **`.defaults`** in top-level settings 3. **Default: `true`** (when neither is set) ```yaml feeds: defaults: false # off globally profiles: worker: base: code feeds_defaults: true # re-enabled for this profile and its children cli_registry_defaults: false mcp_defaults: false mcp_servers: [avenor] ``` Two profile lists interact with manifests differently: - **`profiles..mcp_servers`** is a **selection**: loading `mcp.json` only declares servers; a session starts only the servers named in its profile's `mcp_servers` (merged with `base`). An unknown server name emits a warning. - **`profiles..feeds`** is a **presence assertion**, not a filter. It declares feeds the profile expects to exist, satisfied by either a feed manifest or an active MCP server's resource feed. Missing names emit a warning; loaded feeds still run regardless of this list. See [Profiles & Prompts](/configuration/profiles-and-prompts) for full profile inheritance rules. --- ## Feed manifests Top-level envelope: ```json { "version": 1, "feeds": { "": { "description": "Short summary shown in the jobs prompt.", "command": ["my-watcher", "--stream"], "env": { "API_TOKEN": "env:API_TOKEN", "SESSION_ID": "session:id", "TARGET_URL": "scope:url", "MODE": "watch" }, "restart": true, "on_idle": "wake", "max_pending": 16, "optional": true, "scope": { "url": {"type": "string", "pattern": "^https://"} }, "filter": { "question": "Does this event require action?", "min_no_probability": 0.9 } } } } ``` ### Feed entry fields | Field | Type | Required | Description | |---|---|---|---| | `command` | `string[]` | Yes | Non-empty argv executed by the session's executor. | | `description` | `string` | No | Description rendered in the jobs prompt. | | `env` | `map` | No | Added on top of benign env vars. Values: literal, `env:NAME` (scrubbed host env), `session:id`, or `scope:NAME` (must match a declared `scope` field). | | `restart` | `bool` | No | Default `false`. Restart with exponential backoff (`1s` to `60s`, reset after `60s` uptime). Ignored when suspended by a command filter fault. | | `on_idle` | `"wake" \| "hold"` | No | Whether inputs wake an idle session. Defaults to `jobs.on_idle` (always-on) or `"hold"` (`optional: true`). | | `max_pending` | `int` (`>= 0`) | No | Maximum queued undelivered inputs before dropping oldest. `0` or omitted uses default `16`. | | `optional` | `bool` | No | Default `false`. When `true`, starts only via `subscribe_feed`. | | `scope` | `map` | No | Allowed only when `optional: true`. Keys match `^[a-z][a-z0-9_]*$`. Each value has `type: "string"` (required) and optional Go regex `pattern`. | | `filter` | `Filter` | No | Either `{"question": "...", "min_no_probability": 0.5 < p <= 1}` or `{"command": [...]}`. Never both. | Validation rules: - `version` must be `1`. - Feed names must match `^[a-z0-9][a-z0-9_-]*$` and cannot collide with another feed manifest or an MCP resource feed. - A `scope` block on a non-optional feed fails load. - A `scope:NAME` reference in `env` must name a declared field in `scope`. For stdout line format, filter runtime behavior, and `subscribe_feed`, see [Feeds & Daemon](/capabilities/feeds-and-daemon). --- ## CLI Registry manifests CLI registry manifests are loaded by `github.com/sdougbrown/cli-registry` and exposed through `call_cli` (and `find_tool` when a decision model is active and the catalog exceeds 30 entries). Top-level envelope: ```json { "version": 1, "tools": { "": { "description": "Wait for a child run to finish.", "command": ["avenor", "await", "--until=done", "--format=json"], "env": { "AVENOR_BIND_HOST": "poo", "AVENOR_BIND_SESSION": "session:id" }, "timeout": "36m", "inputSchema": { "type": "object", "properties": { "target": {"type": "string", "description": "Child run ID or label."} }, "required": ["target"], "additionalProperties": false }, "bindings": [ {"property": "target", "style": "positional"} ], "output": { "mode": "json", "success_exit_codes": [0, 10, 11, 12] } } } } ``` ### Tool entry fields | Field | Type | Required | Description | |---|---|---|---| | `description` | `string` | Yes | Shown in the catalog prompt and `find_tool` results. | | `command` | `string[]` | Yes | Base argv executed through the session's executor. | | `env` | `map` | No | Added on top of benign env vars. Supports literals, `env:NAME` (scrubbed host env), and `session:id`. | | `timeout` | `string` | No | Go duration string (e.g. `"36m"`, `"30s"`) overriding default command timeout. | | `inputSchema` | `object` | No | JSON Schema validating model arguments before spawning a process. | | `bindings` | `Binding[]` | No | Maps `inputSchema` properties onto argv or stdin. Each entry names `property`, `style` (`positional`, `equals`, `stdin`, `json`, etc.), and optional `flag`. | | `output` | `object` | No | `mode`: `"raw"`, `"json"`, or `"json-pointer"`. Optional `success_exit_codes` (`int[]`) treats listed exit codes as non-errors. | An optional top-level `availability` block may declare Umpire v1 rules over load-time conditions to filter which entries a session offers. ### Non-CLI script (`fn`) tools A `cli_registry` entry can wrap a script with a pure JSON stdin/stdout contract: ```json { "description": "Sum a pair", "command": ["python3", "fn_notes.py"], "bindings": [{"property": "data", "style": "json"}], "output": {"mode": "json"} } ``` - `style: "json"` serializes a concrete `object` or `array` schema property to the script's stdin (a tool may have at most one `stdin` or `json` binding; `flag` is optional). - `output.mode: "json"` returns stdout JSON directly as the tool result (nonzero exit is an error with stderr diagnostics). - Edge case: a JSON `null` result falls back to the exit-code envelope; wrap nullable results in an object such as `{"result": null}`. See [CLI Registry & Script Tools](/capabilities/cli-registry) for usage details. --- ## MCP manifests (`mcp.json` + `poo` block) `mcp.json` uses the standard `mcpServers` format shared with Claude Code and other harnesses, plus an optional top-level `poo` block for resource feeds. ```json { "mcpServers": { "avenor": { "command": "avenor", "args": ["mcp", "--bind-host", "poo", "--bind-session", "${session:id}"], "env": { "AVENOR_LOG": "${AVENOR_LOG:-info}" } } }, "poo": { "servers": { "avenor": { "feeds": { "avenor-inbox": { "resource": "avenor://inbox", "on_idle": "wake", "description": "Messages from Avenor children.", "filter": { "command": ["jq", "-c", ".text | fromjson | .messages[]"] } } } } } } } ``` ### `mcpServers.` fields Server names must match `^[A-Za-z0-9_-]+$` and be unique across all loaded MCP manifests. | Field | Type | Required | Description | |---|---|---|---| | `command` | `string` | Yes (for `stdio`) | Executable path or name (template string). | | `args` | `string[]` | No | Command arguments (template strings). | | `env` | `map` | No | Environment variables (template strings), merged on top of the scrubbed host environment. An explicit `${NAME}` can re-inject a scrubbed variable. | | `type` | `string` | No | Must be absent or `"stdio"` to launch. `"http"`, `"sse"`, and `"streamable-http"` are skipped with a warning; any other value fails load. | | `url` | `string` | No | If set with no `type`, treated as `"http"` and skipped with a warning. | Unknown top-level keys and unknown fields inside an `mcpServers` entry are ignored so one `mcp.json` works across harnesses. ### Launch-time templates `command`, each element of `args`, and each value in `env` are parsed at load time and resolved when the server launches for a session: | Syntax | Resolution | |---|---| | `${NAME}` | Host environment variable `NAME`. Launch fails if unset. | | `${NAME:-default}` | Host environment variable `NAME`, or `default` if unset. | | `${session:id}` | The session's native ID (preserved across resumes). | | `$$` | Literal `$`. | Load-time errors: unterminated `${`, empty variable name, a `:-default` on `${session:...}`, or any `session:` key other than `id`. ### The `poo` block The top-level `poo` key is owned strictly by `poo`: any unknown field inside `poo` fails load. Path: `poo.servers..feeds.` | Field | Type | Required | Description | |---|---|---|---| | `resource` | `string` | Yes | MCP resource URI to subscribe to. Unique per server. | | `description` | `string` | No | Description rendered in the jobs prompt. | | `on_idle` | `"wake" \| "hold"` | No | Idle delivery policy; inherits `jobs.on_idle` when omitted. | | `filter` | `Filter` | No | Same `command` or `question` filter schema as [Feed manifests](#feed-manifests). | Validation rules: - `` must be defined in the same file's `mcpServers` and use the `stdio` transport. - `` must match `^[a-z0-9][a-z0-9_-]*$` and be unique across all MCP resource feeds and all loaded `feeds` manifests. - Two feeds on the same server cannot subscribe to the same `resource` URI. See [MCP Servers](/capabilities/mcp-servers) for startup timeouts, relaunch budgets, and `call_mcp`. --- # Session log v0 A poo session log is an append-only JSONL file: one JSON object per line, in the order the records were produced. This document is the contract a consumer parses. A session log holds one session. The file is created exclusively, so a run pointed at a log that already exists fails before it sends a request rather than appending a second session to the log. ## Where a session's log lives A logged session's log is `/.jsonl`, and its lock is `/.lock`. The lock is an exclusive `flock`, taken when the session is created or loaded and held until the session is closed: a second process is refused while the session is live, and the kernel releases the lock when the holding process dies. The lock file is never deleted, and a lock file with no log beside it is a harmless leftover. The log is built in a temporary file and renamed into place, so a session that was cut short during its construction is never a session: the temporary file is left behind, and a prune removes it once it is old. A log that was cut short in the middle of a record is truncated when the session is loaded: the bytes after the last newline are not a record. The load then recovers the session, appending the records that resolve what the session left open: an `interrupted` result, and the message that carries it, for every tool call without one, a denied `permission.answered` for every ask without an answer, a `run.settled` with the reason `interrupted` for every run that never settled, a `job.ended` with the outcome `interrupted` for every job that never ended, a `feed.ended` with the outcome `interrupted` for every feed attempt that never ended, an `input.delivered` for every input whose `message` names it in `input_id` but has no `input.delivered` after it, and an `input.dropped` with the reason `interrupted` for every input that never reached the model. The recovery appends only what is missing, so loading a session twice writes nothing twice. A delivery write that outlives the finalization's wait is a stalled store. The finalization gives a delivery's message and fate their own record budgets before that decision, so a delivery within both budgets is not a stall; the wait remains bounded at two record budgets. When the store does stall, the session breaks, the store failure is the run's reason (or a losing candidate when the run was cancelled), and the input's fate is left to the records that land and to a load, which applies the two rules above. The finalization and the close each attempt a bounded flush. A store that is still stalled at the bound is reported by the close's `ErrCloseStalled`; records it has not stored or flushed cannot be recovered, so a load applies the rules above only to what the store holds. The first record is always `session.created`, and it carries `"format": "poo-session-v0"`. A consumer that does not recognise the format should stop rather than guess. ## Common fields Every record carries these three fields, from the same envelope: | Field | Type | Meaning | |---|---|---| | `record` | string | The record's name, e.g. `"tool.call"`. | | `seq` | integer | The session-monotonic sequence number. The first record is 1. | | `ts` | string | The record's timestamp, RFC 3339 with nanosecond precision, in UTC. | The record's own fields follow the envelope. A record that someone produced also carries an `origin`: | Field | Type | Meaning | |---|---|---| | `origin` | string | Who produced the record: `"user"`, `"model"`, `"tool"`, `"system"`, `"job"`, `"steer"`, `"interrupt"`, `"follow_up"`, `"compaction"`, `"feed:"`, `"feed:[=]"` or `"hook:"`. **Absent** on the records that no one produced: the session's own header, a run's boundaries, the usage accounting. | ## Record names | Name | Written when | |---|---| | `session.created` | Once, first, when the session starts. | | `run.started` | Once per run, when the run begins. | | `system_prompt` | Once per run whose prompt differs from the previous one, with the whole prompt. | | `message` | Once per message that enters the model's history. | | `tool.call` | Once per tool call the model makes, before it runs. A call a running tool made through the nested seam is recorded here too, with the parent call's handle in `parent`. | | `tool.result` | Once per tool call, after it runs. | | `usage` | Once per provider request. | | `provider.attempt` | Once per attempt of a request that failed. | | `input.queued` | Once per input the session accepts. | | `input.delivered` | Once per input that reaches the model. It follows the `message` that delivers the input, and that message names the input in `input_id`. | | `input.dropped` | Once per input that never reaches the model. | | `input.held` | Once per round of job results that were held instead of delivered. | | `job.started` | Once per background job, when it is accepted. | | `job.ended` | Once per background job, when it finishes. | | `feed.started` | Once per attempt of a feed, when the attempt starts. | | `feed.ended` | Once per attempt of a feed, when the attempt ends. | | `tool.started` | Once per side-effecting tool call, when the call starts. | | `run.resumed` | Once per run that resumes after a crash. | | `turn.hook` | Once per turn hook, at its start and at its end. | | `feed.subscribed` | Once per feed instance, when it subscribes, and again when a call changes the prompt it screens its records with. | | `feed.unsubscribed` | Once per feed instance, when it unsubscribes. | | `observer.dropped` | Once a second at most, per observer that fell behind. | | `turn.interrupted` | Once per turn an interrupt cut short. | | `compaction` | Once per compaction a compactor produced. | | `session.models_changed` | Once per model switch, between the runs. | | `model.output_limit` | Once per learned output cap, when an endpoint rejects a request's `max_tokens`. | | `decision` | Once per decision call, failures included. | | `permission.asked` | Once per permission ask, when the run starts waiting for an answer. | | `permission.answered` | Once per permission ask, when the answer arrives. | | `run.settled` | Once per run, when the run ends. | The fields of the records grow over time. A consumer must tolerate a field it does not recognise: the fields below are the ones the current core writes, and a later stage adds more. ## `session.created` The first record of a log. | Field | Type | Meaning | |---|---|---| | `format` | string | The record vocabulary. Always `"poo-session-v0"`. | | `session_id` | string | The session's identifier. | | `mode` | string | The persistence mode. `"logged"` for a `poo run`. | | `created_at` | string | RFC 3339, UTC. | | `working_dir` | string | The absolute directory the run works in. | | `profile` | string | The profile the session was built from. Absent when the log was written before the field existed. | | `roles` | object | The models the session talked to. See below. | | `model` | object | The model the session talks to. See below. | | `tools` | array of objects | The tools linked into the session, in call order. | | `settings_hash` | string | The hash of the settings the session was built with. Absent when the log was written before the field existed. | | `context_limit` | integer | The model's context window, in tokens. | | `tools_mode` | string | How the run asks for tool calls: `"native"`, `"text"` or `"auto"`. | | `reasoning_effort` | string | The `reasoning_effort` the run sends. Absent when it sends none. | | `build` | object | The binary that produced the session. | `roles` holds the session's effective roles: | Field | Type | Meaning | |---|---|---| | `chat` | object | The chat model. Absent when the session had none. | | `decider` | object | The decision model. Absent when the session had none. | A role holds model info: its `name`, its `model_id`, its `endpoint`, its `api`, its `ops`, its `context_limit` and its `input_limit`. The roles are the ones the session ran with, not the ones the current settings would pick: a session loaded by another binary keeps the roles it was made with. `context_limit` is the whole window the prompt and the answer share, and `input_limit` is the largest prompt the endpoint accepts, absent when it takes its whole window. The prompt is bounded by the smaller of the two, so a consumer that measures a prompt reads both. `model` holds: | Field | Type | Meaning | |---|---|---| | `id` | string | The provider's model identifier. | | `endpoint` | string | The endpoint, without credentials. Absent when empty. Renamed from `base_url` before v1; older logs carry `base_url`. | | `max_output` | integer | The model's output-token limit. Absent when unknown. | The `endpoint` never carries credentials: a URL that names a user and a password is written without its userinfo, so a consumer can read the log without picking up a secret. Each entry of `tools` holds: | Field | Type | Meaning | |---|---|---| | `name` | string | The tool's identifier. | | `class` | string | The tool's side-effect class: `"read_only"` or `"side_effecting"`. | | `background` | string | The tool's background mode: `"allowed"` or `"always"`. Absent when the tool never runs in the background. | | `idempotent` | boolean | `true` for a `"side_effecting"` tool whose repeated execution is safe, so a durable session may replay an interrupted call. Absent when the tool does not declare it, and on a log written before the field existed. | `build` holds: | Field | Type | Meaning | |---|---|---| | `name` | string | The binary's name. | | `version` | string | The binary's version. | ## `run.started` | Field | Type | Meaning | |---|---|---| | `run_id` | string | The run's identifier: a ULID (26 characters of Crockford base32, the time first). | | `prompt_hash` | string | The hex SHA-256 of the prompt text. | | `started_at` | string | RFC 3339, UTC. | | `model_id` | string | The model the run talks to. | | `max_turns` | integer | The turn limit. `0` means the run is unlimited. | | `tools_mode` | string | How the run asks for tool calls. | | `reasoning_effort` | string | The `reasoning_effort` the run sends. Absent when it sends none. | | `trigger` | string | What started the run: `"prompt"`, `"job"` or `"feed"`. Absent on a log written before the field existed. | | `jobs` | array of objects | The job results that started a job run. Absent on a prompt run. | | `feeds` | array of strings | The feed instances whose inputs started the run, by label (`feed.started` names the form), in queue order. Absent when no feed's input started the run. A wake that carried both a job's result and a feed's input has the trigger `"job"` and names the feeds too. | A `jobs` entry holds: | Field | Type | Meaning | |---|---|---| | `job` | string | The job's identifier, e.g. `"j3"`. | | `handle` | string | The handle of the tool call the job came from, e.g. `"r1"`. The call returned at once with a `started` outcome, and the job carries that call's handle. | | `tool` | string | The tool the job ran. | | `text` | string | The job's result, as the model reads it. | | `outcome` | string | The job's outcome. | ## `message` One message in the model's history. The messages in the log are the same list the model sees: nothing is trimmed, rewritten or summarised. | Field | Type | Meaning | |---|---|---| | `run_id` | string | The run the message belongs to. | | `turn` | integer | The turn the message belongs to. `0` for the run's input. | | `origin` | string | Who produced the message: `"user"`, `"model"`, `"tool"`, `"system"`, `"job"`, `"steer"`, `"interrupt"`, `"follow_up"`, `"compaction"`, `"feed:"`, `"feed:[=]"` or `"hook:"`. | | `role` | string | The message's role: `"system"`, `"user"`, `"assistant"` or `"tool"`. | | `content` | array of objects | The message's content blocks. | | `message_id` | string | The message's session-monotonic id, e.g. `"m7"`. Absent when the message has none. | | `input_id` | string | The input delivered by this message. Absent on other messages and older logs. | | `partial` | boolean | `true` when the message was cut short. Absent when it was not. | | `cause` | string | Why the message was cut short: `"interrupt"` or `"provider_error"`. Absent unless the message is partial. | | `delivery_note` | object | How much of the previous reply the user had seen. Absent when the message carries none. | | `data` | object | The object a feed's filter wrote beside the message's text: the structured record. Absent unless a filter produced one. | A partial message is the text a cut-short response carried. The assistant's own tool calls in a partial response did not run, and the calls that did not run are recorded as `skipped`. `delivery_note` holds: | Field | Type | Meaning | |---|---|---| | `message_id` | string | The assistant message the user had seen part of. | | `upto_chars` | integer | How many characters of that message the user had seen, in code points over its text blocks. | | `text` | string | The rendered note. It is prefixed to the text of the message, followed by a blank line, so the message's `content` holds it too. Empty when the whole reply was presented. | The note is part of the record, so a replay shows exactly what the user saw. The assistant message itself is never trimmed: the note is the record. Each content block holds: | Field | Type | Meaning | |---|---|---| | `kind` | string | `"text"`, `"thinking"`, `"tool_call"`, `"tool_result"`, `"image"` or `"provider"`. | | `text` | string | The block's text. Absent when empty. | | `tool_call_id` | string | The provider's id for the call. Set on `tool_call` and `tool_result` blocks. | | `name` | string | The tool's name. Set on `tool_call` and `tool_result` blocks. | | `arguments` | object or string | A `tool_call` block's arguments. A JSON object when the model sent valid JSON, and a JSON string holding the raw text when it did not. | | `is_error` | boolean | `true` when a `tool_result` reports a failure. Absent when false. | | `media_type` | string | An attachment block's media type, e.g. `"image/png"`. | | `data` | string | An attachment block's bytes, base64-encoded. | | `provider` | object | The block's opaque provider companion. Absent when the block has none. | A `tool_result` block's `text` is the model-facing text of the result. A `provider` block holds: | Field | Type | Meaning | |---|---|---| | `api` | string | The wire API the payload belongs to: `"chat_completions"`, `"responses"` or `"anthropic_messages"`. | | `type` | string | The provider's own name for the payload, e.g. `"thinking_signature"`, `"reasoning"`, `"redacted_thinking"` or `"compaction"`. | | `data` | any | The payload, verbatim. The core never interprets it. | | `required` | boolean | `true` when a request cannot be made without the payload. Absent when false. | A `provider` payload may also ride as the `provider` field of a `thinking` block: an Anthropic thinking block is one block on the wire, with a text part and a signature, and poo keeps the two together. ## `system_prompt` The prompt a run rendered, whole. A prompt that differs from the previous one is written; an unchanged one is not. The record is what a restored session takes: the prompt is never rendered from the sections again, so a session that was recorded under another prompt keeps that prompt. | Field | Type | Meaning | |---|---|---| | `run_id` | string | The run the prompt belongs to. | | `variant` | string | The variant the prompt rendered in. Absent when it rendered in the default one. | | `text` | string | The whole rendered prompt. | | `hash` | string | The hex SHA-256 of the text. | ## `tool.call` A tool call the model made. The record is written before the tool runs, so a log shows what the model asked for even when the tool never finished. | Field | Type | Meaning | |---|---|---| | `run_id` | string | The run the call belongs to. | | `turn` | integer | The turn the call belongs to. | | `handle` | string | The call's handle within the turn, e.g. `"r1"`. | | `tool` | string | The tool the model called. | | `summary` | string | The call's human-facing summary, as the `tool.call` event shows it. A bash call shows the model's `description`, or the command when it supplied none. **Absent** when the tool has no summary, and on a log written before the field existed. | | `arguments` | object or string | The full arguments, in the same shape as a `tool_call` content block. The reserved `background` argument is kept here, even though the core removes it before the tool sees it. | | `mode` | string | How the call ran: `"sync"` in the turn, `"job"` in the background, or `"nested"` from inside another call. Absent when the log was written before the field existed. | | `parent` | string | The handle of the call that made this one, for a call a running tool made through the nested seam. The model-made call a script ran under, so a reader can walk the calls one script made. **Absent** on a call the model made. A nested call that never ran carries the parent and no `mode`, like any other call that did not run. | A nested call's result is recorded but never becomes a `message`: the model never saw the call, and the log's contract — the messages in the log are the same list the model sees — keeps holding. It goes back to the tool that made the call instead, after the same before-tool and after-tool hooks a model-made call goes through. The recovery's message rule leaves a call that names a `parent` out of the history, so a torn tail's nested calls are closed without polluting it either. A nested call's tool runs under a cap of 1,048,576 characters (`poo.NestedOutputCapChars`) and not the session's context-relative caps, since its output never reaches the model directly. The tool that made the call reads the whole result. The record's `text` and the `tool.result` event's `text` are held to the session's observation cap, with the rest counted in `elided_chars`. A cut `text` ends with a line that says how many more characters went to the calling tool. A hook's replaced original is cut the same way. The record's `structured` payload is kept whole, so a tool whose payload holds its output has that output in the log once. Bash's capture always fits under the nested cap. `call_cli`'s stdout and stderr share the cap, so two streams that pass it together are kept as their heads and tails. A tool with no payload, such as read or grep, has only the cut text. ## `tool.result` The outcome of a tool call. | Field | Type | Meaning | |---|---|---| | `run_id` | string | The run the result belongs to. | | `turn` | integer | The turn the result belongs to. | | `handle` | string | The call's handle within the turn. | | `tool` | string | The tool that ran. | | `outcome` | string | `"ok"`, `"error"`, `"denied"`, `"skipped"`, `"cancelled"`, `"interrupted"` or `"started"`. | | `text` | string | The model-facing text of the result. A nested call's text is held to the session's observation cap. | | `elided_chars` | integer | The characters a nested call's `text` left out. Absent when the text is whole. | | `structured` | any | The tool's side-channel payload. Absent when the tool has none. | | `original` | object | The result the tool produced, when a hook replaced it. Absent when no hook replaced it, and absent for a redacted result: the original of a redacted result never reaches the log. | | `redacted` | boolean | `true` when a hook redacted the result. Absent when it did not. | | `redacted_by` | string | The name of the hook that redacted the result. Absent unless the result was redacted. | | `hooks` | array of objects | The after-tool hooks' decisions, in the order the hooks ran. Absent when no hook acted. A redacted chain's decisions carry no `text`. | `original` holds: | Field | Type | Meaning | |---|---|---| | `text` | string | The model-facing text of the result the tool produced. | | `structured` | any | The tool's side-channel payload. Absent when the tool had none. | | `is_error` | boolean | `true` when the result reported a failure. Absent when it did not. | A `hooks` entry holds: | Field | Type | Meaning | |---|---|---| | `hook` | string | The name of the hook that decided. | | `action` | string | What the hook did: `"keep"`, `"annotate"`, `"replace"` or `"redact"`. | | `text` | string | The text the hook added or substituted. Absent when the chain was redacted, and absent when the hook kept the result. | An `error` outcome is recoverable: the model saw the text and the run continued. A bash call that hit its timeout is an `error` outcome, because the model has to see that the command failed rather than read its partial output as a finished command. The `started` outcome belongs to a background job: the call returned at once and its result arrives later as a message. The `denied`, `skipped`, `cancelled` and `interrupted` outcomes arrive with the later stages that produce them. An `interrupted` outcome is written by a load, never by a live run: the call was cut short, its outcome is unknown, and the model is told so. The result is the model-facing text of the call, and the message that carries it answers the call the model made, so a session that is loaded again asks the model nothing it cannot answer. ## `input.queued` An input the session accepted. The record is written before the call that accepted the input returns, so an accepted input is never lost: its fate is in the records. | Field | Type | Meaning | |---|---|---| | `session_id` | string | The session's identifier. | | `run_id` | string | The run the input belongs to. Absent when the session had no run. | | `input_id` | string | The input's identifier: a ULID. | | `mode` | string | How the input is delivered: `"steer"`, `"interrupt"`, `"follow_up"` or `"feed"`. | | `text` | string | The message text. | | `attachments` | array of objects | The files the input carries, each holding `modality`, `media_type` and `data` (base64), so a held input survives a restart with what it carried. Absent when the input carries none. A feed's input carries its image this way. | | `delivery_note` | object | How much of the previous reply the user had seen. Absent when the input carries none. Its `text` is empty when the reply was still streaming at acceptance; the delivered message carries the note rendered at delivery. | | `data` | object | The object a feed's filter wrote beside the text, kept so a held input is still a structured record after a restart. Absent unless a filter produced one. | | `queued_at` | string | RFC 3339, UTC. | ## `input.delivered` An input that reached the model. The `message` that delivers the input is the delivery's commit point: once that record is in the log the input has reached the model, and a store that refuses this record does not undo the delivery. The load writes the missing record from the message. | Field | Type | Meaning | |---|---|---| | `session_id` | string | The session's identifier. | | `run_id` | string | The run the input was delivered to. | | `input_id` | string | The input's identifier: a ULID. | | `mode` | string | How the input was delivered: `"steer"`, `"interrupt"`, `"follow_up"`, `"job"` for a background job's result, or `"feed"` for a feed's input. | | `delivered_at` | string | RFC 3339, UTC. | ## `input.dropped` An input that never reached the model. The reason is the run's final settle reason, or `backlog` when the feed's backlog cap dropped the input with no run involved. | Field | Type | Meaning | |---|---|---| | `session_id` | string | The session's identifier. | | `run_id` | string | The run the input belonged to. Absent when the session had no run. | | `input_id` | string | The input's identifier: a ULID. | | `mode` | string | How the input was accepted. | | `reason` | string | Why the input was dropped. | | `dropped_at` | string | RFC 3339, UTC. | ## `input.held` Job results that were held instead of delivered. A held result waits for the next run, or for the next load: it is never lost. | Field | Type | Meaning | |---|---|---| | `session_id` | string | The session's identifier. | | `run_id` | string | The run the results were held for. Absent when the session had no run. | | `jobs` | array of strings | The jobs whose results were held, or the feeds whose inputs were held. A feed's entry is its origin, e.g. `"feed:inbox"`. | | `reason` | string | Why they were held: `"on_idle"`, `"wake_limit"` or `"session_closed"`. | | `held_at` | string | RFC 3339, UTC. | ## `job.started` A background job was accepted and started. The record is the acceptance: the job, the call it came from, the run that started it and the tool it runs. | Field | Type | Meaning | |---|---|---| | `session_id` | string | The session's identifier. | | `job` | string | The job's identifier, e.g. `"j3"`. | | `handle` | string | The handle of the tool call the job came from, e.g. `"r1"`. The call returned at once with a `"started"` outcome. | | `tool` | string | The name of the tool the job runs. | | `run_id` | string | The run that started the job. | | `started_at` | string | RFC 3339, UTC. | ## `job.ended` A background job finished. The record carries the result the model reads, so a held result survives a crash and a load can deliver it. | Field | Type | Meaning | |---|---|---| | `session_id` | string | The session's identifier. | | `job` | string | The job's identifier, e.g. `"j3"`. | | `handle` | string | The handle of the tool call the job came from. | | `tool` | string | The name of the tool the job ran. | | `run_id` | string | The run that started the job. | | `outcome` | string | How the job ended: `"ok"`, `"error"`, `"cancelled"` or `"interrupted"`. | | `cause` | string | Why the job ended, when something else ended it. Absent unless the cause is `"session_closed"`. | | `timed_out` | boolean | `true` when the job hit the jobs timeout. Absent when it did not. | | `fatal` | boolean | `true` when the job failed with a fatal error. A run that receives the result settles `tool_fatal`. Absent when the job did not. | | `input_id` | string | The id the queued result is delivered under. | | `text` | string | The result the model reads. | | `attachments` | array of objects | The files the result carries, each holding `modality`, `media_type` and `data` (base64), so a held result survives a restart with what it carried. Absent when the result carries none. An earlier build wrote this field as `images`, holding only `media_type` and `data`; a reader takes those as images. | | `ended_at` | string | RFC 3339, UTC. | ## `feed.started` One attempt of a feed started. A feed is a long-lived source that pushes messages into a session, and the session owns its lifecycle: this record names the attempt. One instance's attempts never overlap, so the attempt's end is the next `feed.ended` of the same origin. The `origin` is the instance's: the feed's own `"feed:"`, or `"feed:[=]"` for an instance the model started with `subscribe_feed`. | Field | Type | Meaning | |---|---|---| | `session_id` | string | The session's identifier. | | `feed` | string | The feed's name, e.g. `"inbox"`. The `origin` names the instance. | | `attempt` | integer | The attempt's number within the session and the instance, counting from 1. A loaded session carries on past the numbers the log holds, except an optional feed a subscription started: a restored session holds no optional instances, so a re-subscribed one restarts at attempt 1. | | `started_at` | string | RFC 3339, UTC. | ## `feed.ended` One attempt of a feed ended. The record is terminal: the attempt is never resumed, and a feed's failure reaches the model through the record and the event, never as a message. A loaded session starts the feed's next attempt under the next number, and a subscription's instance does not start again on its own. | Field | Type | Meaning | |---|---|---| | `session_id` | string | The session's identifier. | | `feed` | string | The feed's name. | | `attempt` | integer | The attempt's number within the session. | | `outcome` | string | How the attempt ended: `"exited"`, `"failed"`, `"cancelled"`, `"suspended"`, `"session_closed"` or `"interrupted"`. | | `error` | string | The runner's error, when it returned one. Absent when it did not. | | `restart_in_ms` | integer | How long the session waits before the next attempt, in whole milliseconds, rounded up. Absent when no restart is scheduled. | | `ended_at` | string | RFC 3339, UTC. | `exited` means the runner returned without an error, and `failed` means it returned an error or panicked. `cancelled` means `cancel_job` stopped the attempt, and `session_closed` means the session closed under it, or its store broke. `interrupted` is written by a load, never by a live session: the process stopped during the attempt. `suspended` means the feed's filter failed closed: the filter exited nonzero, or wrote something other than a record, so the attempt ended and the feed did not restart, whatever its restart policy says. The `error` names the fault. A suspension wakes the session with a `feed` input of its own, and that input is the report of how the feed went down. Its text is the feed's `` element with `fault` and `log` attributes beside `name`: the fault's code, and the path of a file beside the session's own that holds the filter's diagnostics for the attempt. Those diagnostics never ride the input. One suspension is one wake: a further fault that arrives before the report is delivered joins it, and the report counts it. ## `tool.started` A side-effecting tool call started. The record is written before the tool runs, so a durable session sees the effect a crash cut short and may replay it. A read-only call writes none: it changes nothing to replay. | Field | Type | Meaning | |---|---|---| | `run_id` | string | The run the call belongs to. | | `turn` | integer | The turn the call belongs to. | | `handle` | string | The call's handle within the turn, e.g. `"r1"`. | | `call_id` | string | The provider's id of the call. The id the call answers, so a reader pairs the start with the call and the result by it. | | `tool` | string | The name of the tool the call names. | ## `run.resumed` A run resumed after a crash. The record names the phase the run stopped in, so a reader of the log sees where the run picked up. | Field | Type | Meaning | |---|---|---| | `run_id` | string | The run that resumed. | | `resumption_attempt` | integer | The resumption's number, counting from 1. | | `from_phase` | string | The phase the run was in when it stopped: one of the session's states, e.g. `"executing"`. | | `turn` | integer | The turn the run was in when it stopped. | ## `turn.hook` A turn hook's start or end. The record is written when the hook starts and when it ends, so a reader of the log sees a hook that a crash cut short: its start has no end, and its end may say it was interrupted. | Field | Type | Meaning | |---|---|---| | `run_id` | string | The run the hook belongs to. | | `turn` | integer | The turn the hook runs in. | | `phase` | string | The hook's phase: `"after_turn"` or `"before_settle"`. | | `status` | string | The record's status: `"started"`, `"ended"`, or `"skipped"` for a hook a resumed turn left out because it is not safe to run twice. | | `hook_index` | integer | The hook's position in the chain, counting from 0. | | `interrupted` | boolean | `true` when the hook's turn was ended by an interrupt. Set on the hook's records along the interrupted path, so a crash between them keeps the fact on the started record. Absent when it was not. | ## `feed.subscribed` A feed instance subscribed. The record is written before the instance runs, so a reader of the log sees the instances a session ran, and a durable session knows which to take on again and the scope and prompt to take them on with. A call that sets a prompt on a running instance writes the record again, so the last one is the subscription the session would repeat. | Field | Type | Meaning | |---|---|---| | `feed` | string | The feed's name, e.g. `"inbox"`. | | `instance` | string | The instance's identifier. | | `scope` | string | The instance's scope. | | `prompt` | string | The prompt the instance was started with. Absent when the instance was started without one. | ## `feed.unsubscribed` A feed instance unsubscribed. The record is written when the instance unsubscribes, so a reader of the log sees the instances a session let go, and a durable session does not take them on again. | Field | Type | Meaning | |---|---|---| | `feed` | string | The feed's name, e.g. `"inbox"`. | | `instance` | string | The instance's identifier. | ## `observer.dropped` The events an observer missed. The record is written at most once a second per observer, so an observer that fell behind does not flood the log, and it is never delivered to an observer: the diagnostics must not cause more overflow. | Field | Type | Meaning | |---|---|---| | `session_id` | string | The session's identifier. | | `observer` | string | The observer that fell behind. | | `count` | integer | How many events the observer missed. | | `dropped_at` | string | RFC 3339, UTC. | ## `turn.interrupted` A turn an interrupt cut short. The record follows the turn's end: a client reads it as a note on the turn that just closed. | Field | Type | Meaning | |---|---|---| | `session_id` | string | The session's identifier. | | `run_id` | string | The run the turn belongs to. | | `turn` | integer | The turn that was interrupted. | | `input_ids` | array of strings | The inputs whose messages aborted the turn. | | `interrupted_at` | string | RFC 3339, UTC. | ## `compaction` What a compactor did. The store keeps every original record, and the compaction record says what the model's view was replaced with. | Field | Type | Meaning | |---|---|---| | `run_id` | string | The run the compaction belongs to. | | `strategy` | string | The strategy that produced the compaction. | | `compaction` | object | The compaction itself. Its shape is the strategy's form: `replace`, `rewrite`, `window` or `end`. | ## `usage` The token accounting of one provider request. Every request whose stream started gets a record, so a consumer can see the time to the first token even when the endpoint reports no token counts. | Field | Type | Meaning | |---|---|---| | `run_id` | string | The run the request belongs to. | | `turn` | integer | The turn the request belongs to. | | `request` | integer | The request's number within the run, starting at 1. `0` for a request a compaction made, which is not one of the run's turns. | | `input_tokens` | integer | The prompt tokens the endpoint reported. `0` when it reported none. | | `output_tokens` | integer | The completion tokens the endpoint reported. `0` when it reported none. | | `cache_read_tokens` | integer | The prompt tokens served from the provider's cache. **Absent** when the endpoint does not report it. | | `ttft_ms` | number | The time to the first streamed token, in milliseconds. Measured by the transport, not reported by the endpoint. | | `origin` | string | Absent for the run's own turn. `compaction` when a compaction strategy made the request: a fork that wrote a handoff, or the request that wrote a summary. | The time to the first token is the time to the first *token*: a non-empty text delta, a thinking delta or a tool call. A chunk that only announces the assistant's role carries no token, so it does not start the clock. Every provider request whose stream started gets a `usage` record, including a request whose stream failed part way through: the request still cost tokens, and the record is what a consumer reads to account for it. That includes the requests a compaction made, which carry the compaction's origin so their share of the spend stays its own. A request that failed before the endpoint's stream started has no usage record: no token was spent on it. An endpoint that reports no usage for a request writes no record either: the charge is an estimate, and the log holds what the endpoint said. ## `provider.attempt` One attempt of a provider request that failed. Every attempt is written, the last one included, so a reader of the log sees what the request tried and what each attempt failed with. | Field | Type | Meaning | |---|---|---| | `run_id` | string | The run the request belongs to. | | `turn` | integer | The turn the request belongs to. | | `request` | integer | The request's number within the run, starting at 1. Every attempt record belongs to a turn's request. | | `attempt` | integer | The attempt's number, counting from 1. | | `error` | string | The failure's message. | | `kind` | string | The provider error kind, when the failure is one. **Absent** when it is not. | | `delay_ms` | integer | How long the transport waited before the next attempt. **Absent** when no retry followed. | ## `session.models_changed` The session switched models. The switch happens between the runs, so a reader of the log knows which model answered which turn. | Field | Type | Meaning | |---|---|---| | `from` | string | The name of the model the session talked to. | | `to` | string | The name of the model the session talks to now. | | `warnings` | array of strings | What the caller should know about the switch. **Absent** when there was nothing to say. | | `omitted` | array of objects | The provider blocks that are left out of the requests from now on, because they belong to another API. Each object holds `api`, `type` and `count`. **Absent** when nothing was left out. | The history is never truncated by a switch. A view that does not fit the new window is a warning, and the next run settles `context_exhausted`. ## `model.output_limit` The session learned a model's output cap from an endpoint that rejected a request whose `max_tokens` was above it. The session keeps the cap for the requests that follow, and the record says why the value dropped. | Field | Type | Meaning | |---|---|---| | `model_id` | string | The identifier of the model the endpoint rejected. | | `previous` | integer | The `max_tokens` the rejected request asked for. | | `limit` | integer | The `max_tokens` the endpoint accepts, which the session asks for from now on. | A restored session applies the last record for the model it talks to, unless that model declares its own limit. ## `decision` One decision call. The record is written whatever the outcome was, so a reader of the log sees the calls that could not be answered too. | Field | Type | Meaning | |---|---|---| | `origin` | string | Who asked the questions. | | `questions` | array of objects | The questions that were asked. Each holds `id`, `instructions` and its kind's own fields. | | `state_hash` | string | The hex SHA-256 of the state payload the questions were asked about. | | `answers` | array of objects | The answers, when the call succeeded. **Absent** when it did not. | | `outcome` | string | `"ok"`, `"deferred"` or `"invalid"`. | | `error` | string | The failure, when the call did not succeed. **Absent** when it did. | | `latency_ms` | number | How long the call took, in milliseconds. | | `requests` | integer | The number of wire requests the call made. **Absent** when the decider did not report one. | | `at` | string | RFC 3339, UTC. | ## `permission.asked` The ask a run is waiting on. The record is written when the run starts waiting, before any asker has answered. | Field | Type | Meaning | |---|---|---| | `run_id` | string | The run that is waiting. | | `ask_id` | string | The ask's identifier. A client answers by it. | | `tool` | string | The name of the tool the model called. | | `summary` | string | What the call does, as the permission ask shows it. A bash call shows the command, never the model's `description`. **Absent** when the tool has no summary. | | `class` | string | The tool's class: `"read_only"` or `"side_effecting"`. **Absent** when the tool names none. | | `reason` | string | Why the call is being asked about: `"policy"` or `"doom_loop"`. **Absent** when there is none. | | `repeat_count` | object | The doom loop's counts, for a doom-loop ask: `exact` and `near`. **Absent** for a policy ask. | | `deadline` | string | The wall-clock time, RFC 3339 with nanosecond precision, when the ask expires. **Absent** when the ask has no deadline, and on a log written before the field existed. | | `fallback` | string | The decision an expired ask resolves to: `"allow"` or `"deny"`. It is the request's effective fallback, so an ask that names none resolves to `"deny"`. **Absent** on a log written before the field existed. | ## `permission.answered` The answer that resolved an ask. It follows its `permission.asked`, and it is written whatever the decision was. | Field | Type | Meaning | |---|---|---| | `run_id` | string | The run the answer belongs to. | | `ask_id` | string | The ask the answer resolves. **Absent** for a doom loop's deterministic action, which answers no ask. | | `decision` | string | `"allow"` or `"deny"`. | | `answered_by` | string | Who answered: an asker, the chain's fallback, the policy's own action, or `"cancelled"` for a run that ended. | | `provenance` | string | How the ask was resolved: `"answered"`, `"timeout"`, `"default"`, `"no_asker"`, `"cancelled"` or `"interrupted"`. | | `reason` | string | Why the call was being asked about. **Absent** when there is none. | | `message` | string | The note the answer carried for the model. For a policy ask the model saw it in the refused call's tool result; for a doom-loop ask the model sees the doom loop's own refusal text instead, and the record keeps the message. **Absent** when the answer carried none. | ## `run.settled` The end of a run. It is the last record of a run. | Field | Type | Meaning | |---|---|---| | `run_id` | string | The run's identifier: a ULID (26 characters of Crockford base32, the time first). | | `reason` | string | The settle reason. See below. | | `detail` | object | Why the run settled. | | `turns` | integer | The number of provider requests the run made. | | `settled_at` | string | RFC 3339, UTC. | `detail` holds: | Field | Type | Meaning | |---|---|---| | `source` | string | The condition that settled the run. | | `text` | string | The human-readable explanation. Absent when there is none. | | `losing` | array of strings | Other candidates that lost the precedence order. Absent when there were none. | | `provider` | object | Set when a provider request failed. | | `handoff` | string | The note a compactor wrote when it refused to compact. Absent when the run did not settle that way. | | `undelivered_input` | array of objects | The accepted inputs that never reached the model. Absent when there were none. | | `jobs_running` | array of strings | The jobs that were still running when the run settled. Absent when there were none. | | `result` | any | The payload of a valid `finish` call, when the run settled as finished. Absent otherwise. | | `usage` | object | The run's token accounting: the sum of what its requests reported. Absent when no request reported usage. | A `usage` entry holds: | Field | Type | Meaning | |---|---|---| | `input_tokens` | integer | The prompt tokens the requests reported, in total. | | `output_tokens` | integer | The completion tokens the requests reported, in total. | | `cache_read_tokens` | integer | The prompt tokens the providers served from their caches, in total. Absent when no request reported one. | A `undelivered_input` entry holds: | Field | Type | Meaning | |---|---|---| | `input_id` | string | The input's identifier: a ULID. | | `mode` | string | How the input was accepted: `"steer"`, `"interrupt"` or `"follow_up"`. | `provider` holds: | Field | Type | Meaning | |---|---|---| | `kind` | string | The failure class, e.g. `"context_length"` or `"server"`. | | `status` | integer | The HTTP status. Absent when the failure was not a response. | | `code` | string | The provider's own error code. Absent when it sent none. It also holds the kind a failure had before it was reclassified: an `interrupted_stream` keeps the kind it broke in here. | | `retry_after_s` | integer | How long the endpoint asked the client to wait, in seconds. Absent when it said nothing. | ### Settle reasons The reasons are a closed set, and the exit code is the process's exit code. The precedence is the order of the table: a run collects a candidate from every source, and the highest-precedence one wins at the commit point. | Precedence | Reason | Exit | Meaning | |---|---|---|---| | 1 | `cancelled` | 130 | The run was cancelled. | | 2 | `store_error` | 23 | The session's store failed. The session becomes broken. | | 3 | `hook_error` | 22 | An executable hook failed or missed its deadline. | | 4 | `tool_fatal` | 21 | A tool failed with an error that means the environment is unusable. | | 5 | `provider_limit` | 24 | The provider refused for quota or plan reasons. The session is not broken. | | 5b | `provider_error` | 20 | A provider request failed and cannot be retried, or the retry budget was spent. | | 6 | `context_exhausted` | 13 | The context window is full. | | 7 | `hook_continue_limit` | 12 | The `BeforeSettle` hooks asked for more continuations than the run allows. | | 8 | `max_turns` | 11 | The run hit its turn limit. | | 8b | `budget_exhausted` | 14 | The run hit a token or time budget. | | 8c | `invalid_turns` | 15 | The model kept producing turns the run could not use: it asked for tool calls and sent none, or its calls did not parse, for as many consecutive turns as the run allows. | | 9 | `finished` | 0 | The model called the `finish` tool with a valid result. | | 9b | `stop_requested` | 0 | A hook or a stop condition asked the run to stop. | | 10 | `output_truncated` | 10 | The provider stopped on the output-token limit. | | 11 | `end_turn` | 0 | The model stopped on its own. | | — | `interrupted` | — | The run's outcome is unknown: the process stopped while the run was going. It is never produced live; a load writes it for a run that never settled. | `provider_limit` and `provider_error` share a precedence level, because a single failed request produces only one of them. A cancellation and a deadline are the same outcome: the run was stopped before the model finished, and both settle `cancelled`. `detail.source` names the condition. The values the core writes: | Source | Meaning | |---|---| | `end_turn` | The model stopped on its own. | | `output_truncated:default` | The provider stopped on the output-token limit, and the request carried poo's default for the model's context window, because the model declares no `max_output`. The detail's text names the `max_tokens` the request carried and the setting that raises it. | | `output_truncated:model` | The provider stopped on the output-token limit, and the request carried the model's own `max_output`. | | `output_truncated:context` | The provider stopped on the output-token limit, and the request carried the room the context window had left, which was under the model's output limit. The detail's text gives the estimated prompt size and the window. | | `output_truncated:endpoint` | The provider stopped on the endpoint's own output limit: the request body carried no `max_tokens`, because the endpoint takes none. | | `max_turns` | The run hit its turn limit. | | `max_run_tokens` | The run hit its token budget. | | `max_duration` | The run hit its wall-clock budget. | | `empty_turns` | The model reached the bound on consecutive turns that asked for tool calls and sent none. The detail's text says how many turns. A run that mixed the two kinds of unusable turn is named for its last turn. | | `unparsed_calls` | The model reached the bound on consecutive turns whose tool calls did not parse. The detail's text says how many turns. A run that mixed the two kinds of unusable turn is named for its last turn. | | `truncated_turns` | The model reached the bound on consecutive turns whose response stopped on the output-token limit before a complete call arrived, with `limits.truncation_retries` retries already spent. The detail's text says how many turns. | | `no_output_room` | The computed `max_tokens` was under 256, so the request was never sent. | | `prompt_limit` | The estimate plus the reserve was over the endpoint's input cap, so the request was never sent. | | `compaction_failed` | The compactor failed when the next request could not go out. | | `provider:context_length` | The endpoint reported that the request was too long. It is recognised whatever status the endpoint sent it with, including a 5xx. The run compacts once and sends the request again when it has a compactor, the refused request carried no partial answer, and no interrupt is pending. A handoff strategy forks the refused request, which fails, so the run settles with the refusal. Without those conditions the run settles as before. | | `provider:` | The provider request failed with that kind. | | `finish` | The model called the `finish` tool with a valid result. | | `before_settle` | A `BeforeSettle` hook stopped the run, or the run asked for more continuations than it allows. | | `after_turn:` | An `AfterTurn` hook stopped the run. | | `stop_condition` | A stop condition matched. | | `cancel:context` | The run's context was cancelled. | | `cancel:deadline` | The run's context deadline passed. | | `cancel:client` | The client cancelled the run. | | `cancel:close` | The session closed while the run was active. | | `store` | The session's store refused a record. | ## Reading a log A consumer reads the file line by line and decodes each line as a JSON object. It keys off `record`, and it must tolerate fields it does not recognise: a later stage adds records and fields, and a consumer that fails on an unknown field breaks on a newer log. A log written by an earlier core is still readable. The fields added after the first version are all optional: `message_id`, `input_id`, `delivery_note` and `trigger` are absent from an older log, and a consumer that needs them must treat an absent field as "the log does not say". The order of the records is the order of the events. A `tool.call` is always followed by its `tool.result`, and a `run.started` is always followed by a `run.settled`. One feed instance's attempts never overlap, so a `feed.started` is followed by its `feed.ended` before that instance's next `feed.started`. The core writes the settle record itself, so a run that was cancelled, or whose provider failed, still ends with one. Every record is written under a context of its own, bounded at 5 s, so a cancelled run still records what it did. A `usage` record the store refuses is dropped rather than ending the run. Only a store that refuses the run's other records stops it before its `run.settled`. ## The tools' observations A `tool.result` carries the tool's own text in `text`, and the tool's side-channel payload in `structured`. The two tools the skeleton ships have these shapes. The bash tool's payload is the observation the model reads, as JSON: | Field | Type | Meaning | |---|---|---| | `returncode` | integer or null | The command's exit status. Null when the process was killed, which is the case for a timeout. | | `timed_out` | boolean | Whether the command hit its timeout. | | `output` | string | The output, when it fits under the observation cap. | | `output_head` | string | The head of the output, when it was elided. | | `output_tail` | string | The tail of the output, when it was elided. | | `elided_chars` | integer | The characters dropped from the middle. Absent when the output was not elided. | | `truncated` | boolean | True when the output passed the 1 MiB capture and the rest was dropped. Absent otherwise. | | `hint` | string | How to see the elided middle, or the dropped end when `truncated` is set. Absent when the output was neither elided nor truncated. | The observation cap and `elided_chars` are counted in characters, not bytes, and a cut never splits a rune. A byte that is not part of a valid character counts as one character. The output is captured up to 1 MiB, and a capture cut that lands in the middle of a character drops the partial one. Bytes the command printed are otherwise kept as they are. The read tool's payload is the range the model saw. Its text carries a header naming the range, such as `[path · lines 1–2000 of 5312]`, and the body below it. The header says `· capped` when the output cap ended the read early, and names an empty range when the offset is past the end of the file. A line is truncated at 2000 characters, counted in characters, and a cut never splits a rune. A carriage return at the end of a line is stripped, so a file with CRLF endings reads the same as one with LF endings. --- # Wire API mapping A paper round-trip through poo's internal message model, for the three wire APIs the model has to survive: **Chat Completions**, **OpenAI Responses (stateless)** and **Anthropic Messages**. The question every row answers is the same one: if a provider sends a piece of content, does poo's internal model hold it, and can poo put it back on the wire unchanged? The answer decides what the model has to carry. The model is frozen after this document, so a gap found here is a gap fixed here. ## How to read the tables - **Wire** is the JSON the API sees. Ellipses stand for the payload. - **Internal** is poo's own shape, in the shorthand of the Go types (`Message{Role:user, Origin:user, Content:[text]}`). - **Back** is what poo puts on the wire when it replays the same history. - **Lossless** says whether `wire → internal → wire` keeps the meaning. It does not mean byte-for-byte: JSON whitespace and key order are not part of the meaning, but a value the API treats as opaque **is** part of it. The internal model is: ```go type Message struct { Role Role Content []ContentBlock ID string // "m", session-monotonic Origin Origin // "user", "model", "job", "system", ... DeliveryNote *DeliveryNote // what the user had seen of the last reply } type ContentBlock struct { Kind ContentKind // text | thinking | tool_call | tool_result | provider Text string ToolCallID string Name string Arguments json.RawMessage IsError bool Provider *ProviderBlock // opaque provider data } type ProviderBlock struct { API API // chat_completions | responses | anthropic_messages Type string // the provider's own name for the payload Data json.RawMessage // the payload, verbatim Required bool // the request fails without it } ``` A `ProviderBlock` is the plan's first-class opaque block. It rides either alone (a `provider` content block) or as the companion of a visible block (a thinking block's signature). ## Chat Completions `POST /v1/chat/completions`. The API poo v1 ships. | # | Wire | Internal | Back | Lossless | |---|---|---|---|---| | C1 | `{"role":"system","content":"…"}` | `Message{Role:system, Origin:system, Content:[text]}` | the same message | **yes** | | C2 | `{"role":"user","content":"…"}` | `Message{Role:user, Origin:user, Content:[text]}` | the same message | **yes** | | C3 | `{"role":"assistant","content":"…"}` | `Message{Role:assistant, Origin:model, ID:"m3", Content:[text]}` | the same message, without the id | **yes** — the id is poo's, not the API's | | C4 | `{"role":"assistant","content":null,"tool_calls":[{"id":"call_1","type":"function","function":{"name":"bash","arguments":"{\"command\":\"ls\"}"}}]}` | `Content{kind:tool_call, tool_call_id:"call_1", name:"bash", arguments:{"command":"ls"}}` | the same call, with the arguments re-encoded as a JSON string | **yes, in value** — the wire carries the arguments as a *string*; poo holds the parsed value, so whitespace inside that string is not preserved | | C5 | `{"role":"tool","tool_call_id":"call_1","content":"out"}` | `Message{Role:tool, Origin:tool, Content:[{kind:tool_result, tool_call_id:"call_1", name:"bash", text:"out"}]}` | the same message | **yes**, except the two fields the wire has no room for: the tool's `name` (read back from the matching call) and `is_error` (conveyed in the text) | | C6 | `delta.reasoning_content` (a server extension, not in the spec) | `Content{kind:thinking, text}` | dropped | **no** — Chat Completions has no field that carries thinking back. The model keeps the thinking in the view; the request loses it. | | C7 | `delta.tool_calls[]` fragments | `Content{kind:tool_call}` | reassembled | **yes** | | C8 | `usage.prompt_tokens`, `usage.completion_tokens`, `usage.prompt_tokens_details.cached_tokens` | `UsageReport{InputTokens, OutputTokens, CacheReadTokens}` | — (response side) | **yes** | | C9 | `finish_reason: "stop"|"length"|"tool_calls"` | `FinishReason` | the same | **yes** | | C10 | `tools[].function.{name,description,parameters}` | `ToolSpec{Name, Description, Schema}` | the same | **yes** | | C11 | `{"role":"assistant","content":null,"refusal":"…"}` — a refusal is a **top-level string** on the message, not a content part | `Content{kind:text}` | a plain string | **no** — see *Scope decisions* | Two asymmetries are worth naming because they are properties of the API, not of poo's model: - **Thinking does not survive the request.** `reasoning_content` is an extension many servers send and no server accepts back. A history that carries thinking is a history the endpoint never sees again. - **A tool result carries no error flag.** Chat Completions has no `is_error` on a tool message: the failure is in the text the model reads. poo keeps `is_error` in its own record and in the model's view, because Anthropic has a field for it and the two APIs should not behave differently inside poo. ## OpenAI Responses (stateless) `POST /v1/responses`, with no `previous_response_id` and no `store`: every request carries the whole history, which is poo's rule. | # | Wire | Internal | Back | Lossless | |---|---|---|---|---| | R1 | `{"type":"message","role":"user","content":[{"type":"input_text","text":"…"}]}` | `Message{Role:user, Origin:user, Content:[text]}` | a message item with `input_text` | **yes** | | R2 | `{"type":"message","role":"assistant","content":[{"type":"output_text","text":"…"}]}` | `Message{Role:assistant, Origin:model, Content:[text]}` | a message item with `output_text` | **yes** | | R3 | `{"type":"function_call","call_id":"call_1","name":"bash","arguments":"{\"command\":\"ls\"}"}` | `Content{kind:tool_call, tool_call_id:"call_1", name:"bash", arguments:{"command":"ls"}}` | its own item, arguments re-encoded as a string | **yes, in value** | | R4 | `{"type":"function_call_output","call_id":"call_1","output":"…"}` | `Content{kind:tool_result, tool_call_id:"call_1", text:"…"}` | its own item | **yes** | | R5 | `{"type":"reasoning","id":"rs_1","summary":[{"type":"summary_text","text":"…"}],"encrypted_content":"…"}` | `Content{kind:thinking, text:"…", provider:{api:responses, type:"reasoning", data:{"id":"rs_1","encrypted_content":"…"}}}` | one reasoning item again: the summary from the thinking text, the id and the encrypted content from the provider block | **in the summary shape** — the encrypted content is opaque and travels back untouched, and the summary's text survives. The *part* boundaries do not: the thinking is one string, so a summary of several parts comes back as one part. See *Where this document is not sure*. | | R6 | a compaction item (an opaque item the provider's own compaction produced) | `Content{kind:provider, provider:{api:responses, type:"compaction", data:, required:true}}` | the same item, verbatim | **yes** — the payload is never interpreted, only carried | | R7 | `instructions` (the system prompt) | `Message{Role:system, Origin:system, Content:[text]}` | the `instructions` field | **yes, in content** — the field's shape differs, the prompt does not | | R8 | `usage.input_tokens`, `usage.output_tokens`, `usage.input_tokens_details.cached_tokens` | `UsageReport` | — (response side) | **yes** | | R9 | `max_output_tokens` | `ChatRequest.MaxTokens` | the same | **yes** | | R10 | `{"type":"message","role":"assistant","content":[{"type":"refusal","refusal":"…"}]}` — a refusal is a **content part** here, unlike Chat Completions | `Content{kind:text}` | a plain string | **no** — see *Scope decisions* | The structural difference from Chat Completions is that a function call and its output are **top-level items**, not messages. poo's model keeps a tool call as a block of the assistant message, so the transport splits one assistant message into a message item plus one item per call, in order. The order is preserved, because the API matches a call to its output by position as well as by id. ## Anthropic Messages `POST /v1/messages`. | # | Wire | Internal | Back | Lossless | |---|---|---|---|---| | A1 | `system` (a string or a list of blocks) | `Message{Role:system, Origin:system, Content:[text]}` | the `system` field | **yes, in content** | | A2 | `{"role":"user","content":[{"type":"text","text":"…"}]}` | `Message{Role:user, Origin:user, Content:[text]}` | the same | **yes** | | A3 | `{"role":"assistant","content":[{"type":"text","text":"…"}]}` | `Message{Role:assistant, Origin:model, Content:[text]}` | the same | **yes** | | A4 | `{"type":"tool_use","id":"toolu_1","name":"bash","input":{"command":"ls"}}` | `Content{kind:tool_call, tool_call_id:"toolu_1", name:"bash", arguments:{"command":"ls"}}` | the same block | **yes** — the input is a JSON *object* here, not a string | | A5 | `{"type":"tool_result","tool_use_id":"toolu_1","content":"…","is_error":false}` | `Content{kind:tool_result, tool_call_id:"toolu_1", text:"…", is_error:false}` | the same block | **yes** — the tool's name is not on the wire, and poo does not need it there | | A6 | `{"type":"thinking","thinking":"…","signature":"sig"}` | `Content{kind:thinking, text:"…", provider:{api:anthropic_messages, type:"thinking_signature", data:"\"sig\""}}` | one thinking block again: the text from the block, the signature from the provider block | **yes** — the signature is opaque and must travel back untouched | | A7 | `{"type":"redacted_thinking","data":"…"}` | `Content{kind:provider, provider:{api:anthropic_messages, type:"redacted_thinking", data:"\"…\""}}` | the same block, verbatim | **yes** | | A8 | `stop_reason: "end_turn"|"max_tokens"|"tool_use"` | `FinishReason` | the same, mapped | **yes** | | A9 | `usage.input_tokens`, `usage.output_tokens`, `usage.cache_read_input_tokens`, `usage.cache_creation_input_tokens` | `UsageReport{InputTokens, OutputTokens, CacheReadTokens}` | — (response side) | **yes**, except the cache *write* count, which the plan's usage record has no field for. See *Scope decisions*. | Two placement rules belong to the API, and a transport has to honour them: - A tool result lives in a **user** message, not in one of its own. poo keeps tool results in their own message with `role: tool`; the transport merges them into the user message that follows the assistant's `tool_use`. - Thinking blocks come **first** in an assistant message. poo preserves block order, so the transport keeps the order and the rule holds. ## Gaps this round trip found, and how they are closed 1. **Opaque provider data had nowhere to go.** Anthropic's thinking signature, Anthropic's redacted thinking, the Responses reasoning item's encrypted content and the Responses compaction item are all values the model must hold without interpreting them, and must give back unchanged. *Closed:* `ProviderBlock{api, type, data, required}` is a first-class block. It rides alone as a `provider` content block, or as the companion of a visible block (a thinking block's signature). 2. **A visible block needed room for an invisible companion.** The Anthropic thinking block is one block on the wire and two facts in poo: the thinking text and the signature. Splitting it into two blocks would break the "one thinking block" shape the API expects. *Closed:* a content block carries an optional `Provider` companion. The transport merges the two back into the API's own block. 3. **Messages had no id.** The plan's delivery note names an assistant message, and the message id is what the note refers to. *Closed:* `Message.ID` holds a session-monotonic `m`, and `poo.MessageIDs` hands them out. The counter belongs to the session, so a second run's ids continue where the first run's stopped. 4. **Messages had no origin.** A user message can come from a person, a steer, an interrupt, a follow-up, a job or a hook, and the model and the log both need to know which. *Closed:* `Message.Origin`, with the plan's values. 5. **A user message had nowhere to put a delivery note.** The note is rendered when the input is delivered, prefixed to the message's text, and must survive to the record, so replay is exact. *Closed:* `Message.DeliveryNote{message_id, upto_chars, text}`. 6. **A tool result's tool name and error flag have no home on one of the APIs.** Chat Completions' tool message carries neither. *Closed:* this is not a model gap. poo holds both, the transport sends what the API accepts, and the difference is recorded in the mapping above rather than worked around in the model. ## Scope decisions These are deliberate, and they are not gaps in the model: - **Refusal parts** are not represented. The two APIs differ in where a refusal lives: the Responses API sends it as a `refusal` content part (`{"type":"refusal","refusal":"…"}`), and Chat Completions sends it as a top-level `message.refusal` string next to the content. v1 ships one transport, the plan's block list does not name refusal, and a refusal is only distinguishable by the message's shape — a shape the OpenAI-compatible servers v1 targets do not all accept. The refusal text is kept as a text block, so nothing the model said is lost; what is lost is the *label*. - **An attachment a tool returns** — an image or a recording — is carried as its own block, and its place on the wire belongs to the API. Chat Completions takes one only in a user message, so this transport sends the tool message and then a user message carrying the parts: `image_url` for an image, and `input_audio` with the base64 and a `wav` or `mp3` format for audio. No Responses or Messages transport ships here; when one does, its own field takes the block without the extra message, since the Responses API names `input_image` and `input_audio` inside the tool result's output. The Messages API has no audio block, so a Messages transport carries images and refuses audio. - **The cache-write token count** (Anthropic's `cache_creation_input_tokens`) has no field: the plan's usage record names `input_tokens`, `output_tokens`, `cache_read_tokens` and `ttft_ms`, and this stage adds no field to that vocabulary. - **A foreign API's opaque block** is omitted from a request when it is not required, and fails the request with `session_incompatible` when it is. The rule needs no model change: the block says which API it belongs to. ## Where this document is not sure Stated plainly, because a wrong detail in a mapping is a bug that waits for the transport that implements it: - **The Responses compaction item.** The API has a compaction endpoint that returns a compacted item set including a compaction item with encrypted content. The exact field names of that item are not pinned here. The model does not care: the item is carried verbatim in a `provider` block, and the transport that implements the endpoint is the only thing that has to know its shape. - **The Responses reasoning item's `summary` versus `content`.** A reasoning item carries either a `summary` (a list of `summary_text` parts) or `content` (a list of `reasoning_text` parts), and the two hold different things: the summary is the model's own account of its reasoning, and the content is the reasoning itself. poo's model has one thinking string, so the *text* survives in either shape but the *part boundaries* do not, and an item whose reasoning arrived as `content` cannot be told from one whose summary said the same words. The transport that implements the Responses API must decide how the two shapes map onto the one block; the model does not depend on the answer, because the opaque `encrypted_content` is carried verbatim either way. - **Whether the Responses API accepts a `system`-role message item.** The documented way to send a system prompt is the top-level `instructions` field, and that is what the mapping uses. A system-role item is not assumed to work. - **Anthropic's exact ordering rule for thinking blocks.** The rule used here is that thinking blocks come first in an assistant message. The transport that implements Anthropic must confirm it against the API before it ships; the model does not depend on the answer, because it keeps the blocks in order either way. - **The Chat Completions content-part array.** The `text` and `refusal` part types are part of the newer spec; the servers poo targets mostly take a plain string. poo sends a string. A refusal, when the server sends one at all, arrives as the message's top-level `refusal` string, not as a part. - **Anthropic's `cache_creation_input_tokens`.** The field name is taken from the usage block's shape; the value is not carried, so a wrong guess costs nothing. ## What the model therefore has to carry The three APIs together need: text, thinking, tool calls, tool results, one opaque companion per visible block, and whole opaque items. That is exactly `ContentKind`'s five values plus `ProviderBlock`, and nothing more. The model is frozen. --- # Evals & Benchmarks `poo` uses two evaluation tracks: 1. **Built-in `poo-eval` suite** — 20 local tasks for regression testing, baseline comparisons, and failure-mode analysis. 2. **Harbor adapter (`evals/harbor/`)** — external benchmark runs on Terminal-Bench and SWE-bench, including head-to-head comparisons against other CLI harnesses. ## Built-in `poo-eval` suite The suite contains 20 tasks across three categories: - **12 coding tasks**: Python packages with a bug and a failing `unittest` suite. Before grading, the harness restores the fixture's original test files so a run cannot pass by rewriting tests; test edits are reported as unexpected changes. - **5 find-and-explain tasks**: Read-only repositories with one question and no files to change. `evals/tasks/check_answer.py` derives the required facts directly from the untouched workdir, asserts zero file edits, and verifies that the final message names every requested fact. - **3 long-context tasks**: Working sets sized past a 32,768-token window and well under 262,144 tokens (`long-find-definition-in-tree`, `long-find-error-in-log`, `long-change-timeout-everywhere`). They test search discipline, narrowing large files, and multi-file edits without blind search-and-replace. (`long-change-timeout-everywhere` is the only task whose prompt expects test updates.) Each task lives in `evals/tasks//` with a `task.json` and `check.sh` (exit `0` = solved). The model catalog is `evals/models.yaml`, and task repositories live under `evals/fixtures/`. ### Running and managing baselines Run the suite against one or more models from `evals/models.yaml`: ```bash poo-eval run --models gemma4,qwen --seeds 3 ``` Each run writes its report and raw transcripts (`runs/`) to an ignored directory at `evals/runs/-/`. Nothing is committed until accepted: ```bash # Promote a run's report.json, report.md, and summary.json to evals/baseline/ poo-eval accept evals/runs/- # Compare a candidate run against the accepted baseline poo-eval compare evals/runs/- # Or compare two explicit run directories poo-eval compare ``` `compare` writes its diff into the candidate directory. Commit updated `evals/baseline/` files in the same PR that produced the run; older baselines remain in git history. ### Isolation (`--isolation bwrap`) `poo-eval run` wraps each `poo` process in `bubblewrap` by default (`--isolation bwrap`). Inside the sandbox, the process sees only: - Read-only `/usr` and `/etc` - Its own workdir at `/work` - Its log directory at `/log` - A private `/tmp` that also serves as `$HOME` (keeping user-level installs like `pip install --user` out of the run's diff) - Its own PID namespace (closing `/proc` access to host processes) - Shared network access so model endpoints remain reachable The real home directory, repository, and task set are hidden. `check.sh` runs outside the sandbox so it can access the task set, which means pass/fail status is determined outside the model's reach. Workdirs are created under `/poo-eval/work` (`--work-root` overrides this and rejects any path containing or inside the task set). Passing `--isolation none` disables `bwrap` and runs model commands with your full privileges. Without sandboxing, a model that searches the filesystem can discover `check.sh` or `check_answer.py`, invalidating the result. ### Fixture integrity hashing Before the first run, each invocation snapshots the fixtures its tasks use into `//fixtures/` and builds every workdir from that snapshot. The runner hashes each source fixture, its snapshot, and each task directory at startup and again after every run. If any hash changes, the run is marked invalid (`source_changed`, `success: false`), a warning naming the run is written to `stderr`, and `poo-eval run` exits non-zero without restoring the modified source. --- ## Harbor adapter (`evals/harbor/`) The Harbor adapter (`evals/harbor/`, added in PR #344) integrates `poo` with [Harbor](https://github.com/harbor-framework/harbor) via `poo_agent:PooAgent`. It uploads a static Linux `poo` binary into each task container, runs `poo run` headlessly, and reports token usage and session metrics back to Harbor. ### Prerequisites and building the static binary 1. Install Harbor (`uv tool install harbor`) and ensure a container runtime is available (Docker, rootless Podman with `podman.socket` and `DOCKER_HOST`, or a remote backend such as `--env modal` or `--env daytona`). 2. Build the static Linux binary (`CGO_ENABLED=0`) so it runs in any Linux task image with no libc dependencies: ```bash evals/harbor/build-bin.sh ``` This writes `evals/harbor/bin/poo-linux-`. Re-run it after any change to `poo`. ### Running Terminal-Bench and SWE-bench Run a quick smoke test on Terminal-Bench before running the full suite: ```bash export OPENAI_API_KEY="sk-..." PYTHONPATH=evals/harbor harbor run \ --dataset terminal-bench/terminal-bench@4.1.0 \ --agent poo_agent:PooAgent \ --model openai/gpt-4o \ --ak context_limit=128000 \ --ak max_turns=80 \ --n-tasks 3 \ --n-concurrent 2 ``` The same adapter runs against SWE-bench Verified (`--dataset swebench-verified`) or any other Harbor dataset. For local or homelab OpenAI-compatible endpoints, pass `--ak endpoint=...` and `--ak model_id=...` using a LAN hostname or container host alias (`host.containers.internal` / `host.docker.internal`) rather than `localhost`: ```bash PYTHONPATH=evals/harbor harbor run \ --dataset terminal-bench/terminal-bench@4.1.0 \ --agent poo_agent:PooAgent \ --ak endpoint=http://grace:4000/v1 \ --ak model_id=qwen \ --ak context_limit=131072 \ --ak tools_mode=native \ --n-tasks 3 \ --n-concurrent 2 ``` To pin compaction, sampling, or built-in providers, pass `--ak settings=/path/to/settings.yaml`. A settings run uses the model named in the file; overriding the model or window requires setting both `endpoint` and `model_id`. ### Paired harness comparisons Harbor includes built-in adapters for other CLI harnesses, allowing head-to-head comparisons on the same dataset and model: ```bash # Run poo PYTHONPATH=evals/harbor harbor run \ --dataset terminal-bench/terminal-bench@4.1.0 \ --agent poo_agent:PooAgent \ --model openai/gpt-4o \ --ak context_limit=128000 \ --n-tasks 15 \ --n-concurrent 4 # Run another harness (e.g., opencode, claude-code, codex) on the same slice harbor run \ --dataset terminal-bench/terminal-bench@4.1.0 \ --agent opencode \ --model openai/gpt-4o \ --n-tasks 15 \ --n-concurrent 4 ``` Results and raw `session.jsonl` transcripts are written under Harbor's `jobs/` directory. ### Key `--ak` options | Key | Default | Description | | --- | --- | --- | | `poo_bin` | `evals/harbor/bin/poo-linux-` | Path to static Linux `poo` binary (or `POO_HARBOR_BIN`) | | `settings` | none | Local `poo` settings file uploaded into `/logs/agent/` | | `endpoint` | inferred from `--model` | OpenAI-compatible base URL (or `POO_ENDPOINT`) | | `model_id` | inferred from `--model` | Model ID (`--model-id`) | | `api_key_env` | inferred from `--model` | Host env var forwarded into container (or `POO_API_KEY_ENV`) | | `context_limit` | `131072` | Context window in tokens (`--context-limit`) | | `tools_mode` | none | `native`, `text`, or `auto` (`--tools-mode`) | | `reasoning_effort` | none | Passed to `--reasoning-effort` | | `max_turns` | none | Turn cap (`--max-turns`); unset leaves the run uncapped | | `max_output` | none | Output token cap (`--max-output`) | | `truncation_retries` | none | Retries after an output-limit cut (`--truncation-retries`) | | `profile` | `code` | `poo` profile (`--profile`) | | `context_strategy` | none | Compaction strategy (`--context-strategy`) | | `context_keep_recent` | none | Compaction verbatim tail in tokens (`--context-keep-recent`) | | `timeout` | none | Wall-clock limit, e.g. `15m` (`--timeout`) | | `append_system_prompt` | none | Extra system prompt text (`--append-system-prompt`) | Run the adapter's unit tests with: ```bash python3 -m unittest discover -s evals/harbor -v ``` ### Benchmark note In head-to-head Terminal-Bench runs on locally hosted `glm-5.3-flash`, `poo` beat `pi` and tied `mini-swe-agent`. This is not an exhaustive multi-model benchmark study, but it provides concrete evidence that `poo` drives relentless agent loops effectively on real terminal tasks.