# AgentOS Documentation (full text) > AgentOS is a local-first AI agent runtime: install it, wire up a model provider, and drive it from the terminal, Web UI, macOS desktop app, or chat channels. AgentOS DEX adds token swaps for agents: a keyless HTTP API that returns unsigned calldata, and the on-chain contracts that execute it. --- # Quickstart > Source: https://useagentos.dev/docs/core/quickstart This guide gets AgentOS installed, configured, and running locally. It assumes you want the standard product experience: terminal commands, local Web UI, Pilot Router, memory/search support, and safe local defaults. ## Requirements - Python 3.12 or newer for terminal installs. - `uv` for the recommended terminal install. - Git, Git LFS, and Node.js 22 or newer only when installing from source. - A provider API key unless you use a local provider such as Ollama. ## Recommended Install Install the current release (recommended extras included) by following the [Installation](https://useagentos.dev/docs/core#installation) section of the README. The newest release assets are always on the [Releases page](https://github.com/use-agent-os/agent-os/releases/latest). The `recommended` extra includes Pilot Router dependencies and memory/search support used by the default product experience. If `agentos` is not found after install, open a new shell or run: ```sh uv tool update-shell ``` ## First-Run Setup Interactive setup: ```sh agentos onboard ``` Script-friendly setup: ```sh export OPENROUTER_API_KEY="sk-..." agentos onboard --provider openrouter --api-key-env OPENROUTER_API_KEY ``` Useful variants: ```sh agentos onboard --if-needed agentos onboard --minimal agentos onboard --provider openai --api-key-env OPENAI_API_KEY agentos onboard --provider ollama --model llama3.1 ``` `--if-needed` is safe for install scripts because it avoids rewriting an already-ready setup. `--minimal` configures the provider path and skips optional channels/search/image-generation sections. Check onboarding state: ```sh agentos onboard status ``` ## Run the Gateway Foreground gateway: ```sh agentos gateway run ``` Background gateway with readiness wait: ```sh agentos gateway start --json agentos gateway status ``` Default address: ```text http://127.0.0.1:18791/control/ ``` The gateway defaults to loopback for safety. To bind elsewhere, opt in: ```sh agentos gateway run --listen 0.0.0.0 --port 18791 ``` Only expose a non-loopback gateway behind appropriate auth and network controls. ## First Useful Run Open the Web UI: ```text http://127.0.0.1:18791/control/ ``` Start terminal chat: ```sh agentos chat ``` Run one automation turn: ```sh agentos agent -m "Inspect this workspace and suggest a test plan" ``` Run a one-shot task in a specific workspace: ```sh agentos agent \ --workspace /path/to/project \ --workspace-strict \ -m "Review the current diff and list the highest-risk changes" ``` Use the Web UI for browser-based chat, approvals, setup, channels, usage, and logs. Use `agentos chat` when you want a terminal conversation. Use `agentos agent` for one-shot automation. ## Resume Work Resume a terminal chat session: ```sh agentos chat --session ``` Inspect sessions: ```sh agentos sessions list agentos sessions show agentos sessions export ``` Export a session when exact history matters for debugging or handoff. ## Check Readiness Run these after setup: ```sh agentos doctor agentos providers list agentos search list agentos channels types --json ``` If the gateway is running, inspect runtime status: ```sh agentos gateway status agentos providers status agentos channels status agentos memory status ``` For provider/model selection details, see [Providers and Models](https://useagentos.dev/docs/core/providers-and-models). For search setup, see [Web Search](https://useagentos.dev/docs/core/search). For gateway lifecycle, host/port, and exposure guidance, see [Gateway](https://useagentos.dev/docs/core/gateway). ## Stop or Restart Foreground gateway: ```text Ctrl+C ``` Managed background gateway: ```sh agentos gateway stop agentos gateway restart ``` ## Upgrade Upgrade to the latest release. `agentos upgrade` also restarts the gateway and verifies it reports the new version, so it is preferred over calling `uv tool` yourself: ```sh agentos upgrade ``` It installs the published release of `use-agent-os[recommended]` — the same extras profile `install_source.sh` uses — pinned to the Python version already running AgentOS. Your configuration and data in `~/.agentos/` are not touched. To check the installed version, run `uv tool list`. `agentos upgrade` never installs from a local checkout: only `bash scripts/install_source.sh` rebuilds the React control UI before installing. If you installed from source, re-run that script. See the [README upgrade section](https://useagentos.dev/docs/core#upgrade). ## Next Steps After the first run: 1. Configure search if you want web research: [Web Search](https://useagentos.dev/docs/core/search). 2. Enable channels if you want Slack, Telegram, Discord, or another messaging surface: [Channels](https://useagentos.dev/docs/core/channels). 3. Review memory behavior if you want durable recall: [Memory](https://useagentos.dev/docs/core/features/memory). 4. Review tool permissions before unattended automation: [Tools, Approvals, and Sandbox](https://useagentos.dev/docs/core/tools-and-sandbox). 5. Learn Pilot Router if you want cost-aware model routing: [Pilot Router](https://useagentos.dev/docs/core/features/pilot-router). 6. Use the glossary if product terms are unfamiliar: [Glossary](https://useagentos.dev/docs/core/glossary). ## Install From Source Use source install when you want a checkout-backed install: ```sh git lfs install git clone https://github.com/use-agent-os/agent-os.git cd agent-os git lfs pull --include="src/agentos/memory/models/**" git lfs pull --include="src/agentos/agentos_router/models/**" bash scripts/install_source.sh ``` For development, use the repository virtual environment: ```sh uv sync --extra recommended --extra dev uv run agentos --help uv run agentos gateway run ``` When developing from source, prefix commands with `uv run` so they use the checkout you are editing. --- # Use Cases and Recipes > Source: https://useagentos.dev/docs/core/use-cases Use this page when you know what you want AgentOS to do, but you are not sure which feature guide to read first. ## First Successful Run Goal: install AgentOS, configure one provider, and send a real message. ```sh agentos onboard agentos gateway run ``` Then open: ```text http://127.0.0.1:18791/control/ ``` If you prefer the terminal: ```sh agentos chat ``` Read next: - [Quickstart](https://useagentos.dev/docs/core/quickstart) - [Web UI](https://useagentos.dev/docs/core/web-ui) - [Providers and Models](https://useagentos.dev/docs/core/providers-and-models) ## Reduce Model Cost Goal: keep simple work on cheaper models and reserve stronger models for hard turns. ```sh agentos configure router --router recommended agentos cost --by-model ``` Use diagnostics when you want to inspect routing and runtime behavior: ```sh agentos diagnostics on ``` Read next: - [Pilot Router](https://useagentos.dev/docs/core/features/pilot-router) - [Tool Compression](https://useagentos.dev/docs/core/features/tool-compression) - [Compaction and Cache Continuity](https://useagentos.dev/docs/core/features/compaction-and-cache) ## Work With Large Tool Results Goal: let the agent inspect logs, pages, tables, search results, or diffs without flooding the model context. Start with a bounded workspace run: ```sh agentos agent \ --workspace /path/to/project \ --workspace-strict \ -m "Inspect the latest logs and summarize the actionable failures" ``` If the turn seems too slow or expensive: ```sh agentos cost agentos diagnostics on ``` Read next: - [Tool Compression](https://useagentos.dev/docs/core/features/tool-compression) - [Tools, Approvals, and Sandbox](https://useagentos.dev/docs/core/tools-and-sandbox) - [Troubleshooting](https://useagentos.dev/docs/core/troubleshooting) ## Build a Repeatable Workflow Goal: turn recurring work into reusable skills. Find an existing skill: ```sh agentos skills search report agentos skills view ``` Read next: - [Skills](https://useagentos.dev/docs/core/features/skills) - [Artifacts and Media](https://useagentos.dev/docs/core/artifacts-and-media) ## Remember Useful Context Goal: preserve preferences, project notes, or reusable task context so future turns can find them. ```sh agentos memory status agentos memory search "project preference" agentos memory list ``` Inspect a stored memory file: ```sh agentos memory show ``` Read next: - [Memory](https://useagentos.dev/docs/core/features/memory) - [Compaction and Cache Continuity](https://useagentos.dev/docs/core/features/compaction-and-cache) ## Connect a Messaging Channel Goal: use AgentOS from a supported messaging surface while keeping the gateway as the local control point. ```sh agentos channels types agentos channels describe telegram agentos channels add telegram --name personal agentos gateway restart agentos channels status personal --json ``` Read next: - [Channels](https://useagentos.dev/docs/core/channels) - [Configuration](https://useagentos.dev/docs/core/configuration) - [Tools, Approvals, and Sandbox](https://useagentos.dev/docs/core/tools-and-sandbox) ## Schedule Recurring Work Goal: ask AgentOS to run a recurring task without manually opening a chat. ```sh agentos cron add \ --every 1h \ --text "Summarize important project updates" \ --name hourly-project-check ``` Inspect jobs and runs: ```sh agentos cron list agentos cron status agentos cron runs ``` Read next: - [Operations](https://useagentos.dev/docs/core/operations) - [Channels](https://useagentos.dev/docs/core/channels) - [Scheduling](https://useagentos.dev/docs/core/scheduling) ## Publish a User-Visible Artifact Goal: ask the agent to produce a file, report, slide deck, HTML page, image, or media asset that you can inspect and share. ```sh agentos agent -m "Create a short HTML report from the current notes" agentos sessions export ``` Read next: - [Artifacts and Media](https://useagentos.dev/docs/core/artifacts-and-media) - [Skills](https://useagentos.dev/docs/core/features/skills) ## Recover From a Bad Run Goal: understand what happened, reduce risk, and continue safely. ```sh agentos doctor agentos gateway status agentos sessions show agentos cost ``` If a tool was denied or the agent had too much access: ```sh agentos sandbox status agentos agent --permissions restricted -m "Read only" ``` Read next: - [Troubleshooting](https://useagentos.dev/docs/core/troubleshooting) - [Tools, Approvals, and Sandbox](https://useagentos.dev/docs/core/tools-and-sandbox) - [Approvals and Permissions](https://useagentos.dev/docs/core/approvals-and-permissions) - [Diagnostics and Replay](https://useagentos.dev/docs/core/diagnostics-and-replay) - [Operations](https://useagentos.dev/docs/core/operations) --- # Gateway > Source: https://useagentos.dev/docs/core/gateway The AgentOS gateway is the local server behind the Web UI, channels, RPC clients, sessions, approvals, diagnostics, and usage views. Most day-to-day AgentOS surfaces work best when the gateway is running. Use this page when you want to start, stop, inspect, expose, or troubleshoot the gateway. ## Foreground Gateway Run the gateway in the current terminal: ```sh agentos gateway run ``` Open the control console: ```text http://127.0.0.1:18791/control/ ``` Stop a foreground gateway with `Ctrl+C`. `Ctrl+C` and `SIGTERM` (what `agentos gateway stop`, the desktop app, launchd and systemd send) run the same orderly shutdown: new turns are refused, turns in flight get up to 30 seconds to finish, channels stop, connected clients receive a `shutdown` event, sockets and MCP clients close, and the process exits 0. A second signal cancels the turns still running instead of waiting for them. ## Managed Background Gateway Start a managed background process and wait for readiness: ```sh agentos gateway start --json ``` Inspect it: ```sh agentos gateway status agentos gateway status --json ``` Restart or stop it: ```sh agentos gateway restart agentos gateway stop ``` Use the managed gateway for the Web UI, channels, scheduled jobs, and local automation that should survive the current terminal tab. `agentos gateway status --json` also reports what a supervisor needs from a live gateway: `drain_budget_ms` (how long a stop may take to drain turns), `active_turns` (turns running right now) and `runtime` — the gateway's own readiness `state` (`starting`, `ready`, `draining`, `safe_mode`), what is `failing`, and the `safe_mode` details. The top-level `state` stays the process state (`running`, `unmanaged`, `not_started`, ...). Add `--deep` to also report an installed service. ## Run as a Service Keep the gateway running across crashes, logouts and reboots by installing it as a user service: ```sh agentos gateway install # port from config (usually 18791) agentos gateway install --port 18792 --config ~/.agentos/config.toml agentos gateway status --deep # adds the service: installed, loaded/active agentos gateway uninstall ``` | Platform | Unit | Restart policy | |---|---|---| | macOS | LaunchAgent `~/Library/LaunchAgents/dev.useagentos.gateway.plist` (label `dev.useagentos.gateway`), logs in `~/Library/Logs/AgentOS/gateway-service.log` and `gateway-service.err.log` | `KeepAlive`, `RunAtLoad`, `ThrottleInterval 10` (at most one respawn per 10 s), `ExitTimeOut 54` | | Linux | systemd user unit `~/.config/systemd/user/agentos-gateway.service` (`systemctl --user daemon-reload` + `enable --now`) | `Restart=always`, `RestartSec=5`, `RestartPreventExitStatus=78`, `KillMode=mixed`, `TimeoutStopSec=54` | | Windows | not supported | — | The unit runs the absolute path of the `agentos` you installed it with (`~/.local/bin/agentos` keeps working after `uv tool upgrade`) as `agentos gateway run --port N [--config PATH]`, with a `PATH` that starts with `~/.local/bin`, `/opt/homebrew/bin` and `/usr/local/bin`, followed by the installing shell's own `PATH`, so harness CLIs installed with Homebrew, npm, nvm, volta, bun or pyenv are found. `AGENTOS_STATE_DIR` and `AGENTOS_GATEWAY_CONFIG_PATH` are carried into the unit when they are set in the installing shell, and `AGENTOS_SERVICE` (`launchd` or `systemd`) tells the gateway it runs under a service manager. The stop timeout (54 s) is the gateway's worst-case stop — 30 s for turns to finish, 2 s to cancel the rest, 2 s for clients' closing handshakes and 10 s for the HTTP server to stop — plus a 10 s margin, derived from the bounds the shutdown itself uses. Installing the same unit again is a no-op, also from a shell whose `PATH` differs (the installed unit is kept; uninstall and install again to refresh its `PATH`). A different unit under the same name (another port or config, or a job with that label loaded from elsewhere) is refused: run `agentos gateway uninstall` first. `--no-start` writes the unit without loading it. `uninstall` with nothing installed succeeds. On Linux, run `loginctl enable-linger $USER` once if the gateway should keep running after you log out. `agentos gateway stop` does not stop a service-run gateway: the service manager would start it again. It exits `3` and says how to stop it instead — `launchctl bootout gui/$(id -u)/dev.useagentos.gateway` until the next login on macOS, `systemctl --user stop agentos-gateway.service` on Linux — or remove the service with `agentos gateway uninstall`. `agentos gateway restart` restarts a service-run gateway in place. A configuration error (exit `78`) is not restarted by systemd. launchd has no such switch and would respawn it every 10 s, so under launchd the gateway waits before exiting `78`: 5 s, doubling with each consecutive config failure up to 5 minutes (a streak older than 15 minutes starts over, a successful boot resets it), and says so in `~/Library/Logs/AgentOS/gateway-service.log`. The desktop app adopts a gateway that already answers on its port, so it works with an installed service; do not let both start their own gateway on the same state directory. ### Crash-loop breaker (safe mode) Every boot is recorded in the gateway database, with a heartbeat every 30 s. When a boot finds **3 unclean boots that ended in the last 5 minutes** — runs that ended without a clean shutdown (killed, crashed, out of memory), counted by their last heartbeat, so a gateway that ran for an hour before crashing counts as crashing now — it starts in **safe mode** instead of restarting the same crash forever: - the control plane starts as usual: Web UI, WebSocket, HTTP, `agentos doctor`, logs, config; - channels, the cron scheduler and the heartbeat are held back, so no automatic turn runs; - `/ready` answers `200` with `state: "safe_mode"` and the reason, and `agentos doctor` reports a `gateway.safe_mode` finding with the way out; - safe mode clears by itself once the 5-minute window drains without another unclean boot (checked every 30 s), and everything it held back starts then. To leave it sooner, fix the cause (the log has the crash) and run `agentos channels start --yes`: it starts every channel, the scheduler and the heartbeat, and stops counting the recorded crashes. `agentos channels start NAME --yes` starts a single channel and keeps safe mode on for the rest — the way to find which channel crashes the gateway. A clean stop never counts: `agentos gateway stop`, a service manager's or the desktop app's SIGTERM, `Ctrl+C` and an in-place restart are all clean. Nor does a boot that failed before it served (a bad config, a failed migration): safe mode could not help it. If the boot ledger cannot be read the breaker is skipped for that boot (fail open), never the start. ## Supervisor Contract What a process supervisor (the desktop app, launchd, systemd, a script) can rely on: | Signal | Contract | |---|---| | `GET /health` | Liveness: `200` whenever the HTTP server answers. | | `GET /ready` | `{ready, state, failing, startup, safe_mode, drain_budget_ms, uptime_ms}`. `state` is `starting` (boot sidecars still running; `failing` names them, e.g. `["channels"]`), `ready`, `draining` (stopping or restarting in place; `failing: ["draining"]`) or `safe_mode` (`failing: ["safe_mode"]`). `503` while `starting` or `draining`; `200` for `ready` and `safe_mode`, where the control plane serves so the cause can be fixed. In `ready` and `safe_mode`, `failing` also names each channel that is down (failed to start, or stopped on bad credentials) as `channel:`; that does not make the gateway unready. `startup.failed.channels` records which channels failed at boot and why. `turn_recovery` counts the [interrupted turns](#interrupted-turns) found at boot by state (`found`, `pending`, `running`, `resumed`, `closed`, `tombstoned`, `cancelled`, `reported`, `expired`) plus `auto_resume`; it never makes the gateway unready. | | `GET /startupz` | `200` once every boot sidecar settled (channels started, router preloaded), `503` before; `pending` lists what is left. | | WebSocket `connect` during boot | Answered with a retryable error `UNAVAILABLE`, `details: {code: "STARTUP_SIDECARS", retry_after_ms}`, then close `1013` (`gateway starting`). Clients retry after `retry_after_ms`; the CLI retries for up to 30 s, the web console and desktop keep "connecting". | | `shutdown` event | `{reason, restart_expected_ms}`, flushed to every connection before its socket closes with `1012`. A number is an in-place restart with an estimate of when the gateway serves again (this boot's own duration plus teardown, at least 3 s); `null` is a terminal stop (a signal, `Ctrl+C`). A client that stopped reading may still miss it (each flush is bounded to 1 s); on close `1012` without the frame, reconnect with the normal backoff. | | Exit code `78` | `EX_CONFIG`: a startup failure only a configuration change fixes — a config file that is not valid TOML or does not validate, a schema migration that cannot apply, a public bind without auth. Repair, then retry; systemd's `RestartPreventExitStatus=78` stops a restart loop. Other startup failures exit `1`. | The desktop app follows it: a spawned gateway is "running" once `/ready` answers `200`; on exit `78` it runs `agentos doctor --json` once, retries the start once, and otherwise shows the exit code with doctor's top finding. ### Sleep and wake A laptop gateway checks itself every 30 s. A gap of more than 45 s between two checks during which the process used almost no CPU means the machine slept: the gateway logs `gateway.thaw`, restarts the channels that are idle (their sockets are stale after a sleep), wakes the scheduler and tells connected clients to refresh (`health` event). Every 5 minutes (after a 60 s start-up grace) it also sweeps channel health and restarts a channel that is `disconnected`, `stuck` (its retry loop gave up), `start_failed` (its last start raised, e.g. no network at login) or `stale-socket` (no inbound event for 30 minutes on a socket or polling transport), at most once per two sweeps each. A restart that fails — the network is not back yet right after a wake — never leaves the channel stopped: the gateway retries the start with backoff (1 s, 2 s, 4 s, ... six times; the channel reads `retrying`), and if that runs out the channel reads `stuck` and the next sweep starts over. Only a channel that failed on bad credentials (`terminal`) or that the platform `blocked` is never restarted automatically: doctor reports it with the fix. A channel you stopped yourself (`agentos channels logout`) stays `stopped`. `agentos channels status` shows each channel's `state` and the reason it is down, and whether safe mode is on; `--json` adds `last_event_at`, `terminal_reason`, `start_error`, and the policy plus the last sweep and thaw (`restarted`, `failed`, `skipped` per channel) under `health_policy`. ## Host and Port Use a different port: ```sh agentos gateway run --port 18792 agentos gateway status --port 18792 ``` Pick where the gateway listens with a bind mode: | Mode | Listens on | Notes | | --- | --- | --- | | `loopback` | `127.0.0.1` | The default. Only this machine can connect. | | `lan` | `0.0.0.0` (every interface) | Token auth is required; the gateway refuses to start without it. | | `tailnet` | the Tailscale IPv4 **and** `127.0.0.1` | Reads the address from `tailscale ip -4`. Fails to start if Tailscale is missing, stopped or logged out — it never falls back to `0.0.0.0`. Token auth is required. | | `custom` | the `host` you configured | What `--listen` / `--bind` select. | ```sh agentos gateway run --bind-mode tailnet agentos gateway start --bind-mode lan ``` Or persist it: ```toml [gateway] bind = "tailnet" ``` Bind to a specific host: ```sh agentos gateway run --listen 127.0.0.1 --port 18791 ``` `--listen` is an alias for the bind host and wins over `--bind` when both are provided; either one means bind mode `custom`. `gateway start` records the bind mode it used, so a plain `gateway status`, `gateway stop` or `gateway restart` finds that gateway again (`--bind-mode` is accepted there too). On macOS the Tailscale app's bundled CLI is used when `tailscale` is not on PATH. Precedence, highest first: `--listen`, `--bind`, `--bind-mode`, `AGENTOS_LISTEN`, `AGENTOS_GATEWAY_HOST`, `[gateway] bind`, the `host` key, `127.0.0.1`. ## Safety Defaults The gateway defaults to loopback scope, usually `127.0.0.1`, because the local gateway controls chat, tools, sessions, channels, approvals, and configuration. Public binding is opt-in: ```sh agentos gateway run --bind-mode lan --port 18791 ``` Do not expose a gateway to an untrusted network without token auth and a network boundary you understand. To reach a gateway from another machine, prefer keeping it on loopback and tunnelling in (SSH, Tailscale Serve) or putting an authenticating reverse proxy in front: see [Remote Access](https://useagentos.dev/docs/core/remote-access). `agentos doctor` flags risky exposure settings. ### Browser origins Every bind applies the same origin policy to the WebSocket handshake, to `/api/*` requests that carry an `Origin` header, and to CORS. A browser page may drive the gateway when its origin is: 1. listed in `control_ui.allowed_origins`, `cors.allowed_origins` or `[gateway] public_origin`, or is the gateway's own `http://localhost:` / `http://127.0.0.1:` (always allowed, so a LAN bind never locks out the browser on the gateway's machine); 2. the same origin as the address the request was sent to, when that address is private: loopback, `10/8`, `172.16/12`, `192.168/16`, link-local, `100.64.0.0/10` (tailnet addresses), IPv6 `fc00::/7`, or a `.local` / `.ts.net` name. Opening `http://192.168.1.20:18791/control/` on a LAN bind works with no configuration; 3. a loopback origin on another port (a dev server) when the connection itself comes from this machine and not through a proxy. Anything else is refused with `403` — for a WebSocket, at the handshake, before the upgrade — and CORS never answers `*`. On a loopback bind only loopback addresses count for rule 2. Requests without an `Origin` header — the CLI, `curl`, scripts — are not affected; token auth still applies. The `Host` header is checked too (a DNS-rebinding guard): the gateway answers to loopback, to the hostnames of the declared origins, and off loopback to any IP address and `.local` / `.ts.net` names. A request for any other name gets `400` naming the setting to change. When you serve the console from a public address or a DNS name, declare the origin you open it at: ```toml [gateway] public_origin = "https://agent.example.com" ``` Without it, the gateway refuses to start the Control UI on a specific public address (it would load and then fail every request). The fix is in the error message; `control_ui.enabled = false` keeps the API running without the console. ## Configuration Path Use a specific config file: ```sh agentos gateway run --config /path/to/agentos.toml agentos gateway status --config /path/to/agentos.toml ``` AgentOS also reads standard configuration locations described in [Configuration](https://useagentos.dev/docs/core/configuration). ## Remote Status Check Inspect a gateway URL directly: ```sh agentos gateway status --gateway ws://localhost:18791/ws ``` This is useful when a client or MCP bridge is configured with an explicit gateway URL. ## When to Restart Restart the gateway after changing: - provider or router configuration; - channel configuration; - durable agent entries; - global sandbox posture; - search or image-generation setup; - environment variables used by configured providers. ```sh agentos gateway restart ``` That works for a gateway started with `agentos gateway start` (stop, then start) and for one started any other way — the desktop app, launchd, systemd or a terminal `agentos gateway run` — which restarts itself **in place**: the gateway drains the turns in flight, re-executes itself under the same process id so every launcher keeps tracking it, and comes back on upgraded code. The CLI confirms the restart from the gateway's readiness probe. Not available on Windows, where the process image cannot be replaced. The same in-place restart is reachable from chat: - `/restart` in the web console or the desktop app (operators only, no setting needed). The socket drops and reconnects; a toast reports when the gateway is back. - `/restart` from a paired Telegram, Discord or Slack sender, and the agent's own `gateway` tool, once `[gateway_control] chat_restart = true` is set and the gateway has been restarted once. The reply acknowledges, then "Gateway restarted (v…, Ns)" lands in the same chat or thread after boot. `/restart` waits up to 30 seconds for active turns to finish; `/restart force` (or `agentos gateway restart --force`) cancels them instead. A second request while one is pending is reported, not queued. ### Interrupted turns A turn the gateway stops under -- a restart that cancels it, or a crash -- is marked interrupted (task status `abandoned`, reason `shutdown_interrupted` or `process_restart`). On the next boot, once channels are up, the gateway looks at every session whose newest turn is such a turn and decides from the transcript what to do: - The reply (or an error) was already written, or there is nothing to answer: nothing to resume. - The user's message was never answered, or the last recorded tool round finished: the turn is resumed with the session's usual tools. - Tool calls were issued with no recorded result (their outcome is unknown): the turn is resumed with **read and status tools only** (file, git, memory and session reads, `web_search`), so it checks what happened instead of acting again. Shell, file writes, trading, outbound messages, approvals and arbitrary HTTP are not available to that turn; the user's next message gets every tool back. The resume is a short internal continuation message, not a replay of the user's message, and its reply goes where a normal reply would: the web console and the desktop app show it in the session, a channel turn's reply is sent to the same chat or thread. A turn from a paired channel is resumed only while that sender's pairing still stands. Each interrupted turn gets at most three attempts (counted across restarts, with backoff); after that, or for a turn older than 24 hours, the session gets a note asking the user to send a message to continue. A new message on the session cancels a resume that has not started yet. Cron, heartbeat, subagent and ACP turns are never resumed, and neither is anything while the gateway is in safe mode. A turn that asked for the restart itself (the `gateway` tool's `restart`, or a shell command that restarts, stops or updates the gateway), or any turn of the session the restart request came from, is not resumed either, so it cannot restart the gateway again: its session gets a note instead. `[task_runtime] resume_interrupted_turns = false` turns the automatic resume off: interrupted turns are only reported (the note in the session, `/ready` `turn_recovery`, an `agentos doctor` finding). ```toml [task_runtime] resume_interrupted_turns = true # default ``` ## Troubleshooting Check status and readiness: ```sh agentos gateway status agentos doctor curl -s http://127.0.0.1:18791/ready ``` If `/ready` reports `state: "safe_mode"`, the gateway restarted after crashing three times in five minutes and is holding channels, cron and heartbeat back; see [Crash-loop breaker](#crash-loop-breaker-safe-mode). If `agentos gateway run` exits `78`, the configuration is the problem: run `agentos doctor` and fix what it reports before starting again. If the port is busy: ```sh agentos gateway run --port 18792 ``` If the Web UI cannot connect, confirm that the URL matches the gateway bind host and port. Read next: - [Remote Access](https://useagentos.dev/docs/core/remote-access) - [Run the Gateway in a Container](https://useagentos.dev/docs/core/container-gateway) - [HTTP API](https://useagentos.dev/docs/core/http-api) - [Web UI](https://useagentos.dev/docs/core/web-ui) - [Configuration](https://useagentos.dev/docs/core/configuration) - [Channels](https://useagentos.dev/docs/core/channels) - [Troubleshooting](https://useagentos.dev/docs/core/troubleshooting) --- # Configuration > Source: https://useagentos.dev/docs/core/configuration AgentOS can be configured from the onboarding wizard, the Web UI setup flow, CLI commands, environment variables, and TOML files. Use CLI commands for routine setup and edit TOML only for advanced or scripted deployments. ## Config Load Order AgentOS reads configuration in this order: 1. `AGENTOS_GATEWAY_CONFIG_PATH` 2. `./agentos.toml` 3. `~/.agentos/config.toml` 4. built-in defaults Use `--config ./agentos.toml` when you want to write or inspect a project-local config file. ## Secret Handling Prefer environment-variable references for secrets: ```sh export OPENROUTER_API_KEY="sk-..." agentos configure provider --provider openrouter --api-key-env OPENROUTER_API_KEY ``` Avoid committing raw API keys to TOML files, shell history, examples, or issue reports. ## Environment Variables Environment variables live in `~/.agentos/.env` and are managed with [`agentos env`](https://useagentos.dev/docs/core/cli#environment-variables) or the Environment screen in the Web UI. They are where credentials belong — skills and external binaries read them, and AgentOS masks them in every listing. ### Load order and the shadowing trap `.env` files are read once at process start, in this order, and **an existing environment variable is never overridden**: 1. `os.environ` — whatever the shell that started AgentOS exported 2. `$CWD/.env`, then `$CWD/.env.test` 3. `~/.agentos/.env` The first rule is the one that surprises people. If your shell exported `OPENAI_API_KEY`, then writing that variable through AgentOS updates the file and the running process, but a restart goes back to the shell's value. `agentos env list` reports the source of each value (`process env` / `project .env` / `AgentOS .env`) and the Web UI warns on the row, so this is visible rather than something to discover through a confusing hour. To make the file authoritative, remove the export and restart. Likewise, a `.env` in the directory the gateway was started from wins over `~/.agentos/.env` -- except for the names below and the runtime-steering ones (`PYTHON*`, `ECC_BACKEND_CLASS`, `ETH_HASH_BACKEND`, `ETH_ACCOUNT_KDF`, `SSL_CERT_FILE`, `SSL_CERT_DIR`, `SSLKEYLOGFILE`, `REQUESTS_CA_BUNDLE`, `CURL_CA_BUNDLE`, `PYTHON_KEYRING_BACKEND`), which a project `.env` cannot set: that directory is often writable by an agent's shell, and the values would land in the process that holds the wallet keys. AgentOS logs `env.project_env_name_ignored` for each one it skips. Put them in `~/.agentos/.env` or export them before starting AgentOS. ### What cannot be written through AgentOS Names that steer subprocess execution or AgentOS runtime posture are refused by every AgentOS surface — the Web UI, the CLI, the RPC, and the agent tool: - Loader and interpreter: `LD_PRELOAD`, `LD_LIBRARY_PATH`, `DYLD_*`, `PYTHONPATH`, `PYTHONHOME`, `PYTHONSTARTUP`, `NODE_OPTIONS`, `NODE_PATH` - Shell and implicitly-invoked commands: `PATH`, `SHELL`, `IFS`, `BASH_ENV`, `EDITOR`, `VISUAL`, `PAGER`, `BROWSER`, `GIT_SSH_COMMAND`, `GIT_EXEC_PATH` - AgentOS posture and state location: `AGENTOS_SENSITIVE_PATHS_DISABLED`, `AGENTOS_SENSITIVE_PAYLOAD_DISABLED`, `AGENTOS_REDACT_SECRETS`, `AGENTOS_STRIP_PROVIDER_ENV`, `AGENTOS_SHELL_DENYLIST`, `AGENTOS_SAFE_BIN_*`, `AGENTOS_AGENT_PERMISSIONS`, `AGENTOS_TRUST_ENV`, `AGENTOS_GATEWAY_TOKEN`, `AGENTOS_GATEWAY_CONFIG_PATH`, `AGENTOS_STATE_DIR`, `AGENTOS_ROOT`, and the bind settings - Outbound routing: `AGENTOS_LLM_PROXY`, `HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`, `NO_PROXY` — **in any casing**, because the libraries that read these names lower-case them first, so `Http_Proxy` routes traffic exactly as `HTTP_PROXY` does. `AGENTOS_LLM_PROXY` is applied to every provider client, so a writable proxy name would let a surface hand each request — API key header included — to a machine of its choosing. `AGENTOS_TRUST_ENV`, which decides whether the ambient `*_PROXY` names are honoured at all, is refused for the same reason. Configure a proxy through `llm.proxy` in the config file, or export it in the shell that starts the gateway. **An agent's own connection is held to an allowlist.** A connection the gateway recognizes as an agent's (agent token, a process the gateway spawned, an open exec window) may `env.set`, `env.unset` or `env.import` only a name the catalog marks agent-settable: a credential-shaped name (`*_API_KEY`, `*_TOKEN`, ...) that an installed skill's `requires.env` or a built-in tool declares. Provider keys, names only your `.env` holds, `AGENTOS_*` names, the wallet's own `RPC_BASE_URL` / `RPC_ROBINHOOD_URL` / `UNISWAP_API_KEY`, the skill hot-wallet keys (`UNIV4_LP_PRIVATE_KEY`, `POOLSFUN_PRIVATE_KEY`, `GMGN_PRIVATE_KEY`, whatever a skill manifest declares about them), and the runtime-steering names above are refused with `env.protected`; so is `env.reveal` of any secret (or uncatalogued) name, and of a hot-wallet key always. Your own connections -- the console, the desktop app, the CLI outside an agent's session -- are not affected. The agent's `env_set` tool still asks for your approval per write. Tools AgentOS spawns inherit most of `os.environ`, and several AgentOS guards are themselves read from it, so a surface that could write these names could widen what the agent is allowed to do. The `AGENTOS_` prefix is not blanket-blocked — ordinary credentials such as `AGENTOS_LLM_API_KEY` remain writable. ### Credentials and child processes `exec_command` and `background_process` pass most of the environment to the command they run, so `gh`, `aws`, `docker` and the rest keep working as they do in your own shell. Three groups are treated differently: | Group | Reaches a child? | Why | | --- | --- | --- | | `AGENTOS_GATEWAY_TOKEN` and the guard switches above | never | The token authenticates to the control plane; the switches let a child reconfigure the next call. | | AgentOS provider keys (LLM, search, image, audio, embeddings) | yes, unless you opt out | Bundled skills read them from `os.environ`. Set `AGENTOS_STRIP_PROVIDER_ENV=1` before starting AgentOS to withhold them. | | Everything else | yes | Your own credentials, in your own shell. | `execute_code` is the other way round: it forwards a small fixed allowlist and nothing else. A skill that needs its own API key there declares it, and the name is added for the session that loaded the skill: ```yaml metadata: agentos: requires: env: [CAP_API_KEY] ``` The value is read from the environment at spawn time and never enters the transcript. A skill installed from a hub cannot declare one of AgentOS's own provider keys this way — that request is refused and logged. Output from `exec_command`, `background_process` and `process(action=log)` is scanned for credentials before it reaches the model. Vendor-shaped keys, auth headers, JWTs, private keys and DSN passwords are masked. Set `AGENTOS_REDACT_SECRETS=0` before starting AgentOS to turn this off; it is read once at startup, so a command the agent runs cannot switch it off mid-session. File content is scanned the same way: `read_file`, `read_spreadsheet`, `grep_search` and `edit_file`'s closest-match hint mask credentials on their way back to the model, using a `«redacted:sk-…»` sentinel that cannot be mistaken for a usable key and written back over the real one. This layer stays on even under `/elevated full`, where the sensitive-path denylist is lifted, so an elevated read of a secrets file does not put the secrets verbatim into the persisted transcript. Reading one through the shell (`cat ~/.aws/credentials`) gets the same treatment. How hard the pass looks depends on the file. Credentials recognisable from their own text — vendor-prefixed keys, JWTs, PEM private keys — are masked in every file, source code included. The name-driven pass (`NAME=value`, `"name": value`, `Authorization:` headers, DSN and URL passwords) is the only one that catches a shapeless secret such as `aws_secret_access_key`, and it runs everywhere **except** source code, where `api_key=self._api_key` is an identifier and `apiKey: NotRequired[str]` a type: masking those would hand back code that no longer matches the file. Configuration data — `.env`, `~/.aws/credentials`, `~/.kube/config`, `.netrc`, `.ini`, JSON and YAML — gets the full pass. `grep_search` judges each matched line by the path it came from, so one search can span both kinds of file. `git_status`, `git_diff`, `git_log` and `git_commit` are scanned too, and always with the full name-driven pass. `git_diff` hands back whatever the repository happens to contain, a committed `.env` included, so the git arguments say nothing useful about what kind of content is coming back. A credential on a diff's `+`/`-` line — or on the `++`/`--` columns of the combined diff a conflicted merge produces — is masked like any other, and with the same non-reusable sentinel the file surfaces use, so a masked diff fed back through `git apply` fails loudly instead of writing a dead-looking key. ### What the outbound guard refuses `http_request`, `exec_command` and `execute_code` refuse to put credential *material* on the network: a PEM private key, an `/etc/passwd`-shaped line, a vendor-prefixed provider key (`sk-ant-…`, `ghp_…`, `AKIA…`), or a connection string with an inline password. The shell check only applies to commands that can actually reach the network. An opaque API key in an `x-api-key` or `Authorization` header is **not** refused — that is how authenticated APIs work, and it cannot be told apart from exfiltration by looking at the bytes. What keeps it safe is the credential path above, not a pattern match. `web_search` is stricter than the rest, because a search provider has no business with any credential in a query. Set `AGENTOS_SENSITIVE_PAYLOAD_DISABLED=1` before starting AgentOS to disable the check entirely. The gate applies on *write* only. Values you set in your shell or by editing `~/.agentos/.env` by hand keep working exactly as before. ### Credentials that already exist elsewhere Before telling you a variable is missing, AgentOS checks whether it is already obtainable. Today that means the GitHub CLI: if `gh auth login` has been run, `GITHUB_TOKEN` and `GH_TOKEN` are reported as available and can be imported with one command or one click. Two properties are deliberate. Checking never reads the credential — it runs `gh auth status`, not `gh auth token` — so a listing that mentions a source has not touched a secret. And importing only ever happens when you ask for it, because a token you granted to another tool becoming available to an agent should not be something that happens quietly. An imported value is a copy. It stays as it was when imported and will not follow the source's own rotation; re-import to refresh it. ### Skill settings are not secrets A skill may also declare ordinary settings — a directory, a format, a default — under `metadata.agentos.config` in its `SKILL.md`: ```yaml metadata: agentos: config: - key: wiki.path description: Path to the knowledge base directory default: "~/wiki" ``` These live in the TOML config under `[skills.config]`, not in `.env`, because there is nothing to hide and a visible, diffable setting is easier to share and review: ```sh agentos config set skills.config.wiki.path /srv/wiki --config ~/.agentos/config.toml ``` When the agent opens the skill, the values currently in effect are appended to what it reads, so it does not have to ask or go looking. ## Skill Prompt Budget Every eligible skill is listed for the agent in a block appended to the system prompt. `[skills].max_skills_prompt_chars` caps how large that block may get: ```toml [skills] max_skills_prompt_chars = 28000 ``` The budget degrades one step at a time, so overrunning it by one skill costs a little description text rather than every description in the block: | Step | `skills_render_mode` | What the agent sees | | --- | --- | --- | | Fits | `full` | Every skill, full description | | Over | `full_truncated` | Every skill, descriptions shortened to the longest length that fits (floor 120 chars) | | Over even at 120 | `compact` | Names only, plus a pointer to `skill_list` | | Still over | `compact_truncated` | Fewer names | The shortened length is the widest one that fits, not a fixed step, so the block spends the budget you gave it rather than settling well under it. The agent is told the descriptions are shortened and where to read the full text. Only the last step drops skills, and it drops the lowest-precedence layer first — `extra` (the directories you listed in `skills.extra_dirs`), then `bundled`, and only then `managed`, `personal`, `project`, `workspace`. A drop is logged as `skills_filter.budget_truncated` with the names, and the affected skills report a `prompt_budget` reason on the Skills screen. Any step below `full` is logged as `skills_filter.budget_degraded` and recorded per turn as `skills_render_mode` in the decision log, because a block that quietly lost its descriptions used to be indistinguishable from one with fewer skills in it. The default of 24000 is sized so a default install lists every bundled skill *with* its description and still has room for roughly 17 skills you add — past that, descriptions start being shortened. If `skills_render_mode` is not `full` and you have context to spare, raise the budget; the alternative is `skills.filter_enabled`, which injects only the skills relevant to each message and so needs far less room. Lower it only if you are running a model with a small context window: the whole-request ceiling on a model below roughly 64k tokens can be smaller than this budget, in which case the skills block alone would not fit. With `filter_enabled = false` the list is identical on every turn, so it is injected as part of the cacheable system prompt. With filtering on it is re-picked per message and is kept out of the cached prefix instead. ## Skill Install Policy `[skills.install_policy]` runs an operator-owned command against every hub skill before it is installed or updated: | Key | Default | Meaning | | --- | --- | --- | | `enabled` | `false` | Turn the policy on. Enabled with no usable `command`, every install is refused. | | `command` | `""` | Absolute path to the executable. Not resolved through `PATH`. | | `args` | `[]` | Arguments, e.g. `["openclaw-install-policy"]` for ClawScan. | | `pass_env` | `["PATH"]` | The only environment variables the command inherits. | | `timeout_seconds` | `300` | The install is blocked when the command runs longer. | | `max_output_bytes` | `1048576` | The install is blocked when the command prints more. | The request and response format, and what `--force` can and cannot override, are in [Install Security](https://useagentos.dev/docs/core/features/skills#install-security). ## Skill Read Ceiling `[skills].max_skill_view_chars` caps one `skill_view` result: ```toml [skills] max_skill_view_chars = 10000 ``` This is a different budget from the one above, because a tool result is not cached the way the system prompt is: a large skill costs its tokens again on every re-read. The shipped skills are small (median 2 400 characters, largest 21 600), so the ceiling only engages for skills installed from a hub or written for another agent — 56 000 characters for one, 87 000 for another, which is 14 000 to 22 000 tokens in a single tool result. Over the ceiling, `skill_view` returns the skill's opening sections plus an index of the rest, and the agent reads on with `skill_view(name, section="")` or `skill_view(name, file_path="...")`. Two cases are deliberately left whole: a body with no headings, because there would be no way to ask for the rest, and a body only slightly over the ceiling, where the index would cost more than it saves. Set `0` to switch it off. ```sh agentos config get skills.max_skills_prompt_chars agentos config set skills.max_skills_prompt_chars 32000 agentos gateway restart ``` ### Pinning a section Which sections survive the cut is otherwise decided by where they sit in the file, so a rule written into a large skill's tail is invisible and nothing says so. A skill can mark a section to be returned wherever it sits, by writing `<!-- always -->` on the line directly above its heading: ```markdown <!-- always --> ## Rules Every file this job needs lives in its own directory. ``` It is an HTML comment, so it renders as nothing anywhere the file is read as markdown, and it only counts as a marker when it is the nearest non-blank line above the heading — a skill that documents the marker does not pin whatever heading follows the explanation. Pinned sections come out of the same ceiling rather than adding to it: together they may take at most half of it, the opening gets what is left, and a section that does not fit is left in the index instead of being cut in half. Reserve it for invariants; pinning reference material spends the opening on it. A pinned section is worth little if it only lasts the turn that read it, so the transcript keeps a `skill_view` result up to this ceiling rather than the short preview it keeps of ordinary tool output. Raising `max_skill_view_chars` raises what is stored per view with it. ## First-Run Wizard ```sh agentos onboard ``` Common options: ```sh agentos onboard --if-needed agentos onboard --minimal agentos onboard --provider openrouter --api-key-env OPENROUTER_API_KEY agentos onboard --provider openai --model gpt-5.4-mini --api-key-env OPENAI_API_KEY agentos onboard --provider ollama --model llama3.1 agentos onboard status ``` The router mode defaults to `recommended`. Use `--router disabled` when you want direct single-model routing. ## Reconfigure One Section The `configure` command edits a selected section: ```sh agentos configure provider --provider openrouter --api-key-env OPENROUTER_API_KEY agentos configure router --router recommended agentos configure router --router openrouter-mix agentos configure router --router disabled agentos configure search --search-provider brave --api-key-env BRAVE_SEARCH_API_KEY agentos configure x-search --api-key-env XAI_API_KEY agentos configure channels agentos configure image --image-provider openai --primary openai/gpt-image-1 --api-key-env OPENAI_API_KEY agentos configure memory --memory-provider local --onnx-dir ~/.agentos/models/embeddings/google-embeddinggemma-300m ``` Supported sections: - `provider` - `router` - `channels` - `search` - `x-search` - `image-generation` - `memory-embedding` ## Configuration Decision Table | Need | Preferred command | | --- | --- | | First setup | `agentos onboard` | | CI or install scripts | `agentos onboard --if-needed` | | Change provider | `agentos configure provider ...` | | Enable or disable routing | `agentos configure router ...` | | Configure web search | `agentos configure search ...` | | Configure messaging platforms | `agentos configure channels` | | Inspect current values | `agentos config get` | | Persist an advanced key | `agentos config set <key> <value> --config <path>` | | Delegate coding to Claude Code / Codex | `agentos acp doctor`, then `[acp]` (see below) | ## Provider Configuration Inspect provider support: ```sh agentos providers list agentos providers configure openrouter agentos providers status ``` Onboarding-verified providers include: - OpenRouter - Bankr LLM Gateway - OpenCAP - Surplus Intelligence - OpenAI - Anthropic - Ollama - DeepSeek - Gemini - DashScope / Qwen - Moonshot AI - Zhipu / Z.AI - Baidu Qianfan - Volcengine Ark AgentOS also carries provider registry entries for additional OpenAI-compatible or self-hosted backends. Use `agentos providers list` on your install to see the current catalog. Read: [Providers and Models](https://useagentos.dev/docs/core/providers-and-models) ### OpenCAP See [Providers and Models — OpenCAP routing](https://useagentos.dev/docs/core/providers-and-models#opencap-routing) for the canonical setup, model catalog, routing, and pricing behavior. ### Surplus Intelligence See [Providers and Models — Surplus Intelligence routing](https://useagentos.dev/docs/core/providers-and-models#surplus-intelligence-routing) for the canonical setup, model catalog, routing, and pricing behavior. Set `AGENTOS_SURPLUS_LIVE_PRICING=0` to use static price estimates instead of its live marketplace catalog. ### Ollama plain-text mode AgentOS supports Ollama native tool calls. For a local model that does not reliably implement Ollama's tool-call protocol, select the model separately, then turn on plain-text mode. Check which models are installed with `ollama list`, then configure the provider and model: ```sh agentos configure provider --provider ollama --model <your-local-model> ``` Then disable model-visible tools and the router in `agentos.toml`: ```toml [tools] enabled = false [agentos_router] enabled = false ``` For a remote or non-default host, set `base_url` under `[llm]` (e.g. `http://10.0.0.42:11434`). `tools.enabled = false` is a hard plain-text mode: no tool definitions are sent to the provider and no tool handler is exposed for the turn. When you do enable tools on smaller local models, keep a positive `agent_max_iterations` so malformed or repetitive tool calls terminate predictably. ### Deferred tools By default a request carries only the tools a typical turn needs. The long tail — 32 builtins: audio generation, project and skill administration, `browser`, `x_search`, `http_request`, `subagents`, the Image Flows tools (`flow_list`, `flow_run`, `flow_publish`, `flow_get`, `flow_create`, `flow_update`), and a few more — is left out; the system prompt lists each by name with a one-line summary under "Tools that must be loaded first", and so does the `tool_search` tool. The model calls `tool_search` to load the ones a task needs, and they stay loaded for the rest of the session (a reset starts lean again). On a stock gateway a request carries 40 tool schemas instead of 71. The spreadsheet/document builders and the git tools stay loaded: with them one load away the model reached for the shell instead. Reading a skill with `skill_view` also loads the tools that skill lists in `requires_tools`. Policy still applies: a tool the session may not use is neither listed nor loadable. A surface narrowed by an allowlist (an agent's `tools.allow` or `profile`, a cron job's tools) defers nothing. To send every tool on every request, as before: ```toml [tools] defer_loading = false ``` `agentos context` shows what a request carries with the current setting. ### Parallel tool calls When a model has several tool calls that do not depend on each other, issuing them in one response saves a full provider round trip per extra call; the runtime already runs them concurrently. By default AgentOS asks for this with `parallel_tool_calls: true` on the providers whose API is known to accept the field (api.openai.com and OpenRouter); every other OpenAI-compatible endpoint (OpenCAP, Bankr, Surplus, DeepSeek, Zhipu, Gemini-compatible, Ollama, local servers) gets nothing, and Anthropic already allows parallel tool use unless told otherwise. The system prompt's tool section carries the matching instruction. To send nothing, as before: ```toml [tools] parallel_calls = false ``` ### Loop guard A model can get stuck calling the same tool with the same arguments and getting the same answer back, or going back and forth between two calls. Each of those calls succeeds, so nothing else stops the turn until its iteration budget runs out. The loop guard watches every turn for that and acts in two steps: 1. **Warn.** Once a call has returned the same result three times, or two calls have alternated six times, a short `[Loop check]` note is appended to that tool result so the model reads it next to the output. 2. **Block.** A call that has already returned the same result four times (or that would stretch an alternation with no new results to eight calls) is not run: every call of that batch gets a result saying it was not run and why, and the model is asked to reassess. If the model proposes a repeat again in the same turn, the turn ends with the error code `loop_detected` and a message for the user. Only repeats that produce nothing new count: a call whose result changed (a log that grew, a file that was edited) starts over, and a successful file edit or command resets the count of every other call. Status polls (`process` poll/log, `*_status` tools, child-session status) get a much larger allowance before they are refused. The guard starts from zero on each new message, so asking for the same action again is never blocked by an earlier turn; the "same call failed again" streak (`tool_failure_loop_block_threshold`) resets on a new message too. To keep the old behaviour — decisions are only written to the turn call log: ```toml [tools] loop_guard = "observe" # default "enforce" ``` ### Provider retries Rate limits, overloads and transport blips are retried on the same model, bounded by a count and a wall-clock budget; a repeated timeout may compact the context once. Top-level keys: - `agent_max_provider_retries` (default `6`): same-model retries of one provider call. - `agent_retry_budget_seconds` (default `90`): seconds those retries may spend, counting the waits and the failed attempts (each attempt at most 10 s) from the first failure. The first retry is always made unless its wait alone is longer than the budget. `0` leaves only the count. - `agent_timeout_context_recovery` (default `true`): after a timed-out request was retried and timed out again, compact older context once and retry, when the request is large (at least half of what preflight compaction lets a request grow to); otherwise fail over to the next model, or fail. ```toml agent_max_provider_retries = 6 agent_retry_budget_seconds = 90 agent_timeout_context_recovery = true ``` See [Providers and Models — Retrying transient failures](https://useagentos.dev/docs/core/providers-and-models#retrying-transient-failures). ### Repetitive output guard A response that degenerates into the same line, paragraph or phrase over and over is cut after the first repeated copy, its provider stream is closed, and it is continued once; a second loop ends the turn with `repetition_detected`. On by default with conservative thresholds; see [Providers and Models — Repetitive Output Guard](https://useagentos.dev/docs/core/providers-and-models#repetitive-output-guard) for how it decides. To turn it off: ```toml [llm.repetition_guard] enabled = false ``` ## Prompt Cache Configuration Controls prompt prefix caching for LLM providers that support it (Anthropic, OpenAI, DeepSeek, OpenRouter, etc.): ```toml [prompt_cache] mode = "auto" # "auto" | "on" | "off" ``` - `auto` (default): Enables prompt caching when the active provider and model support prefix caching. - `on`: Forces prompt caching on. - `off`: Disables prompt caching. Environment variable override: ```sh export AGENTOS_CACHE_MODE="auto" # auto | on | off ``` > [!NOTE] > The legacy `prompt_cache.enabled` key and `AGENTOS_CACHE_ENABLED` environment variable are deprecated and mapped automatically to `mode` (`on`/`off`) with a deprecation warning. ## Router Configuration Router modes: | Mode | Use when | | --- | --- | | `recommended` | You want the selected provider's default routing profile. | | `openrouter-mix` | You want OpenRouter mixed-model defaults. | | `disabled` | You want one configured provider/model for every turn. | Commands: ```sh agentos configure router --router recommended agentos configure router --router openrouter-mix agentos configure router --router disabled ``` Router-supported provider profiles depend on the installed build and configured provider. Read [Pilot Router](https://useagentos.dev/docs/core/features/pilot-router) before using direct model runs for evaluation. For what the four text tiers (`c0`–`c3`) mean and how a turn is assigned to one, see [Model Tiers](https://useagentos.dev/docs/core/features/pilot-router#model-tiers). ### Router strategy Independent of the mode above, `agentos_router.strategy` picks how the router classifies each turn: | Strategy | Default | Behavior | | --- | --- | --- | | `pilot-v1` | Yes | English-optimized local ML router: an AgentOS-native, self-trained model (MiniLM embeddings + ONNX inference). Decides on-device with no LLM call and nothing leaves the machine. The bundle ships in the wheel under `src/agentos/agentos_router/models/pilot_v1/`; when it's missing (e.g. a source checkout without `git lfs pull`) the strategy tags the decision `pilot_unavailable` and routes the turn to the default tier (c1). Runtime deps are `numpy`/`onnxruntime`/`tokenizers` (in the `recommended` and `ml-router` extras); a minimal install without them degrades the same graceful way. Tunable via the `[agentos_router.pilot]` sub-table below. See [Pilot Router](https://useagentos.dev/docs/core/features/pilot-router#the-pilot-strategy) for status and upgrade notes. | | `llm_judge` | No | Each turn is classified by a small LLM judge call instead of the local ML bundle. See "Local judge" below. | | `jev` | No (experimental) | Each turn is classified by one call to typesafe.ai's Jev "System One" classifier. Sends the current turn text to typesafe.ai; returns a calibrated probability that feeds the confidence gate plus a `high_risk` score that floors destructive / production requests at c3. Requires `TYPESAFE_API_KEY`; a missing key, HTTP error or timeout degrades to the default tier with `jev_unavailable` telemetry. Tunable via the `[agentos_router.jev]` sub-table below. See [Pilot Router](https://useagentos.dev/docs/core/features/pilot-router#the-jev-strategy). | ```toml [agentos_router] strategy = "pilot-v1" # default; or "llm_judge", or "jev" (experimental) ``` ### Effort by tier A turn the router sends to a cheap tier also runs with less reasoning: when the thinking level is the router's own pick (the shipped tier table's level, or the pilot controller's per-turn choice), `c0` turns run at most at `low` and `c1` turns at most at `medium`; `c2`, `c3` and the image tier keep their configured level. A level is only ever lowered, never raised, and the model choice does not change. It does not apply when `[llm] thinking` is set, when an explicit model overrode the route, when the user pinned a route or a model with router control, or when `[agentos_router.tiers.<tier>] thinking_level` is set to something other than the shipped value. Config files store the whole tier table, so a level equal to the shipped one cannot be told apart from a hand-written one; use `effort_by_tier = false` to keep it. Only providers with a thinking-level concept are affected (Anthropic effort, OpenAI reasoning effort, OpenRouter `reasoning.effort`). Each lowered turn logs `turn_runner.effort_by_tier`. To keep the tier's level on every turn: ```toml [agentos_router] effort_by_tier = false ``` Jev settings live in their own sub-table (all fields optional; defaults shown): ```toml [agentos_router.jev] # api_key = "..." # literal key; prefer the env var below api_key_env = "TYPESAFE_API_KEY" # env var consulted when api_key is unset base_url = "https://api.typesafe.ai" model = "jev-latest" input_max_chars = 4000 # min 1000; the turn is head/tail truncated high_risk_threshold = 0.7 # 0..1; high_risk >= this floors the turn at c3 # timeout_seconds = 8.0 # unset: derived from routing_timeout_seconds short_circuit_enabled = true # greetings/acks skip the API call agentic_floor_enabled = false # true: tool-bearing turns never go below c1 ``` `api_key` is redacted on every public surface (`agentos config get`, the Web UI, RPC) and is **never written to `config.toml` when it equals `$TYPESAFE_API_KEY`** — the wizard stores the key in the env store and leaves the config pointing at `api_key_env`. Router runtime dependencies (`onnxruntime`, `numpy`, `tokenizers`) stay in the `recommended` / `ml-router` extras rather than the core install: a minimal install without them does not fail — the router degrades to the default tier and emits `pilot_unavailable` telemetry. The supported strategies are also selectable from the Mode dropdown in onboarding (Web UI wizard and CLI), a four-option selector: **Local ML — English-optimized (Pilot)** (`pilot-v1`, the default), **Smart routing (LLM-based)** (`llm_judge`), **Jev cloud classifier (typesafe.ai, experimental)** (`jev`), or **Off**. The legacy **Smart routing (on-device)** (`v4_phase3`) option is no longer offered. The "Judge model" field only appears for the LLM-based strategy; the "Pilot safety net" field only appears for the Pilot strategy; the "TypeSafe API key" field only appears for the Jev strategy. #### Provider-switch profiles When onboarding switches to another LLM provider, AgentOS saves a profile for the provider being left and restores it when you return. Profiles live under `[provider_profiles]` in `config.toml`. A profile holds only what belongs to that provider: - the active model and the non-secret connection settings — `base_url`, `proxy`, `api_key_env`, `max_tokens`, `thinking`, and provider routing preferences; - the provider's router slice — whether the router is enabled, its tier profile, any tiers you authored yourself, and the Smart Routing judge target (`judge_model`, `judge_provider`, `judge_base_url`). Install-wide router settings are deliberately **not** part of a profile: `strategy`, `default_tier`, `rollout_phase`, `auto_thinking`, the Pilot thresholds and the judge short-circuit tuning all stay on `[agentos_router]`. Retuning any of them while another provider is active is kept, not reverted by the next switch. Tier tables that AgentOS wrote itself — the shipped per-provider defaults, or the pinned tiers of a local provider — are not stored in the profile. They are re-derived when you switch back, so upgrading AgentOS still moves you onto the current recommended models. Tiers you edited yourself are stored verbatim and restored unchanged. Passing an explicit model when you switch back always wins over the remembered one, and a local provider's tiers are re-pinned to it. Credentials are never copied into a profile: neither a literal `api_key` nor a local `judge_api_key`. Returning to a provider you configured with a literal key asks you to re-enter it. Use `api_key_env` for credentials you want to survive a provider switch. A profile is only saved for a provider you actually configured, and a profile that no longer parses is dropped on load rather than blocking gateway startup. #### Upgrading from v4_phase3 Historical onboarding persisted `strategy = "v4_phase3"` explicitly in `~/.agentos/config.toml`. The default has since flipped to `pilot-v1`, so on the next config load AgentOS **automatically migrates** any config still pinning `v4_phase3`: - the strategy is rewritten to `pilot-v1`; - the original file is backed up verbatim next to it as `config.toml.backup.<timestamp>` (mode `0600`; like the config itself, a sensitive path an agent's shell and file tools cannot read); - the flip is logged, and the rewrite is idempotent (a config already on `pilot-v1` is left untouched, with no backup). There is no way to keep `v4_phase3` in config — the legacy engine and its model bundle were removed from the tree (Phase C), onboarding no longer offers it as a Mode option, and a value that bypasses the file migration (e.g. an env override) normalizes to `pilot-v1` at config load. #### Pilot strategy settings When `strategy = "pilot-v1"`, the optional `[agentos_router.pilot]` sub-table tunes the Pilot router: ```toml [agentos_router] strategy = "pilot-v1" [agentos_router.pilot] # Under-routing safety-net floor (0.0–1.0). The effective cutoff is # max(safety_net_threshold, router.confidence_threshold), so a value below the # confidence threshold has no effect. Default 0.5. safety_net_threshold = 0.5 # Override the Pilot artifact directory. Defaults to the bundled # `models/pilot_v1/` root; set this to point at a bundle elsewhere on disk. # pilot_artifact_dir = "~/pilot_v1" ``` ### Local judge (Ollama / LM Studio) This section applies only when `agentos_router.strategy = "llm_judge"` — the default `pilot-v1` local strategy makes no LLM call and have no judge to configure. With the `llm_judge` strategy, the router classifies each text turn with a small LLM judge. Instead of a cloud model you can point the judge at a local OpenAI-compatible endpoint (Ollama, LM Studio, llama.cpp, vLLM) — no cloud credentials required, and zero bytes added to the package. In the interactive router setup, pick **Local endpoint** for the judge model and supply the base URL (for example `http://localhost:11434/v1`) and the model name. Onboarding validates the URL shape and runs one test classification call to verify the endpoint is reachable. Equivalent config (`[agentos_router]` in `agentos.toml`): ```toml [agentos_router] strategy = "llm_judge" judge_model = "llama3" judge_base_url = "http://localhost:11434/v1" # judge_api_key is optional — local endpoints usually accept any token; a # placeholder is used when unset. It is redacted in logs. judge_api_key = "" ``` `judge_base_url` only takes effect when `judge_model` is set. When it is, the judge client is built against that endpoint and the usual "judge provider must match `llm.provider`" constraint is bypassed. The resolved judge is logged at boot (`router.judge_resolved` with `source="local"` and the base URL) and reported by `agentos doctor`. ## Search Configuration Inspect search providers: ```sh agentos search list agentos search status agentos search query "AgentOS release notes" ``` Configure search: ```sh agentos configure search --search-provider duckduckgo agentos configure search --search-provider brave --api-key-env BRAVE_SEARCH_API_KEY agentos configure search --search-provider tavily --api-key-env TAVILY_API_KEY ``` Runtime-supported search providers in this build include Brave Search, DuckDuckGo, and Tavily Search. Additional provider metadata may be present for future or not-yet-runtime-supported integrations. Read: [Web Search](https://useagentos.dev/docs/core/search) ## X (Twitter) Search Configuration `x_search` is a separate tool, not a `web_search` backend: xAI runs the search against X's post index and returns a synthesized answer with citations. Credentials come from either a SuperGrok / X Premium+ login or an xAI API key, and the login wins when both exist: ```sh agentos auth login xai agentos auth status ``` ```sh agentos onboard catalog x-search agentos configure x-search --api-key-env XAI_API_KEY agentos configure x-search --x-search-model grok-4.5 ``` | Key | Default | Notes | | --- | --- | --- | | `x_search.enabled` | `true` | Off hides the tool even when a key is present. | | `x_search.model` | `grok-4.5` | Any Grok model with server-side `x_search` access. | | `x_search.base_url` | `https://api.x.ai/v1` | Must be HTTPS; a rejected value falls back to the default. | | `x_search.api_key` | `""` | Pasted key. Persisted to config like other capability keys. | | `x_search.api_key_env` | `XAI_API_KEY` | Read at call time, so no restart after changing the variable. | | `x_search.reasoning_effort` | `""` | `low`, `medium`, `high`, `xhigh`, or empty for the model default. | | `x_search.timeout_seconds` | `180.0` | One attempt. Range 30-300. | | `x_search.total_timeout_seconds` | `300.0` | Whole call including retries. Range 30-600. | | `x_search.retries` | `2` | 5xx, timeout, and connection errors only. Range 0-5. | The tool is hidden from the model until a credential resolves, and its usage bills xAI directly rather than appearing in `agentos cost`. Read: [X (Twitter) Search](https://useagentos.dev/docs/core/x-search) ## Browser automation ```toml [browser] enabled = true headless = true cdp_port = 0 attach_confirmed = false allowed_domains = [] restrict_evaluate = false ``` | Key | Default | Notes | | --- | --- | --- | | `browser.enabled` | `true` | Off hides the tool even when the binary is installed. | | `browser.headless` | `true` | Managed mode; `false` opens a visible window. | | `browser.binary_path` | `""` | Optional explicit path to `agent-browser`; otherwise found on `PATH`, then in the usual npm global directories (nvm, fnm, Volta, pnpm, Bun, Homebrew, `~/.npm-global`). | | `browser.cdp_port` | `0` | `0` = managed. `>0` = attach to your Chrome's debug port. Localhost only; a URL is never accepted. | | `browser.attach_confirmed` | `false` | Must be `true` for attach mode to run — it can drive signed-in sessions. | | `browser.allowed_domains` | `[]` | `[]` = open web (SSRF still blocks private ranges). A non-empty list bounds navigation in AgentOS and in the engine. Entries are hostnames and cover subdomains — `["example.com"]` allows `example.com` and `www.example.com`, but not `evil-example.com`. A leading `.` or `*.`, a scheme, a port, userinfo and a path are accepted and reduced to the hostname, so `https://example.com/x` and `*.example.com` mean the same as `example.com`. An entry that cannot be reduced to a hostname is refused at config time, naming the accepted format. | | `browser.persist_profile` | `false` | `true` keeps cookies/login between sessions (written to disk). | | `browser.session_ttl_minutes` | `15` | Idle sessions are reaped after this. Range 1-1440. | | `browser.max_sessions` | `3` | Concurrent browser sessions; oldest-idle evicted. Range 1-20. | | `browser.snapshot_max_chars` | `24000` | Snapshots over this are truncated with a marker. | | `browser.dialog_policy` | `must_respond` | `must_respond`, `auto_dismiss`, or `auto_accept` for native dialogs. | | `browser.dialog_timeout_s` | `300.0` | Watchdog for an unanswered dialog. Range 1-3600. | | `browser.restrict_evaluate` | `false` | `true` blocks sensitive JS primitives in `eval` (off by default — it also blocks ordinary DOM extraction). | | `browser.allow_unsafe_evaluate` | `false` | `true` overrides `restrict_evaluate` for a trusted page. | The tool is hidden from the model until the `agent-browser` binary is installed. Read: [Browser automation](https://useagentos.dev/docs/core/features/browser) ## Channel Configuration List supported channel types: ```sh agentos channels types --json agentos channels describe slack agentos channels add telegram --name personal agentos channels status ``` Channel saves update configuration. Restart the gateway after edits: ```sh agentos gateway restart agentos channels status <name> --json ``` See [Channels](https://useagentos.dev/docs/core/channels) for details. ## MCP Configuration Use **Settings › MCP** in the Web UI for normal MCP setup. It supports live connect/disconnect controls, inline validation, OAuth authorization, and a featured Robinhood Trading preset. For scripted deployments, configure servers in TOML: ```toml [mcp] enabled = true connect_timeout_seconds = 10 [[mcp.servers]] name = "robinhood-trading" transport = "streamable_http" url = "https://agent.robinhood.com/mcp/trading" oauth = true tool_timeout_seconds = 30 [[mcp.servers]] name = "filesystem" transport = "stdio" command = "npx" args = ["-y", "@modelcontextprotocol/server-filesystem", "/srv/data"] cwd = "/srv" # stdio only; default: the gateway's own enabled = true # false keeps the definition, never connects connect_timeout_seconds = 20 # overrides mcp.connect_timeout_seconds tool_filter.include = ["read_*", "list_*"] tool_filter.exclude = ["read_secret"] ``` Per-server keys (all optional; an existing config keeps working unchanged): | Key | Default | Meaning | |---|---|---| | `enabled` | `true` | A disabled server is skipped at boot and `mcp.connect` refuses it. | | `cwd` | unset | Working directory for a `stdio` server (`~` expands). A missing directory is reported by name. | | `connect_timeout_seconds` | unset | Per-server connect timeout; unset uses `mcp.connect_timeout_seconds`. | | `tool_filter.include` | `[]` | `fnmatch` globs on the server's own tool names; empty registers every tool. | | `tool_filter.exclude` | `[]` | Globs to skip; wins over `include`. Matching is case-sensitive. | | `defer_loading` | `"auto"` | `true` keeps the server's tool schemas out of requests until `tool_search` loads them, `false` always sends them. `"auto"` defers when the server has more than `mcp.defer_tool_threshold` tools (default 8) or all MCP servers together have more than `mcp.defer_total_tool_threshold` (default 20). | `mcp.instructions_max_chars` (default 2000, `0` = none) caps the server-written `instructions` quoted in the system prompt's "Connected MCP Servers" section. All enabled servers connect concurrently at boot, and calls to one stdio server no longer queue behind each other; see [MCP Client Guide](https://useagentos.dev/docs/core/mcp#how-the-agent-sees-mcp-servers). The filter runs before registration, so a filtered tool never reaches the model or the tool registry. If a server cannot be reached at boot, or a `stdio` server's process exits on its own, the gateway reconnects it in the background after 30 s, doubling up to 10 min, logging once per failed attempt; a crashed server's tools are unregistered until it is back. `mcp.status` reports the pending retry. Manage entries from the terminal with `agentos mcp` — see [MCP Client Guide](https://useagentos.dev/docs/core/mcp). `mcp` is an operator-only setting: a stdio server is a command the gateway itself runs, so an agent's connection cannot register or enable one through a config RPC, a file edit of `[mcp]` is held until `agentos config reload`, and `mcp.connect` / `mcp.disconnect` / `mcp.oauth.*` fail for an agent's connection with `mcp.operator_required`. Settings › MCP in the console works as before. Supported transports are `stdio`, `sse`, and `streamable_http`. The MCP SDK is included in the standard AgentOS installation, so Streamable HTTP and OAuth work without installing an additional package extra. `stdio` servers are spoken to with the framing the MCP stdio transport defines: one compact JSON-RPC message per line on the subprocess's stdin and stdout. AgentOS neither sends nor expects the LSP-style `Content-Length` header, so the reference `@modelcontextprotocol/server-*` servers work unmodified. Replies are matched to their request id, so notifications a server interleaves with them are skipped rather than mistaken for a result. `sse` is the legacy HTTP+SSE transport from the 2024-11-05 spec revision; prefer `streamable_http` for new servers. On `sse`, `url` is the endpoint AgentOS opens the event stream against — the URI it POSTs JSON-RPC to is chosen by the server and announced in the stream's `endpoint` event, so there is nothing to configure for it. A relative endpoint resolves against `url`; one pointing at a different scheme or host is refused and nothing is posted to it. If the server opens the stream but never advertises an endpoint, the connection fails after `tool_timeout_seconds`. The HTTP transports accept `http://` and `https://` URLs only, and both connect through the same SSRF guard the built-in HTTP tools use. `http://localhost:PORT` and LAN-hosted servers keep working — the guard blocks cloud metadata endpoints (`169.254.169.254` and friends), which serve instance credentials and are never a valid MCP target. The check runs against the address the socket actually dials, so a short-TTL DNS name cannot answer safely for the check and with the metadata address for the connection. ### MCP tool names and results Each tool a server exposes is registered for the agent as `mcp_<tool>`, so a server's `search` tool is `mcp_search`. That short name is what tool allowlists and denylists refer to. When two servers expose a tool with the same name, the first one to connect keeps the short name and the later one is registered as `mcp_<server>_<tool>` instead of replacing it. Servers connect at startup in the order they appear in `[[mcp.servers]]`, so the first configured server wins. `<server>` is the server's `name` lowercased with every run of characters outside `[a-z0-9_]` turned into `_` (`Linear-Prod.v2` becomes `linear_prod_v2`); if two server names reduce to the same text, a `_2`, `_3` suffix keeps them apart. The gateway logs `mcp.tool_name_collision` naming the server that got the long name, and the `mcp.status` RPC lists each connected server's `tools` plus a `toolMap` from registered name to the server's own tool name. A server connected later (after OAuth, or from the MCP screen) takes whichever names are free at that moment. When a server marks a result as an error (`isError`), the call comes back to the model as a failed tool result whose message quotes the server's error text (capped). A call that exceeds `tool_timeout_seconds` fails the same way. Output from an MCP tool is written by the server, not by AgentOS, so it is handled like `web_fetch` output: wrapped in an `<untrusted source='mcp:<server>/<tool>'>` envelope and counted against the external-content result budget. OAuth access and refresh tokens are not written to `config.toml`. AgentOS keeps them in a server-scoped JSON file under the configured state directory with file mode `0600` inside a `0700` directory on POSIX systems. On Windows, the credential file inherits the current user's state-directory ACL. Removing the server from the MCP screen also clears that credential file. The file also records when the access token expires and the authorization server's metadata found at sign-in (its token endpoint may be on another host), and AgentOS refreshes the token with the saved refresh token before it expires, so a short-lived token (some servers issue ten-minute ones) keeps working without another sign-in. If the server refuses the refresh, the call fails with a message that the server needs to be signed in again, the saved tokens are dropped, and `mcp.status` reports `authenticated: false`, so Settings › MCP offers sign-in. A transport that drops after a failed request reconnects on the next tool call; until then `mcp.status` reports the server as `connected: false`. ## Memory Configuration Useful commands: ```sh agentos memory status agentos memory index agentos memory list agentos memory search "project preference" agentos memory show <path> ``` Configure embedding behavior: ```sh agentos configure memory-embedding ``` Memory can combine Markdown-backed sources with SQLite keyword and semantic indexes. The exact memory shape depends on the configured provider and local embedding support. An external memory provider (`[memory.provider]`) is asked for recall before every turn. `[memory] recall_timeout_seconds` (default `1.5`) is a hard deadline on that recall: a slower recall does not hold the turn, which goes on without it and logs `memory.recall_timeout`. The late recall is not cancelled; it finishes in the background and its result stands in on the session's next turn if that turn's recall is late too. ```toml [memory] recall_timeout_seconds = 1.5 ``` Proactive recall (`[memory.recall]`) searches the built-in memory index for the user's message before each interactive turn and adds strong matches as a fenced `## Recalled Memory` block. Its quick trigger search shares `recall_timeout_seconds`; the deep lane (a wider search plus one small-model summary, run for questions about the past) has its own deadline. Heartbeat, cron, sub-agent, inter-session, group and channel turns never run it. ```toml [memory.recall] enabled = true # proactive recall before each interactive turn mode = "escalate" # deep lane: escalate | always | off trigger_min_score = 0.65 # 0-1; how strong a trigger hit must be to inject trigger_max_hits = 3 max_injected_chars = 1800 # cap on the whole fenced block deep_timeout_seconds = 8.0 deep_max_summary_chars = 400 deep_max_results = 6 provider = "" # deep-lane model; empty inherits the session's chat model model = "" ``` Environment overrides follow the nested convention, e.g. `AGENTOS_MEMORY_RECALL__MODE=off`. With `provider` and `model` empty, the deep lane uses the model the session is chatting with this turn: the session's pinned model, else the agent's model, else a router hold, else the primary `[llm]` model. It uses the turn's own provider credentials and always runs with thinking off. If you chat with a large or slow model, set `model` to a fast one. The call is the auxiliary task `memory_recall`, so `AGENTOS_MEMORY_RECALL_PROVIDER` / `AGENTOS_MEMORY_RECALL_MODEL` and `[auxiliary.tasks.memory_recall]` override both. `[auxiliary]` applies only when no chat provider is configured. See [Memory](https://useagentos.dev/docs/core/features/memory#proactive-recall). The memory review (`[memory.nudge]`) is a short background turn that saves durable facts from the conversation: every `interval` user turns, and with `before_compaction` once more right before a proactive or manual compaction summarises a private chat. That review is bounded by `timeout_seconds`, can only add (new entries, appended notes; no replace, remove or overwrite), and is skipped when the compaction would summarise nothing (`nothing_to_compact`, decided without a model call) and for compactions forced by a full context; the compaction does not depend on what it saved. `[memory.nudge]` and `[memory.recall]` changes apply without a restart. ```toml [memory.nudge] enabled = true interval = 10 # user turns between reviews; 0 disables (both triggers) max_iterations = 6 timeout_seconds = 90.0 # also the most a manual compaction waits for its review before_compaction = true # review once before a proactive or manual compaction ``` ### Turn setup concurrency Before a turn's first model request AgentOS reads several independent things: the memory-provider recall, proactive memory recall, the session's project knowledge, the deferred tools the session has loaded, the recent transcript for the router, and on the first turn of a session the memory index warm-up. `[task_runtime] concurrent_turn_setup` (default `true`) runs them concurrently and applies the results in the same order as before, so the prompt is byte-identical either way. Set it to `false` to go back to running them one after another. ```toml [task_runtime] concurrent_turn_setup = true ``` ### Stopping a turn A turn that is streaming or between steps when it is stopped is asked to stop first: the model's stream is closed, no further request is sent and the turn ends on its own. `[task_runtime] turn_cancel_grace_seconds` (default `5`; `0` cancels at once) is how long it gets before its task is cancelled. A turn running tools is cancelled at once. Stopping it a second time while it has its grace cancels it at once. See [Sessions](https://useagentos.dev/docs/core/sessions). ```toml [task_runtime] turn_cancel_grace_seconds = 5 ``` ### Subagent lanes At most `[subagents] max_concurrent_children` (default `2`; `0` = no per-parent limit) children of one parent session run at once; further spawns wait in spawn order. An agent's own `subagents.max_concurrent_children` overrides it. Child runs (subagents, ACP harness runs) have a pool of their own on top of the shared one: `[task_runtime] max_nested_concurrency` (default: the value of `max_concurrency`) slots across all parents that only children use. A child of a parent whose turn is still running takes a nested slot first, so a parent waiting on its children cannot starve them; any other child takes a shared slot first and a nested one when the shared slots open to children are taken. In the shared pool a child always leaves `[subagents] subagent_reserved_slots` (default `2`, at most `max_concurrency - 1`) free, so a user's own message does not wait behind children. A child keeps the slot it got until it ends. Whatever the per-parent limit and however deep the nesting, running turns never exceed `max_concurrency + max_nested_concurrency`. See [Sessions](https://useagentos.dev/docs/core/sessions). ```toml [task_runtime] max_concurrency = 4 # max_nested_concurrency = 4 # default: max_concurrency [subagents] max_concurrent_children = 2 # subagent_reserved_slots = 2 # shared slots children never take ``` `max_nested_concurrency`, `turn_cancel_grace_seconds`, `max_concurrent_children` and `subagent_reserved_slots` are read when the gateway starts; a change takes effect after a restart. ### Interrupted turns A turn that a gateway restart or crash cut short is resumed on the next boot from what its transcript shows; one whose last tool calls have no recorded result resumes with read and status tools only. `[task_runtime] resume_interrupted_turns` (default `true`) controls this; `false` only reports interrupted turns (a note in the session, `/ready` `turn_recovery`, `agentos doctor`). See [Gateway: interrupted turns](https://useagentos.dev/docs/core/gateway#interrupted-turns). ```toml [task_runtime] resume_interrupted_turns = true ``` Read: [Memory](https://useagentos.dev/docs/core/features/memory) ## Context Compaction When a session's request nears the model's context window, the oldest history is folded into one summary exchange. The trigger is `preflight_compact_ratio` (default 0.85) of the context window, or the provider's request budget when that is tighter. ```toml [compaction] summary_timeout_seconds = 45.0 # bound on the summary call (auxiliary task "compaction") proactive = true # compact between turns, in the background proactive_ratio = 0.70 # ...once the history reaches 70% of the trigger proactive_idle_seconds = 20 # ...after the session has been idle this long estimate_calibration = true # scale the size estimate by what providers report ``` - **Proactive compaction.** After a turn ends with the history at `proactive_ratio` of the trigger or more, AgentOS compacts the session in the background, so the next turn does not wait for the summarizer. The job waits until the session has been idle for `proactive_idle_seconds` (default 20, 0 = at once) before it calls the summarizer, so a quick follow-up does not pay for a summary it throws away. A turn that starts first wins: the background result is dropped and the check runs again when that turn ends. When a turn cancels a summary already in progress, the wait doubles for that session (up to 300 s) until a job completes. A job that has already persisted is never cancelled; one whose session was reset or truncated meanwhile is skipped quietly. Subagent and cron sessions are never compacted this way. The in-turn check stays as the safety net. `proactive = false` turns the background job off. - **Estimate calibration.** The request size is estimated as characters / 4, which over-counts against what providers bill. Per provider and model, AgentOS keeps a running ratio of the provider's reported input tokens to its own estimate and, after two calls, scales the estimate by it (clamped to 0.7-1.25), so compaction does not fire early. Usage the provider marks as estimated and requests carrying images or documents are not counted. `estimate_calibration = false` uses the raw estimate. - **Summary format.** The summary has fixed sections: Goal, Constraints and preferences, Done, In progress, Blocked, Key decisions, Next steps, and Critical context (exact paths, commands, numbers and IDs). A later compaction hands the previous summary to the summarizer as the base to revise, so finished work stays under Done instead of being summarized away. Below the model's text AgentOS appends the files the compacted tool calls read (`read_file`, `read_spreadsheet`, `pdf`) and modified (`write_file`, `edit_file`, `apply_patch`), merged with the previous summary's lists and capped to the newest 20 of each. Shell commands are not parsed for paths. The in-turn, the proactive and the manual (`/compact`, `sessions.compact`) compaction all write this format. A manual compaction revises the newest stored summary, and from then on only the revision is replayed, not the two side by side; if its summarizer call fails, the earlier summary is kept and replays on its own. Summaries stored before this behaviour existed replay as they always did. - When the summarizer fails or times out, a deterministic digest bounded to an eighth of the context window is used instead, so a compaction still shrinks the history. ## Auxiliary Model Not every provider call belongs to a turn. Analysing a document the user attached and describing an image are work AgentOS initiates on its own behalf. These run against the `[auxiliary]` model rather than the agent's: ```toml [auxiliary] provider = "" # empty = reuse [llm] model = "" # empty = reuse [llm] timeout_seconds = 120.0 [auxiliary.tasks.vision] model = "openai/gpt-4o-mini" ``` Point it at something cheap when these tasks do not need your main model. Tasks currently in use are `document`, `vision`, `session_title`, `suggest_next`, `compaction` (the in-turn context summary; it defaults to the router's cheapest text tier and is bounded by `[compaction] summary_timeout_seconds`) and `memory_recall` (proactive recall's deep lane, which inherits the chat model rather than `[auxiliary]`; see [Memory Configuration](#memory-configuration)). A task with a capability requirement wants its own entry, since a text-only model cannot describe an image. Resolution runs highest-first: `AGENTOS_<TASK>_MODEL` (for example `AGENTOS_VISION_MODEL`), then `[auxiliary.tasks.<task>]`, then a capability-aware default such as the router's image-capable tier, then `[auxiliary]`, then `AGENTOS_LLM_MODEL`, then `[llm]`. An install that sets none of this keeps using the `[llm]` model exactly as before. These calls are billed to the session that triggered them and are additionally tracked under an `aux:<task>` scope, so `agentos cost` can separate what the agent spent answering from what the runtime spent on its own. ### Session titles A new chat session is named from its first message — whether it started in the web console, the desktop app or a channel such as Telegram: the `session_title` task asks the auxiliary model for a 3–6 word title in the user's language, and the result lands in the session's `display_name`. With no task override it prefers the router's cheapest text tier (`c0`, else `c1`) so titling never waits on a slow thinking model, where the web console, the desktop app and `agentos sessions` all read it. It only names sessions that still carry a placeholder (`WebChat` or the short id); a name you typed, or one the agent set with `session_rename`, is never overwritten. The title is generated off the turn path, so sending is never slowed down, and open clients receive a `sessions.changed` event with `reason = "renamed"` when it lands. ```toml [sessions] auto_title = true # AGENTOS_SESSIONS_AUTO_TITLE=false to disable auto_title_timeout_seconds = 30.0 [auxiliary.tasks.session_title] model = "openai/gpt-4o-mini" # or AGENTOS_SESSION_TITLE_MODEL ``` If the model is unreachable the first clause of the message is used instead, so a session still gets a readable name. ### Suggested next prompt When a turn finishes, the chat input in the web console, the desktop app and `agentos chat` shows the message you are most likely to send next as grey placeholder text. `Tab` takes it into the input and `Enter` sends it; typing anything else ignores it. Clients ask for it with the `chat.suggestNext` RPC once they see the turn end, and the `suggest_next` task answers from the last user message and reply, preferring the router's cheapest text tier like session titles do. A turn that errored or was aborted gets no suggestion and costs no call, and the answer is cached per reply, so several clients open on one session share a single call. There is no fallback: if the model is unreachable or has nothing useful to offer, the normal placeholder stays. ```toml [sessions] suggest_next = true # AGENTOS_SESSIONS_SUGGEST_NEXT=false to disable suggest_next_timeout_seconds = 15.0 [auxiliary.tasks.suggest_next] model = "openai/gpt-4o-mini" # or AGENTOS_SUGGEST_NEXT_MODEL ``` ## ACP Coding Harnesses `[acp]` controls how AgentOS drives external coding harnesses (Claude Code, Codex, Gemini CLI, Cursor, ...) over the Agent Client Protocol. The defaults work without any `[acp]` table; nothing starts until the agent spawns an ACP session or you run `agentos acp run`. ```toml [acp] enabled = true default_agent = "claude" allowed_agents = ["*"] permission_mode = "ask" non_interactive_permissions = "fail" approval_timeout_s = 900 turn_timeout_s = 0 max_concurrent = 8 # state_dir = "~/.agentos/state/acp" isolate_codex_home = true install_missing_adapters = true stream_delivery = "live" allowed_cwds = [] [acp.agents.cursor] command = "agent" args = ["acp"] env = {} ``` | Key | Default | Meaning | | --- | --- | --- | | `enabled` | `true` | `false` refuses ACP spawns and `agentos acp run`. | | `default_agent` | `"claude"` | Harness used when `sessions_spawn(runtime="acp")` names none. | | `allowed_agents` | `["*"]` | Harness ids the agent may launch; `*` = any. | | `permission_mode` | `"ask"` | Who answers harness permission prompts: `ask` (approval queue), `approve-reads`, `approve-all`, `deny-all`. | | `non_interactive_permissions` | `"fail"` | `ask` with nobody to answer: `fail` the turn or `deny` the request. | | `approval_timeout_s` | `900` | Seconds an `ask` prompt waits before it is rejected. | | `turn_timeout_s` | `0` | Wall-clock limit per harness turn; `0` = none. | | `max_concurrent` | `8` | Live harness sessions per gateway (1-64). | | `state_dir` | unset | Overrides `<state>/acp` (session records, leases, logs, Codex home, worktrees). | | `isolate_codex_home` | `true` | Give Codex its own `CODEX_HOME` with your login copied in and the session directory trusted. | | `install_missing_adapters` | `true` | Allow the `npx -y` / `uvx` adapter download on first use. | | `stream_delivery` | `"live"` | `live` streams the harness's text into the child session as it arrives; `final_only` sends the answer once at the end. | | `agents.<id>.command` / `args` | unset | Replace the built-in launch command for that harness, or add a new harness id. | | `agents.<id>.env` | `{}` | Extra environment for that harness only. | | `allowed_cwds` | `[]` | Extra directories a harness may use as `cwd`; otherwise `cwd` must be inside the agent workspace or a managed worktree. The workspace suits read-only work in a read-only `harness_mode`; list a project here for a harness that writes (`agentos config set acp.allowed_cwds '["~/Code/my-app"]'`, which replaces the whole list). | ```sh agentos config set acp.permission_mode approve-reads agentos config set acp.default_agent codex agentos acp doctor ``` Changes apply after a gateway restart. Read: [ACP Coding Harnesses](https://useagentos.dev/docs/core/acp-agents) ## Sandbox and Permissions Inspect or change posture: ```sh agentos sandbox status agentos sandbox on agentos sandbox full agentos sandbox bypass agentos sandbox reset ``` Single-shot automation permissions: ```sh agentos agent --permissions restricted -m "Read the repo and summarize it" agentos agent --permissions full -m "Make a local patch and run tests" ``` For unattended automation that must stay inside a workspace: ```sh agentos agent \ --workspace /path/to/project \ --workspace-lockdown \ --scratch-dir /path/to/project/.scratch \ -m "Investigate and propose the smallest fix" ``` Read: [Tools, Approvals, and Sandbox](https://useagentos.dev/docs/core/tools-and-sandbox) ## Safety Configuration Controls prompt-ingress safety scanning and untrusted workspace containment: ```toml [safety] wrap_untrusted_workspace = true injection_scan_mode = "report" # "report" | "enforce" | "off" ``` - `wrap_untrusted_workspace` (default `true`): Wraps files read from untrusted workspace directories with safety bounding markers to mitigate prompt-injection framing in workspace files. - `injection_scan_mode` (applied to bootstrap workspace files, not all ingress): - `report` (default): Scans those files and logs detected patterns without changing the content; the turn still runs. - `enforce`: Redacts matched content from untrusted workspace files before it reaches the prompt; the turn still runs. - `off`: Disables prompt-injection scanning. `[safety]` is TOML-only; there is no environment-variable override for these keys. ## Spend Budgets Money ceilings with a hard stop, so a runaway loop or subagent fan-out cannot burn an unbounded amount overnight. Every value is US dollars of estimated model spend (or the provider-billed figure, when the provider reports one). ```toml [budgets] enabled = true # master switch; keeps the numbers but suspends enforcement when false session_limit = 5.0 # hard stop once one session reaches this session_warn = 4.0 # one-shot warning for that session daily_limit = 50.0 # hard stop for gateway-wide spend on the current UTC day daily_warn = 40.0 # one-shot warning for that day turn_reservation = 0.25 # headroom held for each in-flight turn (0 disables) [budgets.agent_daily_limit] main = 20.0 [budgets.channel_daily_limit] telegram = 10.0 ``` `agent_daily_warn` and `channel_daily_warn` take the same per-key shape as their `*_limit` counterparts. - Nothing is enforced by default: every ceiling is unset on a fresh install, and `enabled = true` only means "apply the ceilings you have configured". - A turn that starts at or above a hard limit is refused before any provider call, with a `budget_exceeded` error naming the scope and the number. The refusal is recorded in the session transcript, and the user message that triggered it is rolled back rather than left as a reply-less turn. - Ceilings are re-checked between iterations *within* a turn as well, so a single turn with a long tool loop stops at the ceiling instead of running to completion past it. - A `*_warn` threshold does not stop the turn. It surfaces a `budget_warning` once per session (session scope) or once per UTC day (daily scopes), so a long session does not repeat the same alert every turn. - A warn threshold above its own hard limit is rejected at load time — it could never fire. So are two spellings of one scope key (`default` and `main`, `Telegram` and `telegram`), which would otherwise silently drop one of the two numbers. - Spend is tracked in a ledger persisted at `~/.agentos/state/spend_ledger.db` (keyed per UTC day for the daily scopes, per session for the session scope), so a ceiling survives a gateway restart — a runaway overnight loop cannot be reset by a crash-and-respawn. - Subagent turns run through the same gate, and their spend is attributed to the parent agent id, so a fan-out is bounded by the agent and daily ceilings rather than multiplying past them. - Admission *reserves* as well as checks. Spend is only recorded as a turn burns tokens, so children dispatched at the same moment would otherwise all read the same pre-fan-out total and all clear the same ceiling. Each admitted turn holds `turn_reservation` dollars (default `0.25`) against every scope its session bills to, and the hold is released the moment the turn ends — including on error, cancellation, and an abandoned turn. It therefore bites only within that much of a limit, and only on turns that overlap: a ceiling is never shrunk for turns that run one after another. Set `turn_reservation = 0` to reserve nothing. The re-check *inside* a turn weighs recorded spend only, so a turn is never stopped by its own reservation. - Changing a ceiling requires a gateway restart to take effect. `budgets.*` is not on the live-reload allowlist, so both `agentos config` and the Web UI report `restart_required` when you change one. Restart before relying on a new ceiling — a limit written while the gateway is running is not yet enforcing. - Enforcement fails open. If the ledger cannot be read or written, the shortfall is logged (`usage_tracker.ledger_*`) and turns keep running: a budget check is never the reason a gateway stops working. Reads reconcile the persisted row against in-process accounting by taking the larger of the two, so a dropped write cannot quietly retire a ceiling within a run. `[budgets]` is TOML-only; there is no environment-variable override for these keys. An agent's connection cannot change the ceilings through any config RPC (see [Editing the file while the gateway runs](#editing-the-file-while-the-gateway-runs)). ## Gateway Binding Foreground: ```sh agentos gateway run --listen 127.0.0.1 --port 18791 ``` Managed: ```sh agentos gateway start --json agentos gateway status # shows both the CLI and running-gateway versions agentos gateway stop agentos gateway restart ``` `agentos gateway status` reports the installed CLI version and the running gateway's version; when they differ it appends a mismatch line advising a restart (typically after `agentos upgrade --no-restart` or a manual package upgrade). Bind precedence: 1. `--listen` 2. `--bind` 3. `--bind-mode` 4. `AGENTOS_LISTEN` 5. `AGENTOS_GATEWAY_HOST` 6. `[gateway] bind` 7. config host 8. `127.0.0.1` ```toml [gateway] bind = "loopback" # loopback | lan | tailnet | custom; unset = use `host` public_origin = "" # e.g. "https://agent.example.com" for a public console config_reload = true # apply edits to this file without a restart ``` | Key | Default | Meaning | | --- | --- | --- | | `gateway.bind` | unset | `loopback` = `127.0.0.1`; `lan` = `0.0.0.0` (token auth required); `tailnet` = the `tailscale ip -4` address plus `127.0.0.1`, never a wildcard (startup fails when Tailscale is unavailable); `custom` = the `host` key. Unset keeps `host` in charge. `--listen` / `--bind` count as `custom`. Restart to apply. | | `gateway.public_origin` | `""` | The browser origin a public deployment is opened at. Joins the origin allowlist and the `Host` guard. Required before the Control UI starts on a specific public address. Restart to apply. | | `gateway.config_reload` | `true` | Watch the config file; see [Editing the file while the gateway runs](#editing-the-file-while-the-gateway-runs). | Browser access follows one origin policy on every bind (allowlist, then private same-origin, then a loopback origin on a local socket); see [Gateway → Browser origins](https://useagentos.dev/docs/core/gateway#browser-origins). `cors.allowed_origins` entries join that allowlist; its old default `["*"]` adds nothing, and CORS never answers `*`. Environment overrides: `AGENTOS_GATEWAY_GATEWAY__BIND`, `AGENTOS_GATEWAY_GATEWAY__PUBLIC_ORIGIN`, `AGENTOS_GATEWAY_GATEWAY__CONFIG_RELOAD`. ## Gateway Control The gateway can restart itself in place on request (`/restart` in a chat, the `gateway.restart` RPC, `agentos gateway restart`; see [Gateway](https://useagentos.dev/docs/core/gateway#when-to-restart)). Who may ask depends on the surface: ```toml [gateway_control] chat_restart = false # /restart from paired channels and the agent's gateway tool ``` - Operators on a Control surface — the web console, the desktop app, the CLI — can always restart the gateway. They already hold `updates.apply` and `config.patch`, which are strictly more powerful. - A paired channel sender (`/restart` on Telegram, Discord, Slack, …), a connection bound to an agent, and the agent's own `gateway` tool are refused unless `chat_restart` is `true`. Any paired sender may restart once it is; there is no owner or admin tier. `chat_restart` defaults to `false`. Changing it requires one restart of the gateway (`agentos gateway restart`, or `/restart` from the web console), after which chat restarts are accepted. `gateway_control` is an operator-only setting: no agent connection (bound or unbound) may write it through a config RPC, and a file edit of it is held like the trading limits (see [Editing the file while the gateway runs](#editing-the-file-while-the-gateway-runs)), so an agent cannot switch on its own restart. Environment override: `AGENTOS_GATEWAY_GATEWAY_CONTROL__CHAT_RESTART=true`. In-place restart is not available on Windows. ## Scheduler ```toml [scheduler] startup_agent_delay_seconds = 120 # 0 = run missed agent jobs at boot ``` Cron jobs missed while the gateway was down are caught up at boot (at most 5, staggered over 10 seconds). Missed agent jobs — an agent turn, or a main-session system event — wait `startup_agent_delay_seconds` first so they do not compete with channel start-up for the model; reminders and script jobs run at once. The wait is stored as the job's next run time, so `agentos cron list` shows it. Restart the gateway after changing it. Environment override: `AGENTOS_GATEWAY_SCHEDULER__STARTUP_AGENT_DELAY_SECONDS=300`. See [Scheduling](https://useagentos.dev/docs/core/scheduling#sleep-restarts-and-clock-changes). ## Update Notifications On commands that connect to the gateway, the CLI checks PyPI at most once every 24h and, if a newer release of `use-agent-os` exists, prints a one-line notice on stderr suggesting `agentos upgrade`. Similarly, the Web UI queries the gateway on connection and, if an update is available, shows an **Update available** badge in the status menu and a dismissible notice linking to Settings › Updates. The check is silent on failure and is suppressed in CI, on non-interactive CLI runs (no TTY), or via environment flags. ```toml [updates] notify = true # set false to silence the "new release available" notices ``` `updates.notify` defaults to `true`. Set it from the setup UI (Finish step → Updates), with `agentos config` (a `config.patch` on `updates.notify`), or by editing the config file directly. The state file `~/.agentos/state/update_notice.json` tracks the last check times (namespaced per surface, e.g. `cli`, `webui`) for throttling; delete it to force a re-check. To silence the notices for a single run/session without changing config, set `AGENTOS_NO_UPDATE_NOTICE=1`. ## Observability AgentOS provides Prometheus metrics exposition, OpenTelemetry (OTLP) trace export, and automatic log retention pruning under the `[observability]` table: ```toml [observability] metrics_enabled = true metrics_path = "/metrics" otlp_enabled = false otlp_endpoint = "http://localhost:4318" otlp_headers = {} otlp_service_name = "agentos" log_retention_days = 14 log_retention_max_total_mb = 500 log_retention_sweep_interval_s = 3600.0 ``` - **Prometheus Metrics**: `metrics_enabled` (default `true`) exposes Prometheus metrics at `metrics_path` (default `"/metrics"`). Core metrics (`agentos_queue_depth`, `in_flight_turns_total`, `turn_cancellations_total`, `queue_full_errors_total`) are exported with bounded cardinality. - **OTLP Trace Export**: `otlp_enabled` (default `false`) sends trace events as OTLP spans over HTTP to `otlp_endpoint` (e.g. OpenTelemetry Collector). - **Log Retention**: `log_retention_days` (TTL) and `log_retention_max_total_mb` (total size cap) bound disk growth in `~/.agentos/logs`. Background sweeps run every `log_retention_sweep_interval_s`. ## Image Flows `[flows]` configures the Image Flows engine (the desktop's Flows editor, `agentos flows`, and the agent tools `flow_list` / `flow_run`): ```toml [flows] enabled = true # off: every run is refused and the agent tools are hidden max_concurrent_runs = 1 # 1-8 runs at once; the rest wait in a FIFO queue agent_cost_limit_usd = 0.50 # flow_run above this estimate (or an unknown one) asks for approval cache_max_mb = 500 # node cache, least recently used evicted first ``` Env overrides use a single underscore after the section: `AGENTOS_FLOWS_ENABLED`, `AGENTOS_FLOWS_MAX_CONCURRENT_RUNS`, `AGENTOS_FLOWS_AGENT_COST_LIMIT_USD`, `AGENTOS_FLOWS_CACHE_MAX_MB`. Image provider keys and base URLs are not repeated here: flows use `[image_generation.providers.surplus]` (`SURPLUS_API_KEY`), `.openrouter` (`OPENROUTER_API_KEY`) and `.openai` (`OPENAI_API_KEY`), whatever `[image_generation].enabled` says (that flag only gates `image_generate`). See [Image Flows](https://useagentos.dev/docs/core/flows). ## Downloads, Web Push and Direct Tool Calls ```toml [artifacts] legacy_session_key_urls = true # keep the deprecated ?sessionKey= download URLs this release [push] web_enabled = true # browsers may subscribe to approval notifications vapid_subject = "https://useagentos.dev" # VAPID `sub`: a mailto: or https: contact [tools.invoke] allow = [] # tools lifted off POST /api/v1/tools/invoke's hard deny list ``` | Key | Default | Meaning | | --- | --- | --- | | `artifacts.legacy_session_key_urls` | `true` | `false` makes `/api/v1/artifacts/{id}?sessionKey=` and `/api/v1/attachments/{sha256}?sessionKey=` answer `404`. Clients use ticketed URLs from `artifacts.download`; see [HTTP API](https://useagentos.dev/docs/core/http-api#ticketed-downloads). | | `push.web_enabled` | `true` | Web Push for approvals. The VAPID key pair is generated once into `<state_dir>/web_push_vapid.json` (0600); subscriptions live in `<state_dir>/web_push.sqlite`. | | `push.vapid_subject` | `https://useagentos.dev` | Contact push services may use to reach the sender. | | `tools.invoke.allow` | `[]` | Exact tool names `POST /api/v1/tools/invoke` may run although it would refuse them (not declared read-only, or on its name floor). The configured `[tools]` policy still applies. File-only: config RPC writes cannot add an entry. | All three are read per request: no restart. ## Inbound Webhooks ```toml [hooks] token = "<long random secret, not the gateway token>" rate_limit_per_minute = 60 # per hook name; 429 beyond it max_sessions_per_hook = 1 # distinct sessions one hook may deliver into per hour [hooks.routes.github] # POST /api/v1/hooks/github agent = "main" session_key = "" # empty: agent:main:hook:github template = "PR {{ payload.pull_request.title }} was {{ payload.action }}" [hooks.lifecycle] # shell commands, run with a time budget startup = [] shutdown = ["/usr/local/bin/backup-agentos"] pre_restart = [] ``` - `hooks.token` admits `POST /api/v1/hooks/agent`, `/wake` and `/<name>` (`Authorization: Bearer` or `X-AgentOS-Hook-Token`). The gateway token is refused there, and a hooks token equal to it disables the routes. Unset: the routes answer `404`. Wrong tokens are throttled by `[auth.rate_limit]` in a budget of their own: a sender that keeps guessing is locked out of the hooks (`429`), not out of the gateway. - A route's `template` fills `{{ payload.a.b }}` placeholders (dotted paths, list indexes like `commits.0.id`) from the posted JSON; no expressions. Empty: the body's `message`, else the JSON body itself. A route's `session_key` is the only way to deliver into an existing conversation; a caller may only choose a key under `agent:<agent>:hook:`. - `[hooks.lifecycle]` commands run through `/bin/sh -c` without the gateway's credentials in their environment, with `AGENTOS_LIFECYCLE_EVENT` and `AGENTOS_LIFECYCLE_REASON` set. Budgets: `startup` 10 s, `shutdown` 5 s, `pre_restart` 10 s, shared by every command and in-process hook of that event. They need a POSIX shell: on Windows each one is logged as failed (`gateway.lifecycle_hook_failed`) and not started. - `hooks.token` and `hooks.lifecycle` are file-only: `config.set`, `config.patch` and `config.apply` refuse to set a token or add a command (clearing them is allowed). Route names are 1-64 of `a-z 0-9 _ -` and cannot be `agent` or `wake`. Hooks settings apply on the next request. See [HTTP API → Inbound webhooks](https://useagentos.dev/docs/core/http-api#inbound-webhooks). ## Raw Config Editing For advanced settings, inspect `agentos.toml.example` and edit the active config file directly. Use CLI commands for routine provider, router, search, channel, and sandbox changes because they avoid common key-shape mistakes. ### Editing the file while the gateway runs With `[gateway] config_reload = true` (the default) the gateway checks the active config file every 2 seconds and, once a change has been still for half a second, applies it like a config write from the console: validated, applied in place, hot settings live at once. Settings that are only read at startup (bind, channels, sandbox, memory backend, middleware, and anything not on the audited live list) are recorded as pending instead: `agentos doctor` reports `gateway.config.restart_pending` and the console gets a `config.changed` event listing `hot` and `restartRequired` paths. Restart to apply those. **Operator-only settings are held.** A change to `trading`, `hooks`, `tools` (including `tools.invoke`), `permissions`, `sandbox`, `auth`, `safety`, `workspace_dir`, `workspace_strict`, `acp.permission_mode`, `acp.non_interactive_permissions`, `acp.agents`, `acp.allowed_agents`, `acp.allowed_cwds`, `acp.install_missing_adapters`, `gateway_control`, `mcp`, `skills.install_policy`, `browser.binary_path`, `browser.cdp_port`, `browser.attach_confirmed`, `browser.allow_unsafe_evaluate`, `cors`, `control_ui.allowed_origins`, `gateway.bind`, `gateway.public_origin`, `state_dir` or `observability.otlp_*` is never applied from a file edit alone: the file is one same-user write away for an agent's shell on a host without the OS sandbox, and the config RPCs refuse an agent those settings. The running values stay, the gateway logs `config.reload_held`, `config.changed` carries the paths under `held` (`status: "held"` when nothing else changed), and `agentos doctor` reports `gateway.config.reload_held`. Apply them yourself with `agentos config reload` (refused from an agent's session). **Refused to an agent's connection.** Besides the settings above, a connection the gateway recognizes as an agent's (an agent token, a process the gateway spawned, an exec window) cannot change where model and embedding calls go -- `llm.base_url`, `llm.proxy`, `agentos_router.judge_base_url`, `agentos_router.jev.base_url`, `memory.embedding.base_url` and its `remote`/`ollama` variants, `memory.provider.mem0.*_base_url`, the image, audio and X search `base_url`s, `search_proxy`, `search_use_env_proxy` -- a provider profile's `base_url`/`proxy`/`router.judge_base_url`, a channel's endpoint (`api_base`, `webhook_url`, `gateway_url`, `command_request_url`, `imap_host`/`imap_port`, `smtp_host`/`smtp_port`; a new channel keeps the defaults), the spend ceilings (`budgets`) or the agent definitions (`agents`, and the `agents.create`/`agents.update`/`agents.delete` RPCs, which fail with `agent.operator_required`). Your web console (unbound on loopback), the desktop app and your own CLI keep them, and a file edit of them applies as before. **A restart does not apply them either.** The gateway keeps the values of the operator-only settings as you last approved them in `~/.agentos/config-approval.toml` (`0600`, a sensitive path the agent cannot touch). At boot, a setting the file holds differently from that approval runs on the approved value, the gateway logs `config.boot_held_operator_only` and `agentos gateway run` prints the held settings; they stay held across any number of restarts until you run `agentos config reload` from your own terminal. With a gateway running that applies the file there; with none running it records the file's values as approved for the next start (`agentos config reload --config <path>` names another file). The approval moves forward on its own when you change a setting through a config RPC, the console, or `agentos config set` / onboarding while no gateway runs; a write never approves an edit somebody else had already left in the file. The first boot without an approval file adopts the file as it is. An unreadable approval file stops the gateway at boot (restore it, or delete it to approve the file as it is now). The active config file and `<state dir>/config.toml` are also sensitive paths: an agent's shell and file tools cannot read or write them, nor the `<name>.backup.<stamp>` copies a config write leaves beside them. The same settings cannot be written into `.env` through `agentos env set`, the console or an agent tool (`AGENTOS_TRADING_*`, `AGENTOS_GATEWAY_SANDBOX__*`, ...): edit `.env` by hand if you mean it. An edit that does not parse or validate never replaces the running config: the gateway keeps its last good settings, logs `config.reload_skipped`, sends `config.changed` with `status: "invalid"`, and `agentos doctor` reports `gateway.config.reload_skipped` until a good save (fixing the file back to the running settings sends `config.changed` with `status: "recovered"`). `--listen` / `--port` overrides and runtime-only secrets (an auto-generated token, keys from the environment) carry over a reload. The gateway's own writes are recognized and cause no reload. When `config_reload` is off, restart after changing the file. Either way, check: ```sh agentos doctor agentos gateway status ``` --- # CLI Reference > Source: https://useagentos.dev/docs/core/cli The `agentos` CLI is the fastest way to configure, run, inspect, and automate AgentOS. Run: ```sh agentos --help agentos <command> --help agentos --version ``` `--version` prints the installed version and exits, so the version is available without `uv tool list` or `pip show`. ## Main Commands | Command | Purpose | | --- | --- | | `agentos init` | Initialize a workspace. | | `agentos upgrade` | Upgrade AgentOS and restart the managed gateway to match. | | `agentos doctor` | Diagnose readiness and print recovery steps. | | `agentos onboard` | Run or inspect first-run setup. | | `agentos auth` | Provider logins that are not API keys (`login`/`status`/`logout`; xAI today). | | `agentos configure` | Reconfigure provider, router, channels, search, x-search, image generation, or memory embedding. | | `agentos config` | Get or set configuration keys (`get`/`set`); `reload [--config PATH]` applies the config file, including the operator-only settings (trading, hooks, tools, permissions, sandbox, auth, safety, workspace, ACP launch and permission settings, MCP servers, `gateway_control`, ...) that neither a file edit nor a restart applies by itself: with a gateway running it applies the file there, with none it records the file's values as approved for the next start. `reload` is refused from an agent's session. | | `agentos env` | Read or write `~/.agentos/.env` credentials (`list`/`get`/`set`/`import`/`unset`). | | `agentos gateway` | Run and manage the gateway server. | | `agentos chat` | Start interactive terminal chat. | | `agentos agent` | Run a single automation-friendly agent turn. | | `agentos sessions` | List, inspect, rename, pin, resume, abort, delete, or export sessions. | | `agentos acp` | Drive external coding harnesses (Claude Code, Codex, Gemini CLI, ...) over ACP: `list`, `doctor`, `run`, `sessions`, `cancel`, `close`. | | `agentos projects` | Group sessions into projects with shared knowledge injected into every member session. | | `agentos wallet` | Create, import, export and unlock wallets in the engine's vault; show balances. | | `agentos trade` | Quote and swap tokens on Base / Robinhood Chain through the AgentOS DEX (default) or Uniswap; orders, approvals, history, PnL; Uniswap V4 liquidity; DCA mandates; price triggers (stop-loss, take-profit, trailing stop, buy-the-dip, alerts); brackets (take-profit + stop-loss on one position, one cancels the other). | | `agentos skills` | List, search, view, install, update, publish, inspect, and tap skills. | | `agentos memory` | Inspect and maintain memory. | | `agentos channels` | Configure and inspect messaging channels. | | `agentos providers` | Configure and inspect LLM providers. | | `agentos search` | Configure and use web search. | | `agentos sandbox` | Inspect or change default sandbox posture. | | `agentos cron` | Manage scheduled AgentOS runs. | | `agentos flows` | List, inspect and run Image Flows (node-graph image workflows built in the desktop app): `list`, `show`, `nodes`, `models`, `run`, `runs`, `stop`. | | `agentos cost` | Inspect usage and estimated cost. | | `agentos cost savings` | Report what the Pilot Router saved against the priciest configured tier. | | `agentos context` | Show the fixed per-request context cost and what each tool profile would cost. | | `agentos diagnostics` | Enable or disable runtime diagnostics logging. | | `agentos replay` | Replay a recorded turn from the decision log. | | `agentos migrate` | Import state from external agent runtimes. | | `agentos models` | Inspect available models. | | `agentos agents` | Manage durable agents. | | `agentos mcp` | Manage the MCP servers AgentOS connects to as a client: `list`, `status`, `add`, `remove`, `enable`, `disable`, `probe`, `doctor`. | | `agentos mcp-server` | Run the AgentOS MCP server bridge. | | `agentos dist` | Emit a reproducible workspace-state inventory. | | `agentos reset` | Reset a session, rotating it to a fresh transcript. | ## Run Surfaces Web UI and gateway: ```sh agentos gateway run agentos gateway start --json agentos gateway status agentos gateway status --deep --json agentos gateway restart agentos gateway stop agentos gateway install --port 18791 agentos gateway uninstall ``` `gateway run` and `gateway start` take `--port`, `--bind` / `--listen HOST` (an explicit host, bind mode `custom`) and `--bind-mode loopback|lan|tailnet|custom`, which overrides `[gateway] bind`. `tailnet` listens on the `tailscale ip -4` address and on `127.0.0.1`, and fails to start rather than fall back to `0.0.0.0` when Tailscale is unavailable; `lan` and `tailnet` need token auth. `status`, `stop` and `restart` follow the bind mode `start` recorded (or take `--bind-mode`). A Control UI on a specific public address needs `[gateway] public_origin = "https://<the address you open>"` (or `control_ui.allowed_origins`); without it the gateway refuses to start and says so. See [Gateway → Host and Port](https://useagentos.dev/docs/core/gateway#host-and-port). `agentos gateway status` (and `--json`) reports **both** the installed CLI version (`cliVersion`) and the running gateway's version (`gatewayVersion`); when they differ it sets `versionMismatch` and prints a diagnostic advising a restart — the normal state right after a package upgrade with `--no-restart`, or after a manual upgrade. `--json` also carries `drain_budget_ms` (32000: 30 s to drain turns plus 2 s to cancel), `active_turns` (turns running now; `null` when the gateway is not reachable) and `runtime` — the gateway's readiness `state` (`starting`, `ready`, `draining`, `safe_mode`), `failing` and `safe_mode`. The top-level `state` stays the process state (`running`, `unmanaged`, `not_started`, `stale`, ...). `--deep` adds `service`: whether `agentos gateway install` put a unit in place and whether it is loaded. `agentos gateway run` exits `78` (`EX_CONFIG`) when only a configuration change can fix the start — a config file that does not parse or validate, a schema migration that cannot apply, a public bind without auth — and `1` for other failures. See [Supervisor contract](https://useagentos.dev/docs/core/gateway#supervisor-contract). `agentos gateway install [--port N] [--config PATH] [--no-start] [--json]` runs the gateway as a user service that restarts it when it dies: a LaunchAgent (`dev.useagentos.gateway`) on macOS, a systemd user unit (`agentos-gateway.service`) on Linux; not supported on Windows (exit 1). Both units allow a stop 54 s (`ExitTimeOut` / `TimeoutStopSec`): the gateway's worst-case drain and teardown plus a 10 s margin. It refuses when a different unit with the same name exists (run `agentos gateway uninstall` first) and is a no-op for the same unit. `--no-start` writes the unit without loading it. `agentos gateway uninstall [--json]` stops and removes it, and succeeds when nothing is installed. `agentos gateway stop` cannot stop a service-run gateway (the service would start it again): it exits 3 and names the `launchctl bootout` / `systemctl --user stop` command and `gateway uninstall`. Under launchd a config error (exit 78) waits 5 s, doubling up to 5 minutes, before exiting, so the LaunchAgent does not respawn a broken config every 10 s. A gateway that crashes three times in five minutes starts in safe mode (channels, cron and heartbeat held back); see [Run as a service](https://useagentos.dev/docs/core/gateway#run-as-a-service). `agentos gateway stop` sends SIGTERM, which runs the gateway's orderly shutdown (turns in flight get up to 30 seconds, then channels stop and clients are told). If the gateway is still running after `--timeout` (default 10 seconds) it sends a second SIGTERM, which cancels the remaining turns, and only then SIGKILL. `agentos gateway restart` stops and starts a gateway that `agentos gateway start` spawned. A healthy gateway the CLI does not manage (started by the desktop app, launchd, systemd or a terminal `gateway run`) is restarted **in place** instead: the CLI calls the `gateway.restart` RPC, the gateway drains its active turns and re-executes itself under the same process id, and the command returns once the readiness probe passes (`managed: false`, `details.inPlace: true` in `--json`). `--force` cancels the active turns instead of draining them. On Windows, where in-place restart is not available, the command still exits 3 (`UNMANAGED_GATEWAY_RUNNING`). The same restart is available as `/restart [force]` in the web console and, behind `[gateway_control] chat_restart = true`, from paired channels; see [Gateway](https://useagentos.dev/docs/core/gateway#when-to-restart). A turn the restart (or a crash) cuts short is resumed after boot, with read and status tools only when its last tool calls have no recorded result; `[task_runtime] resume_interrupted_turns = false` only reports it. `agentos doctor` lists interrupted turns that were not resumed (`gateway.turn_recovery.not_resumed`); see [Gateway: interrupted turns](https://useagentos.dev/docs/core/gateway#interrupted-turns). Terminal chat: ```sh agentos chat agentos chat --model gpt-5.4-mini agentos chat --session <session-key> agentos chat --standalone --workspace /path/to/project ``` ### Chat REPL slash commands `agentos chat` exposes a prompt-toolkit REPL with a slash-command palette. The most useful ones: | Command | Purpose | | --- | --- | | `/new [title]` | Start a new chat session. The optional title is persisted as the session's display name and shown in the bottom toolbar and `/status`. | | `/resume <key>` | Resume an existing session by key (or a prefix / display-name match in gateway mode). | | `/status` | Show the current session, model, permissions, and the active Pilot Router tier (or `auto`). | | `/model [filter]` | List available models (optionally filtered by name). | | `/clear` / `/reset` | Clear the current conversation context. The screen is wiped too (including scrollback), so the cleared turns are gone from view as well as from context. | | `/compact` | Compact older context into a summary. | | `/cost` | Show per-session token and cost totals. | | `/save [path]` | Save the transcript to a Markdown file. | | `/c0` … `/c3` | Pin the Pilot Router to a configured tier for this session. The pin appears in the bottom toolbar (e.g. `tier:c3`) and stays active until you exit or run `/auto`. | | `/use <model-id>` | Pin the route to a specific model, outside the configured tiers. The model must belong to the active provider. | | `/auto` | Restore automatic Pilot Router routing (clears the tier pin). | | `/plan [off]` | Toggle plan mode: the session becomes research-only (read, search, and analysis tools) until you approve the plan the agent presents via `exit_plan_mode`. `/plan off` leaves plan mode — from text surfaces it is also how you approve a presented plan before telling the agent to proceed. Gateway mode only. | | `/help` | List the commands available on the current surface. | | `/exit` / `/quit` | Leave the REPL. | Router tier commands (`/c0` … `/c3`, `/auto`) are available in both gateway and `--standalone` modes. Tiers not present in your `[agentos_router]` config are rejected with a readable error. In `--standalone` mode the router must be enabled in config; otherwise the command reports "Pilot Router is disabled or unavailable." A tier pin you set is **sticky**: it holds every turn until you clear it with `/auto` (or the process ends). It does not time out. Pin `/c3` and forget, and every later turn keeps paying for `c3` — check `/status` if you are unsure what is in force. This differs from the routing the model may pick for itself mid-turn, which still lapses on its own after ten idle minutes. `/use` pins a model that is not one of your four configured tiers. It is a separate verb from `/model`, whose argument filters the model listing — `/model gpt` shows you the gpt models, `/use gpt-5.6-terra` switches to one. Because every turn runs through the single configured `llm.provider` (a tier's `provider` field is metadata, not a client selector), only that provider's models can be pinned; anything else is refused at the point of choosing rather than failing on the next turn. A directly-named model rides on the default tier, inheriting its thinking level and pricing baseline — settings a bare model id does not carry. While a pin is in force the model's own `router_control` tool is withdrawn, so it cannot route around your choice. Two exceptions are worth knowing: - **Image turns.** A turn with an image attachment is routed to a vision-capable tier before pins are consulted, so it runs on that tier, not your pinned one. The Web UI flags such a turn. - **Large context.** A pinned turn skips the large-context tier floor. If the conversation outgrows the pinned model's context window, the turn fails at the provider rather than being quietly upgraded. Pin a larger tier, or run `/auto`. ### Assistant label and session chrome The assistant speaker label shown on the `◢` marker and the pre-token waiting row defaults to `agentos`. Override it with the `AGENTOS_ASSISTANT_LABEL` environment variable — the value is read once at startup and used by every renderer, so it stays consistent across the streamed reply marker, the waiting header, and the queued-turn marker. ```sh AGENTOS_ASSISTANT_LABEL="Hani" agentos chat ``` The active input row is framed by a top and bottom rule, so the typing area reads as a distinct box between the transcript and the bottom toolbar: ``` ──────────────────────────────────────── ◢ you <your message here> ──────────────────────────────────────── title · model · [tier:cN] ``` Press `Enter` to submit the current message. Use `Alt+Enter` or `Shift+Enter` to insert a newline when your terminal reports those modified keys distinctly; `Ctrl+J` is the portable newline fallback. The input frame grows with the message up to 10 visible lines, then scrolls internally while remaining pinned above the bottom toolbar. `Up` and `Down` move between lines in a multiline draft before moving through chat input history at the first or last line. After each reply the empty input shows a suggested next prompt in grey, followed by `· Tab`. Press `Tab` to take it into the input, then `Enter` to send it; typing anything else ignores it. Turn it off with `[sessions] suggest_next = false` (see [Configuration](https://useagentos.dev/docs/core/configuration#suggested-next-prompt)). The bottom toolbar renders `title · model · [tier:cN]` while typing. The title comes from `/new <title>` (or is loaded from the gateway on `/resume`); the tier chip appears only while a Pilot Router hold is active. `/status` mirrors the same fields plus the active permissions posture. **Full-screen surface (default).** `agentos chat` renders the conversation in a scrollable in-app pane above a permanently-pinned input frame (Claude Code style), so the frame stays visible while the assistant streams. The branded welcome screen renders at the top of the pane on launch. `PgUp`/`PgDn` scroll back through history; the mouse wheel scrolls when the pointer is over the transcript. New output re-pins to the newest line. **Select and copy.** Drag with the left mouse button across the transcript to highlight any span (the selection shows in reverse video); releasing the button copies the plain text — ANSI styling stripped, CJK width-aware — to the system clipboard (`pbcopy` on macOS, `wl-copy`/`xclip`/`xsel` on Linux, `clip` on Windows, OSC 52 escape as a fallback). Click anywhere to clear the selection. The emulator's own selection gesture (typically `Shift+drag` on Linux, `Option+drag` in iTerm2) also still works if you prefer it. **Markdown rendering.** The assistant's streamed reply is styled inline as it arrives: `#`/`##`/`###` headings render in the brand accent, `>` quotes get a dimmed bar, `---` becomes a rule, list markers are tinted, tables keep their pipes aligned, fenced code blocks stream in a uniform code color (no waiting for the closing fence), and inline spans — `**bold**`, `*italic*`, `~~strike~~`, inline `` `code` ``, and `[text](url)` links — are styled in place. File names, branch names, and other important terms the model wraps in backticks stand out in the accent color. Reasoning-model `<think>…</think>` blocks render as a recessive gray-bar, dim-italic region (the tags themselves are hidden) so the chain-of-thought stays visible but never competes with the reply. The render is write-once (no repaint loop), and `NO_COLOR` (or a non-color terminal) downgrades the stream to plain text so piped output stays greppable. Input navigation follows the current logical line in multiline drafts: `Home`/`End` and `Ctrl+A`/`Ctrl+E` move to that line's start/end. On macOS, `Cmd+Left`/`Cmd+Right` work when the terminal maps those shortcuts to `Home`/`End`; use `Ctrl+A`/`Ctrl+E` as the portable fallback. Full-screen is the default for an interactive terminal. Non-TTY / piped invocations fall back to native scrollback automatically. To force a mode set `AGENTOS_CHAT_FULLSCREEN`: ```sh AGENTOS_CHAT_FULLSCREEN=0 agentos chat # opt out — stream to native scrollback AGENTOS_CHAT_FULLSCREEN=1 agentos chat # force full-screen (e.g. under a pipe) ``` One-shot automation: ```sh agentos agent -m "Review the current directory" agentos agent --json -m "Return a short machine-readable summary" agentos agent --workspace /path/to/project --workspace-strict -m "Inspect this repo" agentos agent --timeout 600 --max-iterations 30 -m "Run a bounded investigation" ``` Useful automation flags: | Flag | Purpose | | --- | --- | | `--workspace` | Set the workspace root. | | `--workspace-strict` | Restrict read-side file tools (including `pdf`, `image` and audio) to the workspace. | | `--workspace-lockdown` | Contain writes to workspace or scratch directory. | | `--scratch-dir` | Place temporary scripts/logs/candidate patches in a known directory. | | `--file` / `-f` | Attach a local file; repeat for multiple files. | | `--unattended` / `--interactive` | Run without a live approval surface (unattended is default). | | `--stateless` / `--clean-room` | Use clean-room prompt bootstrap. | | `--stateless-keep-project-rules` | With clean-room bootstrap, keep `AGENTS.md` project rules only. | | `--no-memory-capture` | Do not write this invocation to durable searchable memory. | | `--session-id` | Target a specific session key/id for cross-invocation continuity. | | `--timeout` / `-T` | Set total agent wall-clock timeout in seconds. | | `--max-iterations` | Bound the model/tool loop. | | `--iteration-timeout-seconds` | Per-iteration timeout in seconds (one LLM call + tool executions). | | `--tool-timeout-seconds` | Per-tool execution timeout in seconds. | | `--request-timeout-seconds` | Single LLM HTTP/streaming request timeout in seconds. | | `--max-provider-retries` | Bound transient provider retries. | | `--length-capped-continuations` | Bound automatic continuations after length-limited provider output. | | `--thinking` | Override reasoning level (off, minimal, low, medium, high, xhigh, adaptive). | | `--permissions` | Select restricted, bypass, or full permission posture. | | `--transcript-path` | Write a JSONL transcript for automation. | | `--usage-path` | Write usage JSON. | | `--session-db-path` | Persist session replay across invocations. | | `--json` | Emit machine-readable JSON output. | ## Version ```sh agentos --version # or -V: prints the installed version, nothing else ``` Deliberately cheap (no config load, no gateway probe): the macOS app runs it at every launch to decide whether the engine it ships needs installing. ## Installer stage protocol `install.sh` is also the engine installer behind the macOS app, which drives it stage by stage so it can show real progress and retry one step: ```sh bash install.sh --manifest # one JSON line: {"protocol_version":1,"stages":[…]} bash install.sh --stage uv --json # run ONE stage; the last stdout line is the result frame # {"ok":true|false,"stage":"uv","skipped":bool[,"reason":"…"]} ``` Stages, in order: `prerequisites` (platform, curl/wget, reachability of github.com and astral.sh), `uv` (download-then-run the astral installer if uv is missing), `python` (`uv python install 3.12` if needed), `package` (`uv tool install --force` the version-pinned wheel, then smoke-test the entry point), `path` (append the uv tool bin dir to the login shell's rc file once), `complete`. Every `--stage` call is a separate process, each stage body runs in a subshell so a helper's `exit 1` still yields `{"ok":false}`, and `--non-interactive` makes a stage that would need input report `skipped:true` (none do today). A plain `bash install.sh` runs all stages in order as before. ## Upgrade `agentos upgrade` is the primary upgrade path. It detects how AgentOS was installed, installs the **published PyPI release** of `use-agent-os[recommended]`, and — by default — restarts the managed gateway and **verifies** the running gateway reports the new version before declaring success (a "successful" upgrade that leaves the daemon on old code is the common upgrade regret). It always targets the release, never a local checkout. To install a checkout, run `bash scripts/install_source.sh` — that script is the only path that rebuilds the React control UI (`npm ci && npm run build`) before installing. ```sh agentos upgrade # snapshot, upgrade, restart the gateway, verify agentos upgrade --check # is a newer release available? change nothing agentos upgrade --dry-run # print the exact command that would run agentos upgrade --no-restart # upgrade only; leave the gateway on OLD code agentos upgrade --source github # install the GitHub release asset, not PyPI agentos upgrade --timeout 900 # bound the upgrade subprocess (default 600s) agentos upgrade --verify-data # only check the state databases agentos upgrade --restore-snapshot latest # put the last snapshot back ``` | Flag | Purpose | | --- | --- | | `--check` | Ask PyPI and GitHub Releases for a newer release (5s timeout each); offline prints `could not check (offline)`. Changes nothing. `--json` adds `pypi`, `github` and the `source` an upgrade would use. | | `--dry-run` | Print the upgrade command that would run, whether a snapshot would be taken and whether the gateway would be restarted; touch nothing. | | `--source` | `auto` (default): PyPI, or the GitHub release wheel when GitHub is ahead or PyPI is unreachable. `pypi` / `github` force one. | | `--no-snapshot` | Skip the pre-upgrade snapshot (default: taken). | | `--no-restart` | Upgrade the package but do not restart the gateway. Prints an unmissable warning that it still runs the old version; run `agentos gateway restart` yourself. The data check is skipped too — only a restarted gateway has migrated anything. Without the flag, a gateway the CLI does not manage (desktop app, launchd, systemd, a terminal) is restarted in place over `gateway.restart` rather than skipped. | | `--timeout` | Upgrade-subprocess timeout in seconds (default 600). On timeout the tool's process group is killed with recovery guidance — never a half-state. | | `--verify-data` | Run `PRAGMA quick_check` on every SQLite file under `~/.agentos/state/` and exit; nothing else happens. Exit 1 on a problem, naming the last snapshot. | | `--restore-snapshot DIR\|latest` | Copy a pre-upgrade snapshot back file for file. Refuses while a gateway answers on the configured endpoint (a live database would replay its journal over the restored file). | | `--config` | Target a specific config file for the gateway restart. | | `--json` | Machine-readable output. | ### Release sources Every release is published twice — a wheel on PyPI and the same wheel attached to the GitHub release the tag created (`install.sh` installs from the latter). `--source auto` prefers PyPI and falls back to the GitHub asset only when GitHub is *ahead* (the "PyPI publish failed for this tag" case) or PyPI cannot be reached; the spec then becomes `use-agent-os[recommended] @ https://github.com/use-agent-os/agent-os/releases/download/v<version>/use_agent_os-<version>-py3-none-any.whl`, which `uv tool install` / `pipx install` accept as-is. `AGENTOS_REPOSITORY` (`owner/name`) points both `install.sh` and the upgrade at a fork. ### Snapshot and data check Before the installer runs, `config.toml`, `auth.json`, `skills-lock.json` and every `*.db` / `*.sqlite` under `~/.agentos/state/` are copied into `~/.agentos/state/snapshots/pre-upgrade-<utc>/` (databases through SQLite's online-backup API, so a WAL-mode file the gateway is writing still yields a consistent copy; files over 1 GiB are skipped and listed; `.env` is never copied). The newest three snapshots are kept. After the restarted gateway has verifiably reported the new version — and so has run its config and schema migrations — every state database gets a `PRAGMA quick_check`. If one fails and there is a snapshot, the managed gateway is stopped, the snapshot restored, the gateway started again and the check repeated; the JSON output carries `data` and `restored`. A gateway this command does not manage is left alone and the exact `--restore-snapshot` command is printed instead. ### From the Control UI and the desktop app The web console's update notice (and Settings › Updates) has an **Update now** button: after a preflight it calls the `updates.apply` RPC, which spawns `agentos upgrade --json` as a detached job (it survives the gateway restart it causes) and records progress under `~/.agentos/state/upgrade_job.{json,log}`; `updates.status` reports `idle | running | done | failed` plus the log tail and the final JSON, from whichever gateway process is up. `updates.verifyData` runs the data check on demand. The macOS app runs `agentos upgrade --json --no-restart` itself, restarts the gateway it spawned, then confirms the version and data over RPC (Settings › About). Per install method: - **uv tool** — delegated automatically as `uv tool install --force --python <running major.minor> "use-agent-os[recommended]"`, resolving `uv` to an absolute path over a hardened PATH. `install` rather than `upgrade` is load-bearing: `uv tool upgrade` takes only a bare tool name and re-resolves whatever uv's receipt recorded, so an install laid down from a checkout (`install_source.sh` passes `.`) keeps rebuilding the wheel from the working tree — re-packaging whatever `src/agentos/gateway/static/dist/` is on disk, because nothing in the upgrade path runs `npm run build`. `--force` is required so an already-installed tool is genuinely rebuilt instead of no-op'ing, and it also self-heals a stale cache or an orphaned interpreter (e.g. after the base Python moves). `--python` pins the rebuilt venv to the interpreter already in use, so a forced reinstall never moves a 3.13 install onto another version. - **pipx** — the same shape: `pipx install --force "use-agent-os[recommended]"`. - **pip / editable / unknown** — not faked: prints the exact manual command (e.g. `python -m pip install --upgrade "use-agent-os[recommended]"`) and exits with a distinct code. The editable hint points at `git pull && bash scripts/install_source.sh`, since an editable install serves the control UI straight out of the checkout. - **portable** (the Windows portable zip's venv, built without pip) — not faked either: prints `python -m ensurepip` and then the `python -m pip install --upgrade` command, as two lines to run in order. Extras are always `[recommended]` — the same profile `install_source.sh` installs by default. Without them the ONNX embedding models and the pilot router degrade silently at runtime. When the current install was built from a local directory (detected via PEP 610 `direct_url.json`), the command prints a note naming that directory and `scripts/install_source.sh` before proceeding. It is informational only: it never prompts, blocks, or changes the exit code. `--json` reports the same as `sourceDirectory` (`null` for a release install). On **Windows** the managed gateway is stopped *before* the installer runs and started again afterwards. Windows refuses to replace a file a live process holds open, and the managed gateway runs the tool venv's own interpreter — leaving it up is what produced `Access is denied` on `…\uv\tools\use-agent-os\Scripts`, and a half-replaced directory with `agentos` no longer on PATH. `--no-restart` keeps its promise not to touch the gateway, so an upgrade with that flag can still hit the lock. POSIX is unchanged: files are replaced under the running gateway, which is restarted afterwards. If the installer is refused anyway, the failure names the recovery instead of only echoing the installer's error: stop the gateway and close every other AgentOS process, re-run the printed command from a fresh terminal, and — if `agentos` is then not found — put uv's tool bin directory back on PATH with `uv tool update-shell`. Exit codes: **0** success (upgraded + verified, or `--check`/`--dry-run`); **3** this install method needs a manual command (printed); **1** the upgrade failed, timed out, the post-restart version could not be verified, or the data check failed; **2** an invalid `--source`. Config migrations run at gateway start and write a timestamped backup before rewriting any file, so `~/.agentos/` config and data are safe across upgrades. ### Version skew Commands that talk to the gateway compare the CLI and gateway versions once per run: - **Gateway older than the CLI** (normal right after an upgrade, before a restart) — prints a warning on stderr, never blocks. - **Gateway newer than the CLI** (you downgraded the CLI, or drive a newer gateway from a stale environment) — **refused**, because a newer gateway may have written config with a newer schema. Fix by upgrading the CLI or restarting the gateway from this environment; override in an emergency with `AGENTOS_ALLOW_VERSION_SKEW=1`. ### Update notifications On gateway-connected commands the CLI checks PyPI at most once every 24h and, if a newer release exists, prints a one-line notice on stderr. Similarly, the Web UI queries the gateway on connection and, if an update is available, shows an **Update available** badge in the status menu and a dismissible notice linking to Settings › Updates. The check is suppressed on non-interactive CLI runs (no TTY) and in CI. Control it with: - `updates.notify = false` in `agentos.toml` (or the setup UI's Finish step) — turns the notices off entirely (both CLI and Web UI). - `AGENTOS_NO_UPDATE_NOTICE=1` — silences it for a single run/session. See [Configuration](https://useagentos.dev/docs/core/configuration#update-notifications). ## Configuration Commands Provider and router: ```sh agentos onboard agentos onboard status agentos configure provider --provider openrouter --api-key-env OPENROUTER_API_KEY agentos configure router --router recommended agentos providers list agentos providers configure openrouter agentos providers status ``` `agentos configure router` **without** `--router` (and the router step of `agentos onboard`) opens a Mode selector: **Local ML — English-optimized (Pilot)** (default), **Smart routing (LLM-based)**, **Jev cloud classifier (typesafe.ai, experimental)**, or **Off**. Passing `--router <mode>` is the non-interactive form: it writes that tier profile and saves without asking anything. Picking the Jev mode asks for a TypeSafe API key (leave it blank to use `TYPESAFE_API_KEY` from the env store, set with `agentos env set TYPESAFE_API_KEY`, which prompts for the value), verifies it with one test call, and saves. A key typed at the prompt is written to `config.toml` under `[agentos_router.jev]` (redacted on every public surface, and omitted whenever it equals `$TYPESAFE_API_KEY`). To skip the wizard entirely: `agentos config set agentos_router.strategy jev`. Jev sends the current turn text to typesafe.ai; see [Pilot Router](https://useagentos.dev/docs/core/features/pilot-router#the-jev-strategy). `providers status` includes a `circuit` column with the active provider's failover circuit-breaker state (`closed`, `half_open`, or `open (42s)`); see [Providers and Models](https://useagentos.dev/docs/core/providers-and-models#provider-health-circuit-breaker). Provider-specific setup examples, including OpenCAP and Surplus Intelligence, live in [Providers and Models](https://useagentos.dev/docs/core/providers-and-models). Context history: when a turn ends, its tool results and tool-call arguments longer than `compaction.history_tool_result_max_chars` are kept for later turns as head/tail plus a tool-result-store handle (during the turn the model sees them in full). `0`, the default, means 2% of the model's context window, clamped to 4,000-12,000 characters: ```sh agentos config set compaction.history_tool_result_max_chars 20000 ``` Coding harnesses (`sessions_spawn(runtime="acp")`) run in the agent workspace unless the spawn passes a `cwd`; that `cwd` must sit inside the workspace or under one of `acp.allowed_cwds` (managed worktrees are always allowed). The workspace suits read-only work; list the project a harness should write in (the value replaces the whole list, and a refused spawn prints this command with the directory filled in): ```sh agentos config set acp.allowed_cwds '["~/Code/my-app"]' ``` The in-turn compaction summary is an auxiliary side task (`compaction`, the router's cheapest text tier unless `[auxiliary.tasks.compaction]` names a model) bounded by `compaction.summary_timeout_seconds` (default 45): ```sh agentos config set compaction.summary_timeout_seconds 30 ``` Once a turn ends with the history at `compaction.proactive_ratio` (default 0.70) of the compaction trigger, the session is compacted in the background before the next turn, once the session has been idle for `compaction.proactive_idle_seconds` (default 20; doubled per session, up to 300, after a turn cancels a running summary); `compaction.proactive false` turns that off. The trigger's size estimate is calibrated per provider/model against the input tokens providers report; `compaction.estimate_calibration false` uses the raw estimate: ```sh agentos config set compaction.proactive false agentos config set compaction.proactive_ratio 0.6 agentos config set compaction.proactive_idle_seconds 60 agentos config set compaction.estimate_calibration false ``` Search: ```sh agentos search list agentos search status # optional provider id: agentos search status brave agentos search configure duckduckgo agentos search query "latest AgentOS release" agentos configure search --search-provider duckduckgo ``` X (Twitter) search — a separate xAI-backed tool, not a `web_search` backend. With a SuperGrok / X Premium+ subscription, sign in instead of using a key: ```sh agentos auth login xai # device-code flow; preferred over XAI_API_KEY agentos auth status # never prints a token agentos auth logout xai agentos auth login xai --no-wait --json 2>/dev/null # start, print link + code, exit agentos auth login xai --resume --json 2>/dev/null # exit 0 done, 3 not yet, 1 failed ``` ```sh agentos onboard catalog x-search agentos configure x-search --api-key-env XAI_API_KEY agentos configure x-search --x-search-model grok-4.5 --x-search-reasoning-effort low agentos configure x-search --no-x-search-enabled ``` The `x_search` tool stays hidden from the agent until an xAI credential is reachable. See [X (Twitter) Search](https://useagentos.dev/docs/core/x-search). Image generation: ```sh agentos configure image --image-provider openai --primary openai/gpt-image-1 --api-key-env OPENAI_API_KEY agentos configure image --no-image-enabled ``` Memory embedding: ```sh agentos configure memory --memory-provider local --onnx-dir ~/.agentos/models/embeddings/google-embeddinggemma-300m agentos configure memory --memory-provider openai --model text-embedding-3-small --api-key-env OPENAI_API_KEY ``` Channels: Built-in channel types are `discord`, `email`, `slack`, and `telegram`; `agentos channels types` is the authoritative catalog. On upgrade, config entries for retired built-in channel types are removed only after AgentOS creates the normal secure config backup. Slack webhook entries accept `--field webhook_path=/slack/team-a/events` when added with `channels add slack`. An omitted or empty field selects the automatic path: the first enabled webhook account in config order keeps `/slack/events` regardless of how many other webhook accounts are enabled, so adding a second account never changes an already-configured account's Request URL; every other enabled webhook account with no explicit path gets `/slack/events/<account_name>`. Disabled and Socket Mode entries do not count, or count as "first". An explicit path takes precedence. Configure each Slack app's Request URLs to match its path. Duplicate webhook paths with overlapping HTTP methods are rejected at gateway startup. See [Slack modes](https://useagentos.dev/docs/core/channels#slack-modes). ```sh agentos channels types agentos channels describe telegram agentos channels native-commands telegram agentos channels native-commands slack --request-url https://agent.example/slack/events agentos channels add telegram --name personal agentos channels add email --name inbox \ --field imap_host=imap.example.com --field imap_username=agent@example.com \ --field imap_password=<app-password> --field smtp_host=smtp.example.com \ --field from_address=agent@example.com --field allowed_senders=you@example.com agentos channels list agentos channels status agentos channels pairing list personal agentos channels pairing approve personal ABCD2345 agentos channels pairing deny personal <telegram-user-id> agentos channels pairing revoke personal <telegram-user-id> agentos channels pairing clear-pending personal agentos channels edit inbox --field allowed_senders=you@example.com agentos channels edit team --field allowed_user_ids=U012ABCDEF agentos channels edit my-discord --field pairing_enabled=true agentos channels pairing approve my-discord ABCD2345 agentos channels logout personal -y agentos channels enable personal agentos channels disable personal agentos channels restart personal agentos channels start --yes agentos channels start personal --yes agentos channels remove personal ``` `agentos channels start [NAME] [--yes] [--json]` starts channels on the running gateway. Without a name it starts every channel that is not running and, when the gateway is in safe mode (three unclean boots in five minutes), leaves it: cron and heartbeat resume too, and the recorded crashes stop counting. With a name it starts only that channel and keeps safe mode on for the rest. `agentos channels status` shows each channel's runtime `state` (`connected`, `disconnected`, `stale-socket`, `stuck`, `retrying`, `start_failed`, `stopped`, `terminal`, `blocked`), why it is down, and whether safe mode is on; `--json` adds `last_event_at`, `terminal_reason`, `start_error`, and the gateway's automatic restart policy with its last health sweep and sleep/thaw under `health_policy`. A failed automatic restart is retried with backoff (`retrying`) and later by the sweep; only a `terminal` channel (bad credentials) or a `blocked` one is never restarted automatically — fix it with `channels edit`, then `channels restart`. `native-commands` prints the native platform payload derived from the same channel command registry used for text `/command` dispatch. Telegram and Discord menus synchronize when their adapters start. Slack also synchronizes at startup when its channel entry has `app_id`, a short-lived app configuration `manifest_token`, and `command_request_url`. Otherwise import the exported Slack manifest fragment manually; its `--request-url` must point to the gateway's Slack webhook endpoint. Telegram direct messages always require pairing. Pairing is binary (`unpaired`/`paired`), with no admin or owner tier. Groups are disabled by default and require an explicit group chat ID, a paired sender, and—by default—a bot mention. Any connected Control client may approve, deny, or disconnect a pairing. Discord and Slack admit only the platform user ids in `allowed_user_ids` and, when `pairing_enabled = true`, senders paired through the same `agentos channels pairing` commands (codes are issued in DMs). With neither field set the channel refuses every inbound message, slash command, and approval button; `agentos doctor` flags it as `channel.<name>.admission_closed`. `agentos channels pairing …` accepts any Telegram channel and any Discord or Slack channel with pairing enabled. See [Sender admission](https://useagentos.dev/docs/core/channels#sender-admission). ### Platform-Native Interactive Approvals Platform-native interactive tool approvals (such as Slack block actions, Telegram inline keyboard callbacks, and Discord message components) allow operators to approve or deny gated tool executions directly using interactive buttons in their messaging app. For security, interactive approvals are: - **Restricted to Direct Messages (DMs)**: Interactive approval prompts are only sent in channel DMs, not group/channel chats, ensuring they cannot be triggered or visible to unauthorized participants in a shared room. - **Access Gated**: Each button click/interaction verifies that the clicker's sender ID is admitted by the channel (paired, or listed in `allowed_user_ids` on Discord/Slack). Clicking by an unadmitted user is dropped and rejected. - **Session Bound**: Approval tokens are strictly bound to their originating chat session key. A click received from a different chat context or user session will mismatch and be ignored. Raw config (`agentos config`): ```sh agentos config get # dump every key agentos config get llm.provider agentos config set port 18791 ``` Without `--config`, `config set` prints the `export AGENTOS_GATEWAY_…` line that applies the setting; with `--config <path>` it writes the file. Both validate the value first, so a value the gateway would refuse (`tools.profile bogus`) is reported as `Invalid value for …` here rather than when the gateway starts. A gateway started with an invalid setting reports each bad key on one line, naming the environment variable when one supplies it. A long-lived gateway keeps per-session state in memory — stream replay buffers, usage scopes, plan-mode flags, approval elevations. Every one of those sits behind a shared bounded registry whose ceilings are config keys: ```sh agentos config set registry_session_max_entries 512 agentos config set registry_cache_max_entries 512 agentos config set registry_cache_ttl_seconds 900 ``` `registry_session_max_entries` bounds session-scoped state, `registry_cache_max_entries` and `registry_cache_ttl_seconds` bound the time-scoped caches. Session state is normally dropped the moment a session is deleted, aborted or completed; the ceiling is the backstop for sessions that never emit a terminal event. Raise `registry_session_max_entries` on a gateway that runs many simultaneous sessions. For Ollama models that do not reliably support native tool calls, set `tools.enabled = false` in the config file to run in plain-text mode. Keep it enabled for tool-capable cloud models such as `glm-5.2:cloud`; the Ollama provider preserves native tool-call history between turns. Ollama is sent the agent's context window as `num_ctx`, capped at 32768 because Ollama reserves memory for the whole window up front (its own default is a few thousand tokens and silently drops the start of a long prompt); set `AGENTOS_OLLAMA_NUM_CTX` to override it, larger for a big GPU or smaller to fit a small one. Prompt caching is controlled by `[prompt_cache]`: `mode` (`auto`, `on`, `off`) and `ttl`. With `ttl = "1h"` Anthropic keeps the cached system prompt and tool list for an hour instead of five minutes; a cache write then costs 2x the input price instead of 1.25x, which pays off when a session pauses longer than five minutes between requests: ```sh agentos config set prompt_cache.ttl 1h ``` Model streams have their own timeouts, read from the environment: `AGENTOS_LLM_STREAM_CONNECT_TIMEOUT_SECONDS` (default 12), `AGENTOS_LLM_STREAM_WRITE_TIMEOUT_SECONDS` (default 30) and `AGENTOS_LLM_STREAM_IDLE_TIMEOUT_SECONDS` (default 120; `0` turns it off). The idle timeout starts once the model has begun streaming and ends a stream that then goes silent with a retriable error, instead of waiting for the much longer per-iteration timeout. More detail: - [Configuration](https://useagentos.dev/docs/core/configuration) - [Providers and Models](https://useagentos.dev/docs/core/providers-and-models) - [Web Search](https://useagentos.dev/docs/core/search) - [Channels](https://useagentos.dev/docs/core/channels) ## Environment Variables `agentos config` edits the TOML config. `agentos env` edits `~/.agentos/.env`, which is where OS environment variables live — the credentials skills and external binaries read, and provider keys you would rather not keep in the config file. ```sh agentos env list # every variable AgentOS knows about agentos env list --missing # only the ones that are not set agentos env list --category skill # provider | search | image | audio | memory | skill | custom agentos env get OPENAI_API_KEY # state and description, value masked agentos env get OPENAI_API_KEY --reveal agentos env set OPENAI_API_KEY --stdin # value read from stdin agentos env import GITHUB_TOKEN # copy from a tool that already has it agentos env unset OPENAI_API_KEY agentos env unset OPENAI_API_KEY -y # skip the confirmation ``` `agentos env import` covers the case where the credential is not really missing. If you have run `gh auth login`, AgentOS can see that the GitHub CLI holds a token and copy it in rather than asking you to go find one; `agentos env list` marks such variables. Nothing is imported without you asking — a token you granted to another tool is not automatically something an agent should get. The copy does not follow that tool's own rotation, so re-run the import after rotating. Values are never printed unless you ask for them with `--reveal`, which prompts first. From an agent's session `--reveal` (and the value `env list` shows for a non-secret) works only for a setting no source calls secret and whose name does not look like a credential, start with `AGENTOS_` or belong to the gateway: a skill manifest declaring `secret: false` cannot make `GITHUB_TOKEN` or another skill's key readable to an agent. Prefer `--stdin` or the interactive prompt over `--value`: a value passed as a flag lands in your shell history and in the process list. When the gateway is running, the change applies to it immediately, so a skill that needed the variable becomes eligible without a restart. When no gateway is running the file is written directly and the command says the value applies at next start. Provider keys always need a restart to take full effect, because the client was constructed at boot with the previous value — the command tells you when that is the case. Names that steer subprocess execution (`PATH`, `LD_PRELOAD`, `PYTHONPATH`, `EDITOR`, …) or AgentOS runtime posture (`AGENTOS_AGENT_PERMISSIONS`, `AGENTOS_GATEWAY_TOKEN`, `AGENTOS_STATE_DIR`, …) or outbound routing (`HTTP_PROXY`, `AGENTOS_LLM_PROXY`, `AGENTOS_TRUST_ENV`, … — proxy names in any casing) are refused, so this surface cannot be used to widen what the agent is allowed to do. Edit `~/.agentos/.env` by hand if you genuinely need one of them. Variables already set that way keep working; only writing through AgentOS is gated. From an agent's own session (`agentos env` run by the agent's shell, or any connection the gateway recognizes as an agent's) `set`, `unset` and `import` accept only an agent-settable name -- a skill's or a built-in tool's declared credential, such as `FIRECRAWL_API_KEY`, never a skill hot-wallet key -- and `get --reveal` refuses every secret; anything else fails with `env.protected`. Run the command yourself for those. See [What cannot be written through AgentOS](https://useagentos.dev/docs/core/configuration#what-cannot-be-written-through-agentos). What `agentos env list` knows about comes from three places: the setup specs of providers the runtime can actually drive (a provider catalogued for the setup UI with no client behind it -- Exa, Perplexity, and a number of LLM vendors -- contributes nothing, so its key is not offered as "needed"), built-in tools that read a variable directly (`web_fetch`'s `FIRECRAWL_API_KEY`), and `requires.env` in installed skill manifests. A skill entry declared with `required: false` unlocks a feature of the skill when set -- an extra engine, say -- and its absence does not hide the skill. Anything present in `.env` that none of those declare is listed as `custom`. If `agentos env list` reports a variable as coming from `process env`, the shell that started the gateway exported it and that value wins over the file. Editing the file will not change anything until the export is removed. Shell commands the agent runs inherit most of this environment, but not the gateway token or the sandbox guard switches, and `execute_code` forwards only a small allowlist plus what a skill declares. See [Credentials and child processes](https://useagentos.dev/docs/core/configuration#credentials-and-child-processes). Read: - [Configuration](https://useagentos.dev/docs/core/configuration) ## Skills ```sh agentos skills init <name> agentos skills init <name> --description "A custom skill description" -t "trigger1" -t "trigger2" --with-script agentos skills list agentos skills list --json agentos skills search pdf agentos skills view pdf-toolkit agentos skills install <skill-name> agentos skills install <skill-url> --source bankr agentos skills install <skill-url> --source aeon agentos skills update --all agentos skills uninstall <skill-name> agentos skills publish <path-to-skill> agentos skills publish <path-to-skill> --repo <owner/repo> agentos skills tap list agentos skills tap add <owner/repo> agentos skills tap remove <owner/repo> ``` `agentos skills init <name>` initializes a new custom skill template. - `--description` / `-d` provides a description of the skill. - `--trigger` / `-t` registers activation trigger terms (repeatable). - `--target-dir` / `-p` specifies the target parent directory. If omitted, the tool resolves to the highest precedence existing layer directory in the workspace/personal layers list. - `--with-script` scaffolds an executable script `scripts/run.py` template and entrypoint command configuration. - `--force` / `-f` forces overwrite of generated files without purging the parent folder. `agentos skills publish <path-to-skill>` validates the skill directory and publishes it. `--repo` / `-r <owner/repo>` targets the repository the PR goes to; a failed publish prints `Failed:` and exits 1. `agentos skills tap` manages custom skill source repositories (taps) for teams that keep their own skill catalog: `tap list` shows the registered taps, `tap add <owner/repo>` registers one, `tap remove <owner/repo>` removes it. See [Skills](https://useagentos.dev/docs/core/features/skills#manage-skill-sources). The `skills list` table is unchanged: name, layer, eligible, description. `--json` carries more, and now reports the same facts the Web UI shows for the same skill instead of a separate, thinner answer: | Key | What it says | | --- | --- | | `layer` | where the files are — `bundled`, `managed`, `personal`, `project`, `workspace`, `extra` | | `acquisition` | how the skill got there: `kind` is `shipped`, `hub`, or `local`, plus `source_id`, `author`, `identifier`, `version`, `installed_at`, `source_trust`, `scan_verdict`, `registry_verdict`, `policy_decision`, and the `removable` / `updatable` booleans | | `publisher` | `{id, name, url, logo}`, all empty strings when the skill is unbranded. Only publishers on an allowlist inside AgentOS resolve to a name; a skill cannot brand itself by writing one into its manifest | | `provenance` | unchanged, and independent of `publisher` — where the text came from and under what licence | | `status` | `ready`, `needs_setup`, or `not_declared`, alongside a `disabled` boolean and a `status_detail` line | `acquisition.removable` is the honest answer to "can `agentos skills uninstall` remove this", not a restatement of the layer: a hub install whose recorded path no longer matches the configured `skills.managed_dir` reports `false`, while `updatable` stays `true` because an update re-fetches by identifier. `status` answers "can this run". `ready` means the manifest declared requirements **and** every one is satisfied; `not_declared` means there was no `requires:` block to check. Both run — the split records only whether AgentOS verified anything, which is why the Web UI shows them under one **Ready** count and leaves the distinction to `status_detail`. `needs_setup` covers a missing binary, a missing required env var, a wrong OS, and a skill switched off via `skills.disabled` / `skills.enabled`; only the `disabled` boolean tells the last one apart, and it is the only one no install will fix. A required env var must be **non-blank** to count. `export ORACLE_KEY=` leaves the variable set but empty, which no API key, token, or path survives, so it reports as missing rather than as satisfied. `acquisition.author` is an attribution string, not an identity. It is whatever the catalog row credited — a handle a publisher chose — so it passes through no allowlist and must never be rendered with a logo or read as a trust signal; `publisher` is the only field that answers "who vouches for this". It is empty only when it would repeat the resolved brand, so a partner skill is credited once rather than twice — a *different* credit survives. That is the wallet-published case: a skill written from a wallet on bankr.bot but named in the wheel's user-skill allowlist carries Bankr's `publisher` and the author's handle (e.g. `@igoryuzo`) as its `author`. There is deliberately **no `availability` key** in CLI output. Whether the agent is currently being offered a skill depends on a chat session's tool surface, which a CLI process does not have; the gateway's `skills.list` and the Web UI answer that instead. An absent key means "not computed", not "not offered". Read: - [Skills](https://useagentos.dev/docs/core/features/skills) ## Sessions and History ```sh agentos sessions list agentos sessions list --search api-refactor # match name, key, subject or model agentos sessions list --agent main --status done # also --channel, --since agentos sessions show <session-key> agentos sessions rename <session-key> "api-refactor" agentos sessions rename <session-key> --clear # drop the custom name agentos sessions pin <session-key> # keep it in the Pinned section agentos sessions unpin <session-key> agentos sessions resume <session-key> agentos sessions abort <session-key> agentos sessions export <session-key> --format md --output notes.md agentos sessions export <session-key> --format json # no --output: writes <session-key>.json agentos sessions delete <session-key> -y ``` Every filter on `sessions list` runs client-side over the recent history rather than over the page `--limit` would show, so `--limit` bounds how many matches are printed, not how far back the filter looks. `sessions delete` also removes the session's derived memory index document (when session indexing is on), so memory search stops returning it. What the session taught the agent stays in memory; `agentos memory forget --session` removes that. Sessions are auto-named. `rename` gives one a human-readable label that shows up in `sessions list`, in the chat toolbar, and in the Web UI Sessions list, and that `--search`, `resume`, and `show` all accept in place of the key. Inside a chat, `/rename <name>` does the same for the session you are in (no name clears it). Names are trimmed, collapsed to one line, and capped at 120 characters. `pin` puts a session in the **Pinned** section at the top of the session list in the Web UI and the desktop app; `unpin` takes it out. Both accept the key, a short session id or the session's name, and `--json`. The pin is stored on the gateway, so every client shows the same Pinned section. Pinning does not count as activity: the session keeps its place in time. In chat, asking the agent ("pin this session", "pin the session called api-refactor") does the same through the `session_pin` tool. ## ACP coding harnesses ```sh agentos acp list # every harness, launch source, missing CLIs agentos acp list --json agentos acp doctor # check every harness on this machine agentos acp doctor claude --probe # also spawn it and run ACP initialize (30 s cap) agentos acp run claude "Summarize this repo" --cwd ~/code/app agentos acp run codex "Fix the failing test" --permissions approve-all --oneshot agentos acp run claude "Keep going" --resume <acp-session-id> agentos acp run gemini "Explain src/" --mode read-only --json agentos acp sessions # gateway sessions, else stored records agentos acp cancel agent:main:acp:1a2b3c4d agentos acp close agent:main:acp:1a2b3c4d --discard ``` `list` and `doctor` ask the running gateway (`acp.agents`, `acp.doctor`) and fall back to this machine's config and `PATH` when no gateway answers; `--local` skips the gateway. `doctor <id>` exits 1 when that harness cannot launch. `run` needs no gateway: it starts the harness itself, streams the reply to stdout, prints progress and a `Stats:` line (runtime, tokens, cost when the harness reports it) to stderr, and exits 1 on an error or refusal, 130 when cancelled. Options: `--cwd` (default: current directory), `--mode` (ACP session mode id the harness offers), `--oneshot` (discard the resume record afterwards), `--resume <acp-session-id>`, `--model`, `--timeout` seconds (default `[acp] turn_timeout_s`), `--permissions approve-reads` (default: reads allowed, everything else rejected) `| approve-all | deny-all`, `--verbose`, `--json` (one result object, no live text). Harness questions are declined. `sessions` falls back to `<state>/acp/sessions/` when the gateway is down; `cancel` and `close` need the gateway and the full session key (an unknown or non-ACP key is an error and exits non-zero). `cancel` stops the running turn and drops queued ones; the session stays usable. `close` ends the session for good (later turns are refused with `ACP_SESSION_CLOSED`; a finished `oneshot` session, by contrast, stays resumable), and `--discard` also deletes the resume record. Every command takes `--config <path>` except `cancel`/`close`. Read: [ACP Coding Harnesses](https://useagentos.dev/docs/core/acp-agents) ## Projects ```sh agentos projects list agentos projects create "Token research" --knowledge "Shared context here" agentos projects create "Token research" --knowledge-file notes.md agentos projects show <project-id> agentos projects update <project-id> --name "New name" --knowledge-file notes.md agentos projects move <session-key> <project-id> # 'none' detaches agentos projects delete <project-id> -y --json # sessions survive, detached agentos projects list --agent main --json ``` A project groups chat sessions across agents and carries a free-form **knowledge** text (capped at 24,000 characters — the same ceiling the per-turn injection applies, so everything that saves reaches the prompt in full). Every session in the project gets that knowledge injected into its system prompt as a `Project Knowledge` block — edit it and the next turn of every member session picks it up. Sessions of any agent can join the same project (the `--agent` on `create` only sets the default agent for new chats in the project). New sessions can start inside a project (`agentos chat` sessions join via `projects move`, the Web UI's project page starts a new chat in the project), and deleting a project never deletes sessions: they just detach and stop receiving the knowledge. Agents can manage projects from prompting through the `projects_create` / `projects_list` / `projects_update` / `projects_move_session` tools, and `session_search scope=project` searches only sibling sessions of the calling session's project. The tools are scoped to the calling session: `projects_update` edits only the session's own project, `projects_list` returns knowledge text only for that project, and `projects_move_session` moves only the calling session — everything else stays on the CLI/Web UI surface. Read: [Sessions and History](https://useagentos.dev/docs/core/sessions) ## Image Flows ```sh agentos flows list # saved flows, newest first agentos flows show "Lighthouse study" # nodes, links, public inputs agentos flows nodes # node types agentos flows models # image models, which have a key, prices agentos flows run "Lighthouse study" --input prompt="a red fox in snow" --input count=2 agentos flows run flw_2af4f4b5 --to n2 --json # only up to node n2; JSON summary agentos flows run flw_2af4f4b5 --no-wait # queue it and print the run id agentos flows runs "Lighthouse study" --limit 10 # recent runs (all flows without an argument) agentos flows stop run_0123456789ab ``` Every command talks to the running gateway over the `flows.*` RPC, so a run started here shows up live in the desktop's Flows editor (`origin: cli`). `show`, `run` and `runs` take a flow id or its exact name (ids win; two flows with one name are refused). `--input name=value` overrides a public input only (`show` lists them); numbers and toggles take their string form. `run` waits (`--timeout`, default 600 s) and prints the status, `n/m` nodes, how many were cached, the cost against the estimate and the saved PNG paths; it exits 0 when the run is done, 1 when it failed, was cancelled or is still going at the timeout (it keeps running), and 2 for an input the engine refuses (unknown flow or input, a graph with errors: each node error is printed). `--json` prints one summary object; errors are a JSON envelope on stderr. `models` names the missing key for every unavailable model (`SURPLUS_API_KEY`, `OPENROUTER_API_KEY`, `OPENAI_API_KEY`). `run` and `stop` spend or change things, so from an agent's shell the gateway refuses them (`flows.operator_required`); agents use the `flow_run` tool, which asks for approval above `[flows].agent_cost_limit_usd` (default $0.50), e.g. `agentos config set flows.agent_cost_limit_usd 1.00`. Read: [Image Flows](https://useagentos.dev/docs/core/flows) ## Wallets and trading ```sh agentos wallet status agentos wallet setup [--mode auto|manual] # once; default: [trading] unlock_mode (auto = password kept in ~/.agentos/wallets/unlock.key) agentos wallet setup --mode manual # or: unlock per gateway session, keys only in RAM agentos wallet mode manual|auto # switch later; manual deletes the stored password (logged) agentos wallet unlock / lock # lock holds until unlock, in auto mode and across restarts: nothing signs, DCA buys and trading triggers wait agentos wallet create --label main agentos wallet import --label cold --private-key-stdin < key.txt agentos wallet import --label cold --keystore wallet.json agentos wallet export <addr> --keystore --out backup.json # a new owner-only file (0600 / user-only ACL); an existing path is refused agentos wallet export <addr> --private-key # prints the raw key; always asks the vault password agentos wallet list / rename <addr> <label> / primary <addr> / remove <addr> --yes|-y # remove also stops the wallet's DCA mandates, triggers and brackets (re-importing the key revives none) agentos wallet balances [<addr>] [--chain base|robinhood] [--refresh] [--hidden] [--json] # ledger view; --refresh re-reads the chain first (throttled to once per 10 s per wallet); --hidden lists junk tokens too agentos trade status # provider, API key, chains, limits, vault state; --json adds syncKind (why a sync runs: background, requested, initial) and ledgerRepair ("full sync required") after a ledger repair migration agentos trade provider # show the swap provider (aggregator | uniswap) agentos trade provider uniswap # switch it (= config set trading.provider uniswap) agentos trade probe [--provider aggregator|uniswap] [--api-key <key>] # reachable? key valid? (--json exits 1 when not ok; --api-key is operator-only) agentos trade tokens --chain robinhood AAPL # search; verified Stock Tokens are marked ✓ agentos trade quote --chain base --in ETH --out USDC (--amount 0.01 | --usd 5) [--wallet <addr>] [--slippage <pct>] agentos trade swap --chain base --in ETH --out USDC --amount 0.01 --wait [--wait-seconds 1..900] [--slippage <pct>] agentos trade swap --chain base --in ETH --out USDC --usd 5 # "$5 of ETH": the engine sizes it at the current price agentos trade swap --chain robinhood --in ETH --out <addr> --amount 0.01 --wallet <a> --wallet <b> # Robinhood Chain: --amount (no native USD price yet → --usd may answer trading.unpriced); bare USDC resolves to lookalikes there, use the verified address agentos trade swap --chain base --in USDC --out ETH --amount 20 --all-wallets --note "DCA" [--as-agent] # the daily cap is per wallet: this spends up to N caps agentos trade swap --chain base --in USDC --out ETH --amount 20 --client-id dca-eth-$(date +%Y%m%dT%H%M) # idempotency key: one id per intended order, the same id on every retry; minute resolution so sub-daily jobs never collide agentos trade swap --chain base --in ETH --out USDC --amount 0.01 --expected-out-raw <quote.expectedOutRaw> --min-out-raw <quote.minOutRaw> # pin the fill to the quote shown; worse than 2× slippage → trading.price_moved agentos trade orders [--status awaiting_approval] [--wallet <addr>] [--kind swap|send|revoke|bridge|lp_collect|lp_remove|lp_add] [--limit N] agentos trade order <id> --wait --wait-seconds 600 / reject <id> [--reason <text>] # --wait-seconds without --wait returns at once; a parked multisend leg also lists every leg of its batch agentos trade approve <id> [--yes] [--json] # operator-only: shows the order in full (token contracts + verified mark, full recipient and wallet, chain, value; a multisend leg lists EVERY leg and the total — one approval runs them all), then asks; --yes skips the question and is required with --json; sends the digest of what was shown, so an order that changed meanwhile is refused (trading.approval_changed) agentos trade send --chain base --token USDC --to <addr> --amount 25 [--wallet <addr>] [--note <text>] [--client-id <id>] [--wait] [--wait-seconds 1..900] [--as-agent] agentos trade send --chain base --token ETH --to <a> --to <b> --usd 5 # multisend: one batch, $5 of ETH to each agentos trade send --chain base --token USDC --to <a>=10 --to <b>=20 --file recipients.txt # ADDR=AMOUNT per --to; file lines 'ADDR' or 'ADDR,AMOUNT' agentos trade allowances [--chain base|robinhood] [--wallet <addr>] [--full] [--wait/--no-wait] [--wait-seconds 1..3600] # live ERC-20 allowances, spender labels, exposure; --wait polls until the scan has caught up agentos trade revoke --chain base --token <addr> --spender <addr> [--wallet <addr>] [--note <text>] [--wait] [--wait-seconds 1..900] # approve(spender, 0) agentos trade bridge quote --chain base --to-chain robinhood --token ETH (--amount 0.01 | --usd 20 | --pct 50) [--wallet <addr>] [--json] # Relay: what arrives on the other chain, fees, whether it would wait agentos trade bridge create --chain base --to-chain robinhood --token USDC --amount 25 [--wallet <addr>] [--note <text>] [--client-id <id>] [--wait] [--wait-seconds 1..900] [--as-agent] [--json] # ETH↔ETH or USDC↔USDG, both directions; from an agent it always waits for approval; confirmed = funds landed on the destination agentos trade bridge status <orderId|requestId> [--json] # the deposit, Relay's fill on the other chain, the final status agentos trade decode --chain base <txhash> / --data <0x…> [--to <addr>] # what a transaction called and what moved agentos trade network [--fresh] # head block, block age, gas, RPC latency and health per chain agentos trade lp pool <token|TOKEN/QUOTE|poolId> [--chain base|robinhood] [--quote <token>] [--fee <tier>] [--json] [--no-card] # Uniswap V4: a token's deepest pool (or the one on --fee) — reserves, TVL, mcap, launcher, LP lock, biggest ranges agentos trade lp ranges <token|TOKEN/QUOTE|poolId> [--chain base|robinhood] [--quote <token>] [--fee <tier>] [--json] [--no-card] # the pool's liquidity spread over price / market-cap ranges agentos trade lp position <tokenId> --chain base|robinhood [--json] [--no-card] # one position NFT: range, in/out of range, principal, uncollected fees agentos trade lp positions [--wallet <addr|label>]… [--chain base|robinhood]… [--all] [--budget-seconds N] [--json] [--no-card] # every V4 position of the vault's wallets (or --wallet), out of range first; ≤ 50 rows, totals over all; answers within 25 s (--budget-seconds 5-300), partial if cut short agentos trade lp collect <tokenId> --chain base|robinhood [--allow-empty] [--note <text>] [--client-id <id>] [--wait] [--wait-seconds 1..900] [--json] [--no-card] # collect a vault position's fees; always waits for approval agentos trade lp remove <tokenId> --chain base|robinhood [--pct 100] [--slippage 1] [--note …] [--client-id …] [--wait …] [--json] [--no-card] # take liquidity (and every fee) out; --pct 100 burns the NFT agentos trade lp add <token|TOKEN/QUOTE|poolId> --chain base|robinhood [--quote <token>] [--fee <tier>] (--usd X | --amount-base A [--amount-quote B]) [--range mcap:2M-10M|pct:20|above[:20]|below[:20]|full|ticks:LO:HI] [--to-position <tokenId>] [--wallet <addr|label>] [--slippage 1] [--note …] [--client-id …] [--wait …] [--json] [--no-card] # mint a position (or top one up); default range pct:20 agentos trade markets <token> [--chain base|robinhood] [--side all|quote|base] [--min-tvl 10000] [--limit 50] [--lookalikes] [--deep] [--json] [--no-card] # every pool the token trades in, on every DEX: tokens priced in it, and it priced in others; default chain robinhood agentos trade dca create <token> --usd X --every 30m|2h|1d|1w|<seconds> (--cap X | --runs N | both) [--max-price X] [--quote <token>] [--chain base|robinhood] [--wallet <addr|label>] [--slippage 1] [--name <text>] [--start now|next] [--json] [--no-card] # DCA mandate: the engine buys on schedule under a hard cap; from an agent it waits for approval agentos trade dca list [--all] [--wallet <addr|label>] [--json] [--no-card] # live mandates (awaiting approval, active, paused); --all adds completed/stopped/rejected/expired agentos trade dca show <id> [--json] [--no-card] # one mandate: schedule, progress, avg buy vs price now, recent runs agentos trade dca approve <id> [--yes] / reject <id> [--reason <text>] [--json] [--no-card] # operator-only; approve shows the mandate (token contracts, wallet, slippage) and asks first; --yes skips it and is required with --json agentos trade dca pause <id> / resume <id> / stop <id> [--reason <text>] [--json] [--no-card] # operator-only; stop is final agentos trade dca run <id> [--wait] [--wait-seconds 1..900] [--json] [--no-card] # buy now (operator-only); the next scheduled buy does not move agentos trade dca update <id> [--usd X] [--cap X] [--runs N] [--every 12h] [--max-price X] [--name <text>] [--json] [--no-card] # operator-only; --runs 0 / --max-price 0 remove the limit agentos trade trigger create <token> (--below <price|pct%> | --above <price|pct%> | --trail <pct>) (--sell (--pct 50 | --amount 0.05 | --usd 100) | --buy --usd 50 | --alert) [--quote <token>] [--chain base|robinhood] [--wallet <addr|label>] [--slippage 1] [--name <text>] [--for 30m|2h|1d|1w|<seconds>] [--json] [--no-card] # price trigger: the engine watches the price and fires once; from an agent it waits for approval; --quote defaults to the chain's USDC (the native coin when the token is USDC) agentos trade trigger list [--all] [--wallet <addr|label>] [--json] [--no-card] # live triggers (awaiting approval, armed, triggered, paused); --all adds done/stopped/rejected/expired agentos trade trigger show <id> [--json] [--no-card] # one trigger: condition, price now and distance, size, checks, recent fires, result agentos trade trigger approve <id> [--yes] / reject <id> [--reason <text>] [--json] [--no-card] # operator-only; approve shows the trigger and asks first (--yes: required with --json) agentos trade trigger pause <id> / resume <id> / stop <id> [--reason <text>] [--json] [--no-card] # operator-only; stop is final agentos trade trigger fire <id> [--wait] [--wait-seconds 1..900] [--json] [--no-card] # fire now whatever the price (operator-only) agentos trade protect <token> --tp <price|pct%> (--sl <price|pct%> | --trail <pct>) [--pct 100 | --amount 0.05 | --usd 100] [--tp-pct 50] [--alert] [--quote <token>] [--chain base|robinhood] [--wallet <addr|label>] [--slippage 1] [--name <text>] [--for 30m|2h|1d|1w|<seconds>] [--json] [--no-card] # bracket: a take-profit and a stop-loss on one position, whichever fires first stops the other; default the whole position (--pct 100); from an agent it waits for one approval agentos trade bracket list [--all] [--wallet <addr|label>] [--json] [--no-card] # live brackets (awaiting approval, armed, triggered, paused); --all adds done/stopped/rejected/expired agentos trade bracket show <id> [--json] [--no-card] # one bracket: both lines with the price now between them, upside/downside, reward:risk, size, each leg's checks, fires, result agentos trade bracket approve <id> [--yes] / reject <id> [--reason <text>] [--json] [--no-card] # operator-only; acts on both legs; approve shows the bracket and asks first (--yes: required with --json) agentos trade bracket pause <id> / resume <id> / stop <id> [--reason <text>] [--json] [--no-card] # operator-only; both legs; stop is final agentos trade bracket fire <id> [--leg tp|sl] [--wait] [--wait-seconds 1..900] [--json] [--no-card] # fire one leg now (default the nearer one), the other goes on hold (operator-only) agentos trade history [--wallet <addr>] [--chain base|robinhood] [--kind swap|deposit|withdraw|gas|approval|lp_collect|lp_remove|lp_add] [--limit N] [--hidden] agentos trade portfolio [--wallet <addr>] [--hidden] # holdings, cost basis, realized + unrealized PnL (dust under $0.10 is listed, not counted); --hidden lists junk tokens too agentos trade hide --chain base <addr> / unhide --chain base <addr> # your call on a token's visibility; the engine never reverses it agentos trade sync [--wallet <addr>] [--full] # re-read the chain into the ledger; --full rebuilds it (operator-only) — run it once after an upgrade when `trade status` shows ledgerRepair agentos trade limits [<addr>] # guardrails + today's agent spend (default: the primary wallet) ``` Every command takes `--json`. On success the JSON is on stdout; on failure stdout is empty and stderr carries `{"error": {"code": "…", "message": "…"}}`. Exit codes: 1 = gateway or provider error (`GATEWAY_UNAVAILABLE`, `trading.*`), 2 = bad input (`INVALID_ARGUMENT` — e.g. `--amount` and `--pct` together, `--pct` outside `(0, 100]` — `TOKEN_NOT_FOUND`, `TOKEN_UNVERIFIED`, `TOKEN_AMBIGUOUS`, `CONFIRMATION_REQUIRED`), 3 = conflict (`CONFLICT`, `VERSION_SKEW`). Wallets live in the engine's **vault** (`~/.agentos/wallets/`, keystore v3 files encrypted with one vault password). Nothing here is tied to an OS keychain: `auto` mode keeps the password in `unlock.key` (mode 0600) so the gateway unlocks at boot and the agent can sign unattended; `manual` mode keeps keys only in the gateway's memory after `agentos wallet unlock`. Export always asks the vault password. Passwords are read from a hidden prompt or `AGENTOS_WALLET_PASSWORD` (`AGENTOS_KEYSTORE_PASSWORD` for an imported keystore) — never from the command line. Swaps run on Base (8453) and Robinhood Chain (4663) through one of two providers. The **AgentOS DEX** (the default, `trading.provider = "aggregator"`, served at `https://agg.useagentos.dev`) needs no key and no account: one GET returns the price *and* the unsigned calldata, including the ERC-20 approval when one is needed. It never signs and never broadcasts — your wallet does both — and it charges 20 bps on the swap, reported back in the quote. **Uniswap** (`agentos trade provider uniswap`) is the fallback and needs a key: `agentos config set trading.uniswap_api_key <key>`. The desktop app swaps through the AgentOS DEX only and has no setting for either. 0x refuses the tokenised stocks (AAPL, TSLA, NVDA, SPY and the rest on Robinhood Chain, AAPLc and the rest on Base) for legal reasons (`trading.token_not_tradeable`), so when either side of a pair is one the engine asks the AgentOS DEX for its **Uniswap** source instead (`source=uniswap`) — `quote`, `swap`, DCA runs, trigger fires and bracket legs alike. No Uniswap API key is needed, and the quote and the order keep `provider: "aggregator"`. Only when that source cannot take the pair does the engine fall back to the Uniswap provider, if a key is configured; without one the error says how to route through Uniswap directly (`agentos config set trading.uniswap_api_key <key>`). ETH, WETH and USDG trade normally there. Robinhood Chain has no native USD price feed yet, so `--usd` may be refused with `trading.unpriced` (size with `--amount`), and the bare symbol `USDC` resolves to unverified lookalikes there (`TOKEN_UNVERIFIED`): use an address `agentos trade tokens --chain robinhood …` marks `verified: true`. `--in`/`--out` take `ETH`, an address, or a symbol; a symbol must resolve to exactly one *verified* token or the command exits 2 (`TOKEN_AMBIGUOUS`, `TOKEN_UNVERIFIED`, `TOKEN_NOT_FOUND`). Amounts are human units; `--pct` accepts fractions, and `--pct 100` on ETH keeps about 0.001 ETH back for gas. A quote does not check balance or gas — the swap does (`trading.insufficient_balance`) — and carries `expiresAt` (about 20 s for the aggregator, 30 s for Uniswap). Guardrails apply to **agent-initiated** swaps, and the **gateway** decides who is an agent: a shell spawned by an agent turn carries an agent token (`AGENTOS_AGENT_TOKEN`), a `cron --script` job carries one too, any connection opened while an agent shell is running counts as the agent's, and a connection that presents nothing is the agent's as well. The operator proves themself with a secret: the desktop app hands the gateway one at spawn, and the gateway writes its own to `~/.agentos/wallets/operator.secret` (mode 0600, rotated at every boot). The CLI reads that file on its own when `AGENTOS_AGENT_TOKEN` is not set and the gateway is local. Against a gateway on another machine the gateway token is the proof: a control WebSocket that authenticates with it from a non-loopback address (the desktop app in External mode, the web console, a remote CLI) is the operator's, unless it also presents an agent token. The address is the socket's own peer, never an `X-Forwarded-For` claim, so a process on the gateway's own host (which dials loopback) never becomes the operator by the token alone. An agent-bound connection is an agent whatever it declares (`--as-agent` only forces the agent rules for a person). For the agent: an order above `trading.approval_threshold_usd` (default 100) or above `trading.agent_max_price_impact_pct` (default 5; "price impact" is the price vs reference, venue fee and feed skew included) waits as `awaiting_approval` for `trading.approval_ttl_seconds` (15 minutes); an order that would push a wallet past `trading.daily_cap_usd` (default 1,000 per wallet per calendar day — `--all-wallets` spends up to N caps — with an order counted as max(in, out) in USD — an order whose sell side has no feed price is unpriced and waits, whatever the token it buys is worth — orders in flight included; 0 switches agent swaps off) is rejected, `expectedOutRaw` or not; `--slippage` above `trading.agent_max_slippage_pct` (default 5) is refused with `trading.slippage_too_high`. `agentos trade approve` / `reject`, `hide` / `unhide`, `probe --api-key`, `sync --full` and every vault command except `status`, `list` and `balances` fail from an agent's connection with `trading.operator_required`; `config set` on any `trading.` key is refused from an agent too (the gateway rejects the write as an invalid request). Those are the user's actions, in the app or their own terminal. `wallet status` and `trade status` leave out `vaultPath` for an agent. Swaps typed by a person are neither queued nor capped; if the price moves more than twice the slippage between quote and send they fail with `trading.price_moved` instead. `swap` also accepts the quote's `expectedOutRaw` / `minOutRaw` (`--expected-out-raw`, `--min-out-raw`) and refuses with `trading.price_moved` when the fill would be more than 2× the slippage worse than that quote. `--wait --wait-seconds N` blocks until each order settles (`confirmed`, `failed`, `rejected`, `expired`) or N seconds pass; `--wait-seconds` alone, without `--wait`, returns at once. A `submitted` order survives a gateway restart and is marked `failed` after 6 hours without a receipt. On Base and Robinhood Chain the first receipt a node serves can be a preconfirmation whose `l1Fee` is provisional, so every order kind (swap, send, revoke, approval, LP write) is settled from the receipt re-read once the head is past its block (up to 15 s; if that never happens the first one is used and `trading.receipt_provisional` is logged). `--client-id <id>` on `swap` and `send` is an idempotency key: a second call with the same id returns the existing order instead of placing another, so a retry after a timeout cannot trade twice — one id per intended order, the same id on every retry of it. After upgrading, if `agentos trade status --json` shows `ledgerRepair`, run `agentos trade sync --full` once. A swap's target and the approval's spender are pinned to the contracts the desk knows for the provider (a quote naming any other address is refused, not signed); the gas limit is the provider's or the estimate plus 20 %, and the order is refused up front when the wallet cannot cover value plus gas at the quoted fee. `--note` is stored as shown to the approver: control and bidi characters are dropped, whitespace collapses, and it is cut at 240 characters. Sends and revokes share the order pipeline (`kind` is `swap`, `send` or `revoke`). A send moves ETH by value or an ERC-20 by `transfer`, one plain transaction per recipient; several `--to` (up to 200, from flags or a `--file`) make one **batch** with a shared `batchId` that is judged, approved, rejected and reported as one. Guardrails differ from swaps on purpose: an **agent-initiated** send or revoke always waits for the user's approval — there is no threshold under which the agent sends alone — while the daily cap still counts the batch's total; a send typed by a person runs at once. Each leg is booked as a `withdraw` entry under its order. `trade bridge` moves ETH or the USD stable (USDC on Base, USDG on Robinhood Chain) to the other chain through Relay: it is judged like a send (an agent's always waits for approval and counts toward the cap), the engine re-quotes right before signing and sends only a deposit to the pinned Relay solver, the deposit is a `withdraw` on the origin chain and the fill a `deposit` on the destination, and the order stays `submitted` until that fill lands ([Bridge](https://useagentos.dev/docs/core/bridge)). `trade allowances` scans the wallet's own `Approval` logs incrementally, reads every remembered (token, spender) allowance live, and shows what is at stake (`exposureUsd` = the smaller of the allowance and the balance, in dollars); `trade revoke` sends `approve(spender, 0)`. `trade decode` names the function behind a hash or calldata (ERC-20, WETH, Permit2 and the Uniswap routers are known; anything else is reported as its selector, never guessed) and lists the receipt's transfers and approvals with token metadata; `tx.gasWei` is what the sender paid, the L1 data fee (`tx.l1FeeWei`) included on Base and Robinhood Chain. `trade network` reads each chain's head block and gas and flags a head older than a minute — the sign of an RPC that is behind. `trade lp` reads Uniswap V4 liquidity on Base and Robinhood Chain and never signs anything, so every form is allowed from an agent's connection (gateway methods `trading.lp.pool`, `trading.lp.ranges`, `trading.lp.position`, `trading.lp.positions`). Reads use the engine's RPCs (`trading.rpc_urls`) and the V4 library bundled with the `senior-unilp-manager` skill. `<token>` is an address or a symbol the engine resolves on that chain; with no `--chain`, `pool` and `ranges` try Base, then Robinhood Chain. A token's pools are found through the launchpad registries (Clanker, Liquid, Doppler), the hook-less fee tiers and — where the chain's public node serves full-history logs, as Robinhood Chain's does — the PoolManager's `Initialize` log, which also finds pools at unconventional fees. A log request that times out or hits a rate limit is asked once more and, for pool discovery, then searched over the last 2,000,000 blocks only (the card says so and is partial); every pool found is remembered per token, so a later failed log request still finds it. Only an explicit span refusal is remembered (for ten minutes) as "this node will not serve full history". The one shown is the deepest: pools with active liquidity before empty ones, pairs against the chain's quote assets (WETH, ETH, USDC, USDG) before other pairs, then by TVL; liquidity comes from the tick bitmap. A poolId's PoolKey is recovered the same ways; when none works the error is `trading.lp.pool_key_unknown` — pass the token instead. `pool`, `ranges` and `add` take a pair as `TOKEN/QUOTE` (`ETH/USDC`) or as a token with `--quote USDC` (RPC `quote`; both at once must agree), and `--fee <tier>` (RPC `feePct`) to pick a fee tier among the pair's pools: a percent (`0.05`, `0.05%`, `0.3`, `1`), V4's own units — any whole number of 100 or more, hundredths of a bip (`500` = 0.05 %, `3000` = 0.3 %) — or `dynamic`. Several pools on that tier (other hooks or tick spacings): the deepest wins. Naming a tier also derives its hook-less pools at the usual tick spacings, so an unusual tier is found where a node serves no logs. No pool on the tier is `trading.lp.not_found`, whose message and `details.tiers` name the tiers that do exist (`no 0.05% Uniswap V4 pool for BONER/USDG on Robinhood Chain; tiers that exist: 0.3%, 1%`); a poolId on a different tier than `--fee` is `trading.invalid`. "ETH/USDC 0.05 %" is `trade lp add ETH --quote USDC --fee 0.05 …` (or `add ETH/USDC --fee 0.05`). `positions` without `--wallet` covers every wallet in the vault on both chains; `--chain` may be repeated (`--chain base --chain robinhood`), while `pool`, `ranges` and `position` take one and refuse a repeat with `INVALID_ARGUMENT`. `--wallet` may name any address (read-only), but a token contract there fails with `trading.lp.not_a_wallet` and names the `trade lp pool` command to use instead. Closed positions are left out unless `--all`. A card lists at most 50 positions (out of range first, then by value) while its totals cover every position found. The scan usually takes under 15 s and never much more than its budget — 25 s by default, `--budget-seconds` (5–300) to change it: when the budget runs out the search stops, the card is `partialScan` and a warning names what was not read (the indexer's remaining pages, Transfer logs before a block) and how many of each wallet's positions were found; `totals.count` is everything found. A wallet holding more than 60 distinct tokens has USD prices looked up only for the chain's quote assets, the listed rows' tokens and the most-held others (up to 60); every other position is valued at its own pool's price, and a warning says so. With `--json`, the JSON is the first line of stdout; unless `--no-card` is also given, the result is written to `lp-cards/<kind>-…json` in the working directory (the 20 newest cards there are kept) and the last line on stdout is `publish_artifact path=<file> mime=application/vnd.agentos.lp+json` (run from an agent's shell, followed by ` nonce=<value>` from `AGENTOS_INLINE_ARTIFACT_NONCE`), which that shell turns into a card in the chat. Without `--json` the command prints a table and writes nothing. An error writes no card; with `--json` every error, including a bad or missing option, is `{"error": {"code", …}}` on stderr, and input errors (`INVALID_ARGUMENT`, `trading.invalid`, `trading.lp.not_a_wallet`, `trading.lp.pool_key_unknown`) exit 2. The payload is specified in [LP cards](https://useagentos.dev/docs/core/lp-cards); every card also echoes `request: {kind, params}` — the `trading.lp.<kind>` call that re-reads it. `trade markets` lists **every pool a token trades in, on every DEX** the chain has, in two sections: *priced in NVDA* (the token is the pool's quote asset — `AI/NVDA` on Bankr, `ORBIO/NVDA` on Pons) and *NVDA priced in* (the token is the base — `NVDA/USDG`, `NVDA/WETH`). It is read-only and allowed from an agent (gateway method `trading.markets`), and it is the one `trade` command whose `--chain` defaults to **robinhood**. Pools come from GeckoTerminal (the only listing with both sides; 20 a page, 5 pages by default, 10 with `--deep`, read in bursts of five and cached for 120 s per token — a cold read takes 20–60 s because GeckoTerminal's edge caches a page only after the first request, a warm one about a second), enriched by DexScreener; for a Stock Token the card also carries the Chainlink oracle price (`oracle`, with `stale`/`paused`) and each `base` row its premium against it. Rows under `--min-tvl` (default $10k) and **lookalikes** — a counterparty that borrows a Stock Token's symbol or name at another address — are dropped and counted (`--lookalikes` shows them, flagged). Each section is sorted by TVL; `viaUniswap` marks the pools the Uniswap route can use. A rate limit stops paging and the card says `partial`; no page at all is `trading.markets.unavailable`. The counts line also says how many rows `--limit` cut (`· 12 more over the limit`), and `counts.pageCapHit` tells a client when `--deep` would show more. Human output is the token line (price, oracle, premium), one table per section (`PAIR DEX TVL VOL 24H PRICE IN <TOKEN> AGE FLAGS`, flags `uni`, `stock`, `lookalike`; the base section's ratio column is `IN QUOTE`, the token priced in each row's counterparty) and a counts line. With `--json` the payload goes to stdout, the card to `markets-cards/markets-<symbol>-<stamp>.json` (20 newest kept) with the `publish_artifact … mime=application/vnd.agentos.markets+json` line last on stdout, unless `--no-card`; errors are the `{"error": …}` envelope on stderr, exit 1, and write no card. The payload is specified in [Stock Token markets](https://useagentos.dev/docs/core/markets). `trade lp collect|remove|add` change a Uniswap V4 position of a vault wallet through the same order pipeline as a swap or a send (gateway methods `trading.lp.collect`, `trading.lp.remove`, `trading.lp.add`; the contract is [LP writes](https://useagentos.dev/docs/core/lp-write)). Each creates **one order that always waits for approval** — from an agent or from you, whatever the amount — which is then approved in the app or with `trade approve <id>`. The engine plans the call with the `senior-unilp-manager` skill's V4 encoders, simulates it from the wallet (`eth_simulateV1`, with any pending approvals run first; a node without it gets `eth_call`), and refuses a call that would revert with `trading.simulation_failed`. On approval it re-reads the pool: an `add` whose required amounts now exceed the approved maxima, or a `remove` whose amounts fall below the approved minimums, fails with `trading.price_moved`; the deadline is the latest block's timestamp + 600 s, set then. An `add` first approves exactly what it may pull — `ERC20.approve(Permit2, max)` and `Permit2.approve(token, PositionManager, max, now + 30 min)`, each only when short — never an unlimited amount. `collect` is a zero-liquidity decrease (no slippage); `remove --pct N` takes N % of the liquidity with minimums `--slippage` (default 1 %) under today's amounts, plus every uncollected fee, and 100 burns the NFT; `add` takes `--usd` (split between the two sides as the range needs at today's price) or token amounts (`--amount-base` and/or `--amount-quote`; the binding one wins), `--range` `mcap:LO-HI` (`2M`, `2.5m`, `750k`, `1e6`), `pct:N` (± N % around the price), `above[:N]` (one-sided, all base token: from just above the price up N %), `below[:N]` (one-sided, all quote token: from just below the price down N %; N defaults to 20 for both, and the band is snapped to the tick spacing and kept off the current tick, so `plan.oneSided` is `base` / `quote`), `full` or `ticks:LO:HI` (multiples of the tick spacing) — default `pct:20` — and `--to-position` to top up an existing position instead of minting (with `--to-position`, a `--quote`/`--fee` given must describe that position's pool, else `trading.invalid`). `collect` on a position whose uncollected fees read as zero on both sides is refused with `trading.lp.nothing_to_collect` — it would only pay gas — unless `--allow-empty` (RPC `allowEmpty: true`). Nothing is swapped for you: a wallet short of a side the range needs is refused with `trading.insufficient_balance` naming that side (a range entirely above or below the price needs only one token). The position must belong to a vault wallet (`trading.lp.not_owner`) and hold liquidity (`trading.lp.position_closed`). An agent's `add` counts toward the daily cap; `collect` and `remove` do not. The output is `{"order": …}` like `trade revoke`, with `order.plan` (the LpPlan) and, once confirmed, `received`, `spent` and a mint's new `tokenId`; `--wait` blocks until the order is decided and settled. With `--json`, a confirmed order is followed by the refreshed card — `lp position` (after a burn, the wallet's `lp positions`) — written to `lp-cards/` and announced by the `publish_artifact` line, the last on stdout, unless `--no-card`. Input errors (`trading.invalid`, `trading.lp.range_invalid`, `trading.lp.not_owner`, `trading.lp.position_closed`, `trading.lp.nothing_to_collect`, `trading.lp.not_found`) exit 2; everything else exits 1. The ledger books a confirmed write as `lp_collect`, `lp_remove` or `lp_add` entries, one per token moved. `trade dca` manages **DCA mandates**: a recurring buy the engine owns and runs itself — `create ETH --usd 10 --every 1d --cap 300` buys $10 of ETH with the chain's USDC every day until $300 is spent (gateway methods `trading.dca.create|get|list|approve|reject|pause|resume|stop|run|update`; the contract is [DCA mandates](https://useagentos.dev/docs/core/dca)). The cap, the run count and the schedule are rows in the ledger, enforced by the engine; every buy is an ordinary swap order (guardrails, approval threshold, daily cap, ledger) with the mandate's id and a `DCA ETH · buy 3/30` note, and no agent turn is spent on it. `--every` takes `30m`, `2h`, `1d`, `1w` or a plain number of seconds (minimum 60); `create` needs `--cap`, `--runs` or both (the cap defaults to `--usd × --runs`); `--quote` defaults to the chain's USDC and is required on Robinhood Chain; `--max-price` skips a buy while the token's price is above it (no price known → skipped too); `--start next` puts the first buy one interval after activation instead of at once. A mandate created from an agent's shell always answers `status: "awaiting_approval"` and expires after 24 h without a decision; yours starts `active`. `create`, `list` and `show` are allowed from an agent; `approve`, `reject`, `pause`, `resume`, `stop`, `run` and `update` are the user's and answer `trading.operator_required` to an agent. Three skipped (balance, daily cap) or failed buys in a row pause the mandate; `resume` does not make up missed buys. `update --every` re-anchors the schedule at now; lowering `--cap` below what is spent completes the mandate. `run --wait` waits for the order it placed (like `swap --wait`) and prints the mandate again once it settled. With `--json` the payload is the first line of stdout and, unless `--no-card`, it is written to `dca-cards/<mandate|mandates>-<id|live|all>-<utc stamp>.json` (the 20 newest kept) and announced by the last line, `publish_artifact path=<file> mime=application/vnd.agentos.dca+json`; without `--json` a mandate prints as a panel and `list` as a table. Input and state errors (`INVALID_ARGUMENT`, `trading.dca.invalid`, `trading.dca.bad_state`, `trading.dca.not_found`, `trading.invalid`, `trading.token_not_found`) exit 2; everything else exits 1; under `--json` every error is `{"error": …}` on stderr and writes no card. `trade trigger` manages **price triggers**: a conditional order the engine watches and fires by itself — `create ETH --sell --pct 50 --below 3800` sells half the wallet's ETH for USDC once ETH is at or under $3,800, `--buy --usd 50 --below 3500` buys the dip, `--sell --pct 100 --trail 10` is a trailing stop 10 % under the highest price since arming, and `--alert --above 5000` only notifies you (gateway methods `trading.trigger.create|get|list|approve|reject|pause|resume|stop|fire`; the contract is [Price triggers](https://useagentos.dev/docs/core/triggers)). Pass exactly one condition (`--below`, `--above`, `--trail`) and one action: `--sell` with exactly one size (`--pct` of the balance at fire time, a token `--amount`, or `--usd`), `--buy` with `--usd`, or `--alert` with none; a wrong combination exits 2 before anything is sent. `--below`/`--above` take a USD price (`3800`) or a percent of the price now (`--below -10%` or `10%`, `--above +15%` or `15%`), resolved to a price when the trigger is created. The engine checks the price every tick (60 s) and fires only after the condition held on two checks in a row; an unknown price never fires. A sell or buy is one ordinary swap order (guardrails, approval threshold, daily cap, ledger) with the trigger's id and a `Stop-loss ETH · fired at $3,790` note; a fire that cannot act (nothing to sell, not enough USDC) pauses the trigger, and three failed fires in a row pause it too. `--for` (`30m`, `2h`, `1d`, `1w` or seconds, minimum 60) lets it expire unreached; without it the trigger stays until it fires or you stop it. A trigger created from an agent's shell always answers `status: "awaiting_approval"` and expires after 24 h without a decision; yours is `armed` at once. `create`, `list` and `show` are allowed from an agent; `approve`, `reject`, `pause`, `resume`, `stop` and `fire` are the user's and answer `trading.operator_required` to an agent. `fire --wait` waits for the order it placed and prints the trigger again once it settled. With `--json` the payload is the first line of stdout and, unless `--no-card`, it is written to `trigger-cards/<trigger|triggers>-<id|live|all>-<utc stamp>.json` (the 20 newest kept) and announced by the last line, `publish_artifact path=<file> mime=application/vnd.agentos.trigger+json`; without `--json` a trigger prints as a panel and `list` as a table. Input and state errors (`INVALID_ARGUMENT`, `trading.trigger.invalid`, `trading.trigger.bad_state`, `trading.trigger.not_found`, `trading.invalid`, `trading.token_not_found`) exit 2; everything else exits 1; under `--json` every error is `{"error": …}` on stderr and writes no card. `trade protect` creates a **bracket**: a take-profit and a stop-loss on one position, whichever fires first stops the other (one cancels the other) — `protect ETH --tp +20% --sl -10%` sells all of the wallet's ETH for USDC once ETH is 20 % up or 10 % down, `--tp 4560 --sl 3420` uses prices, `--trail 10` makes the stop a trailing stop, `--tp-pct 50` takes profit on half and lets the stop guard the rest, and `--alert` is a range alert that only notifies you when the price leaves the range; `trade bracket list|show|approve|reject| pause|resume|stop|fire` manages one (gateway methods `trading.bracket.create|get|list|approve|reject|pause|resume|stop|fire`; the contract is [Brackets](https://useagentos.dev/docs/core/brackets)). `--tp` is required (a price, or `+20%`/`20%` over the price now) with exactly one of `--sl` (a price, or `-10%`/`10%` under it) or `--trail`; pass at most one size (`--pct`, `--amount`, `--usd`; none is `--pct 100`); `--tp-pct` needs `--pct` (or the default) and may not exceed it; `--alert` takes no size; a wrong combination, or a take-profit price not above the stop price, exits 2 before anything is sent. The two legs are ordinary price triggers with the trigger's checks (two ticks in a row, guardrails, approval threshold, daily cap); while one leg's order is open the other is on hold, a filled leg stops the other, and a failed fire releases it. A bracket created from an agent's shell always answers `status: "awaiting_approval"` and one approval arms both legs; yours is `armed` at once. `create` (`protect`), `list` and `show` are allowed from an agent; `approve`, `reject`, `pause`, `resume`, `stop` and `fire` are the user's and answer `trading.operator_required` to an agent. `fire` fires the `--leg` given or the nearer one; `fire --wait` waits for its order and prints the bracket again once it settled. The legs do not appear in `trade trigger list` and refuse the `trade trigger` writes. With `--json` the payload is the first line of stdout and, unless `--no-card`, it is written to `trigger-cards/<bracket|brackets>-<id|live|all>-<utc stamp>.json` (the 20 newest trigger and bracket cards kept) and announced by the last line, `publish_artifact path=<file> mime=application/vnd.agentos.trigger+json`; without `--json` a bracket prints as a panel and `list` as a table. Input and state errors (`INVALID_ARGUMENT`, `trading.bracket.invalid`, `trading.bracket.bad_state`, `trading.bracket.not_found`, `trading.invalid`, `trading.token_not_found`) exit 2; everything else exits 1; under `--json` every error is `{"error": …}` on stderr and writes no card. `[trading]` config keys (each also an environment variable with the `AGENTOS_TRADING_` prefix): `enabled`, `provider` (`aggregator` | `uniswap`), `aggregator_base_url` (default `https://agg.useagentos.dev`), `aggregator_trusted_spenders` (list of 0x addresses, default empty: contracts an aggregator quote may name as the approval spender and swap target on top of the built-in AgentOS Router and 0x AllowanceHolder; added, never replacing them; mixed case must pass its EIP-55 checksum; set it as a JSON list of the verified addresses, e.g. `'["0x…"]'`), `uniswap_api_key`, `uniswap_api_key_env` (default `UNISWAP_API_KEY`), `rpc_urls` (chain id → JSON-RPC URL; the wallet sync's bulk ERC-20 balance read still tries the chain's public node first), `approval_threshold_usd`, `daily_cap_usd` (0 = agent swaps off), `approval_ttl_seconds`, `agent_max_price_impact_pct`, `agent_max_slippage_pct`, `default_slippage_pct` (unset = provider auto), `unlock_mode` (`auto` | `manual`; the default for `wallet setup` without `--mode`, and with `manual` the vault never reads or writes `unlock.key`: auto setup or `wallet mode auto` is refused, `wallet.unlock_mode_policy`, and a stored password from an earlier auto vault is ignored until `agentos wallet mode manual` deletes it), `sync_interval_seconds`, `price_ttl_seconds`. A change applied without a restart (`config set`, `agentos config reload`) is what the engine's own loop enforces from its next tick: `enabled = false` stops DCA buys and trigger fires and refuses to sign anything, an order already waiting for approval included, and a new cap or threshold judges the next automated buy. Read: [Wallets and Trading](https://useagentos.dev/docs/core/features/trading) ## Memory ```sh agentos memory status --deep --agent main --json agentos memory index --force --agent main agentos memory list --source all agentos memory ingest /path/to/docs agentos memory curated get --target memory agentos memory curated add "Important project convention" agentos memory curated remove "Important project convention" agentos memory search "preference" agentos memory show <path> agentos memory embedding-download agentos memory raw-fallbacks list agentos memory raw-fallbacks show <path> agentos memory recall status [--session <session-key>] [--show-block] [--json] agentos memory recall pause --session <session-key> agentos memory recall resume --session <session-key> agentos memory forget --session <id-or-key> [--session ...] [--agent <id>] [--dry-run] [--json] ``` `memory recall status` shows the `[memory.recall]` settings, paused sessions, and the last proactive-recall outcome per session (or for one session with `--session`); `--show-block` prints the fenced block that was injected. When the deep lane ran, the outcome also names its model, the provider, and the rule that chose it (`env`, `auxiliary_task`, `memory_recall`, `session_model`, `agent_model`, `router_hold`, `llm`, or an auxiliary fallback). The same values are in `--json` as `deepProvider` / `deepModel` / `deepModelRule`. `pause` / `resume` switch proactive recall off and on for one session only; the switch lives in the gateway until it restarts and does not change `[memory.recall] enabled`. `agentos config set <key> <value> --config <path>` says whether a running gateway applies the key on its own or needs a restart; `[memory.recall]` and `[memory.nudge]` apply without one. `memory status --json` also counts, for `MEMORY.md` and `USER.md`, the entries whose origin is recorded (`tracked`) and those without one (`untracked`). `memory forget` removes what the selected sessions taught the agent: curated entries with any origin from them (an entry that also came from other sessions is removed whole and listed as `mixed`), note blocks they saved where every copy of that text in the note is theirs (an edited, extended or shared block is listed as `unmatched`, reason `changed` or `ambiguous`, and left alone) and their session index documents. The sessions are then kept out of indexing; what could not be removed keeps its lineage, so running the forget again retries it. One forget runs at a time per agent. A selector is a full session id (that transcript) or a full session key (every transcript under it, including later ones); a prefix never matches. An unresolved selector changes nothing and exits 2; a report with `errors` exits 1. Transcripts, turn-capture files, checkpoints and untracked or hand-edited text are not removed; the report's `notCovered` says so. Read: [Memory](https://useagentos.dev/docs/core/features/memory) ## Durable Agents and Scheduling ```sh agentos agents list agentos agents add research --name Research --workspace /path/to/research --model gpt-5.4-mini --description "research agent" agentos agents delete research -f agentos cron list agentos cron add --every 1h --text "Summarize important updates" --name hourly-summary agentos cron status <job-id> agentos cron run <job-id> -y --json # run now; may post into a live session agentos cron remove <job-id> -y --json agentos cron runs <job-id> agentos cron output <job-id> ``` `--job-kind` picks what fires: `reminder` (delivers `--text` verbatim, no LLM), `script` (runs a file, no LLM), `agent_turn` (the agent runs `--text` as a prompt), or `system_event`. It defaults to `auto`, which is `reminder` for normal targets — so the example above repeats that sentence hourly rather than summarizing anything. Add `--job-kind agent_turn` to have the agent do the work. ### Running a script on a schedule, without a model ```sh agentos cron add --every 5m --script watch-memory.sh --name memory-watchdog agentos cron update <job-id> --script watch-disk.sh --workdir /srv/app agentos cron add --every 15m --script watch_rss.py --name hn \ --script-arg --url --script-arg https://news.ycombinator.com/rss ``` `--script` implies `--job-kind script` and resolves relative to `~/.agentos/scripts/`; absolute paths, `~`, and `..` are refused, and so is a symlink out of that directory. Subdirectories are allowed, and `{job_id}` anywhere in the path is replaced with the created job's own id, so a job can own a directory named after itself in one `add`. `.sh`/`.bash` run under bash, anything else under python. `--workdir` sets the script's working directory; a relative value resolves against the script's own directory, which is also the default. `--script-arg` (repeatable) passes argv straight to the script — never through a shell. Non-empty stdout is delivered verbatim, empty stdout is a silent run, and a non-zero exit or `--timeout` delivers the error and fails the job. Secrets are masked in the output, and the gateway token is withheld from the child process. A script job runs under the agent's rules: the scheduler hands it an agent token, so an `agentos trade` command inside it is an agent order (threshold, daily cap, approval) and the operator-only commands fail in it. The bundled `cron-watchers` skill ships scripts for RSS, JSON endpoints, and GitHub repos that already follow this contract. #### Seeing what the script did A job scheduled from the CLI has no conversation attached, so "delivered verbatim" has nowhere to deliver to: the stdout lands on the run record and the chat stays empty. `--session-key` names the chat the job reports into — the run itself stays isolated, only the output is mirrored there: ```sh agentos sessions list # copy the key of the chat you want agentos cron add --every 5m --script watch-memory.sh --name memory-watchdog \ --session-key 'agent:main:webchat:<id>' ``` Either way `agentos cron runs <job-id>` shows each run's `Output` and `Delivery` columns. The `Output` column is a 500-character preview, so the whole list stays small no matter how much a job prints; `agentos cron output <job-id>` prints one run's output in full (the most recent run, or `--run <run-id>` for an older one — run ids come from `agentos cron runs --json`). A `Delivery` of `fwd:no_session_target` is the scheduler saying the script printed something that reached no conversation — add `--session-key`. Jobs created from the Web UI or from a chat already carry their originating session, so their output shows up in that chat without any extra flag. Add `--script` to an `--job-kind agent_turn` job instead and it becomes a pre-run collector: its stdout is handed to the agent as context, and a tick where it prints nothing skips the turn entirely — no LLM call at all. See [Scheduling](https://useagentos.dev/docs/core/scheduling). No LLM runs, so no tokens are spent — but nothing reviews the script before it executes either. It runs on this host as you, unattended, so treat `~/.agentos/scripts/` as trusted as your shell profile. Only an interactive CLI or Web caller can create one; the in-agent `cron` tool refuses `job_kind='script'` from a channel. ### Announcing to a specific channel `--announce --channel telegram --to <chat-id>` pins where a job reports, and `--account`, `--no-deliver`, `--best-effort-deliver`, and `--webhook-url` cover the rest. The in-agent `cron` tool accepts the channel case too, through a `delivery` object — also restricted to an interactive CLI or Web caller, so a chat participant cannot redirect a job into a room they were never in. Webhook delivery and failure destinations stay CLI/Web/RPC-only. See [Scheduling](https://useagentos.dev/docs/core/scheduling#naming-a-channel-recipient). ### Letting a cron job run shell-based skills By default, cron jobs of kind `agent_turn` run elevated under the `bypass` mode (controlled globally by `permissions.cron_default_mode`). This allows them to run shell-based commands (like those in skills) without interactive approval prompts. That default applies to jobs you create. A job the in-agent `cron` tool creates from a chat channel (or any turn other than your own CLI/Web session) is stored with `elevated = "off"` and a `deny` list of the tools its creator lacked; see [Tools, Approvals, and Sandbox](https://useagentos.dev/docs/core/tools-and-sandbox#delegated-work-and-caller-authority). If you wish to opt out a job from elevated execution, pass `--no-elevated`: ```sh agentos cron add --every 6h --agent main --no-elevated \ --name "LP check" --text "Use the senior-unilp-manager skill to review my LP positions" agentos cron list # the Elevated column shows the mode agentos cron update <job-id> --elevated-mode bypass ``` Related flags: `--elevated` (which sets the job to explicitly run elevated), `--elevated-mode {bypass,full}`, and `--tool-policy '<json>'` (`profile`, `allow`, `alsoAllow`, `deny` — can only narrow the cron baseline). `profile` must be one of `coding`, `full`, `memory_only`, `messaging`, `minimal`; omit the key to inherit rather than inventing a name, since an unknown one is rejected when the job is written. Elevation is only accepted on agent-turn jobs; reminders and system events never run an agent turn with the job's tool policy. **What you are accepting.** Every time the job fires, with nobody watching, an LLM decides which shell commands run on this host as you, and they run — no approval prompt, no sandbox, with your environment variables and API keys passed through to the child process. If the skill signs transactions, an unattended turn can sign and broadcast them. `write_file`, `git_commit`, `apply_patch` and `execute_code` stay off the offered tool surface, but `exec_command` reaches all of them, so treat that list as a default rather than containment. Most importantly, anything the job reads from the network (`web_fetch`, `web_search`, RPC responses, token metadata) is untrusted input one reasoning step away from that shell. Still enforced: the never-bypassable command denylist; the sensitive-path block on *destructive* operations against `~/.ssh`, `.env*` and private keys, which `bypass` keeps and `full` disables; workspace lockdown and write-deny globs; no private-memory reads (force-denied for every cron caller, and no tool policy can revive them); no `cron` tool, so the job cannot schedule or elevate another; and no `message` tool, so output goes only where you configured delivery. Note the sensitive-path block does not stop a *read* of a secret file — once `exec_command` is on, secrets on disk are reachable. A cron turn also never loads `USER.md`, so anything per-user the skill needs (wallet address, chain, thresholds) has to come from the task text or the environment. Practical shape: one skill and one narrow task per elevated job, a tight `--timeout`, `--session-target isolated`, delivery and a failure destination configured, and if the skill has a dry-run/confirm handshake, keep cron on the read half and leave broadcasts to an interactive session. ### Overlapping runs, job health, and missed runs ```sh agentos cron add --every 5m --job-kind agent_turn --text "Check the queue" --concurrency replace agentos cron update <job-id> --concurrency forbid agentos config set scheduler.startup_agent_delay_seconds 120 ``` `--concurrency` (on `add` and `update`) says what happens when a run comes due while the previous one is still going: `forbid` (default) skips it, `replace` cancels the running run and starts the new one, `allow` runs both. `agentos cron list --json` reports each job's `concurrency` and a `health` block — `consecutive_failures`, `last_error` (the last finished run's error), and `degraded` (true from 3 failures in a row). After a laptop sleep each overdue job runs once, however many runs it missed. After a gateway restart up to 5 missed jobs are caught up, staggered over 10 seconds; missed agent jobs wait `scheduler.startup_agent_delay_seconds` (default `120`, `0` = no wait) so they do not compete with channel start-up. Read: - [Durable Agents](https://useagentos.dev/docs/core/agents) - [Scheduling](https://useagentos.dev/docs/core/scheduling) - [Approvals and Permissions](https://useagentos.dev/docs/core/approvals-and-permissions) ## Sandbox Posture Controls ```sh agentos sandbox status agentos sandbox status --json agentos sandbox bypass agentos sandbox full agentos sandbox on agentos sandbox reset ``` `agentos sandbox status` shows the current sandbox posture (`on`, `bypass`, `full`), whether runtime sandboxing and security grading are active, and default permissions. - `agentos sandbox on`: Restores the default sandboxed posture (`sandbox = true`, `security_grading = true`, `permissions.default_mode = "off"`). - `agentos sandbox bypass`: Disables runtime sandboxing and auto-grants approvals except for sensitive paths (`permissions.default_mode = "bypass"`). - `agentos sandbox full`: Disables runtime sandboxing and skips approval and sensitive-path gates (`permissions.default_mode = "full"`). - Neither mode answers a skill signing prompt: a bundled skill command that signs with its hot-wallet key and moves funds always waits for you (see [Skill signing prompts](https://useagentos.dev/docs/core/approvals-and-permissions#skill-signing-prompts)). - `agentos sandbox reset`: Resets sandbox posture to AgentOS defaults (`bypass`). Pass `--config <path>` to target an explicit configuration file. Changes require a gateway restart (`agentos gateway restart`) to apply to running processes. Read: [Tools, Approvals, and Sandbox](https://useagentos.dev/docs/core/tools-and-sandbox) ## Cost, Diagnostics, and Replay ```sh agentos context agentos context --top 10 --json agentos cost agentos cost savings agentos diagnostics status agentos diagnostics on agentos diagnostics off agentos replay --session <session-key> --turn <turn-id> agentos replay -s <session-key> -t <turn-id> ``` `agentos context` answers a different question from `agentos cost`: not what a session spent, but what every request carries before the conversation starts. Tool schemas dominate it — around 7,300 tokens on a stock install, charged on every call in every turn — and the command prices each `[tools] profile` against the current one so the trade is visible before you make it. A profile is fixed for the session, so narrowing it does not disturb the prompt cache. `--top <n>` (default 10) sets how many of the largest tools it lists. The figure already leaves out deferred tools (`tools.defer_loading`, on by default): the long tail the model loads on demand through `tool_search`, which the command counts on its own line. `agentos config set tools.defer_loading false` sends every tool on every request again. Two turn-speed switches, both on by default. The first stops asking api.openai.com and OpenRouter for parallel tool calls; the second keeps each router tier's own thinking level instead of lowering it on cheap tiers (c0 at most `low`, c1 at most `medium`): ```sh agentos config set tools.parallel_calls false agentos config set agentos_router.effort_by_tier false ``` The loop guard (on by default) tells the model when it keeps repeating a tool call that returns the same result, then refuses the repeat, and ends the turn with `loop_detected` if it tries again. To only log those decisions instead: ```sh agentos config set tools.loop_guard observe ``` A reply that loops on the same line, paragraph or phrase is cut after its first copy and continued once (`[llm.repetition_guard]`, on by default; see [Providers and Models](https://useagentos.dev/docs/core/providers-and-models#repetitive-output-guard)). To let such replies run to the output limit instead: ```sh agentos config set llm.repetition_guard.enabled false ``` Every CLI command logs to stderr at `INFO` and above, so its output is only the command's own. Set `AGENTOS_LOG_LEVEL=debug` to see the debug-level events too (the gateway process keeps its own configured `log_level`, `DEBUG` by default, and `agentos chat` its `WARNING`). `agentos cost` aggregates and displays model usage and estimated cost reports from the gateway: ```sh agentos cost [--by-model] [--json] [--csv] agentos cost --start-date YYYY-MM-DD --end-date YYYY-MM-DD agentos cost --agent-id <agent-id> --channel-type <channel-type> agentos cost --tool-name <tool-name> --skill <skill-name> agentos cost --export /path/to/export.csv ``` | Option | Purpose | | --- | --- | | `--by-model` | Group aggregate rows by model. | | `--json` | Emit machine-readable JSON. | | `--csv` | Emit machine-readable CSV. | | `--start-date` | Filter by start date (YYYY-MM-DD). | | `--end-date` | Filter by end date (YYYY-MM-DD). | | `--agent-id` | Filter by agent ID. | | `--channel-type` | Filter by channel type. | | `--tool-name` | Filter by tool name. | | `--skill` | Filter by skill name. | | `--export` | Path to export results (JSON/CSV). | ### `agentos cost savings` `agentos cost` answers "what did I spend"; `agentos cost savings` answers "what did the [Pilot Router](https://useagentos.dev/docs/core/features/pilot-router) save me". It reads the local decision log (`~/.agentos/logs/decisions-*.jsonl`) rather than the gateway, so it works with the gateway stopped: ```sh agentos cost savings # summary + per-route table agentos cost savings --json agentos cost savings --csv agentos cost savings --start-date 2026-08-01 --end-date 2026-08-31 agentos cost savings --pdf ~/pilot-router-savings.pdf ``` | Option | Purpose | | --- | --- | | `--pdf` | Write a branded, shareable PDF report to this path. | | `--json` | Emit machine-readable JSON. | | `--csv` | Emit machine-readable CSV, one row per route pair. | | `--start-date` | Filter by start date (YYYY-MM-DD, UTC, inclusive). | | `--end-date` | Filter by end date (YYYY-MM-DD, UTC, inclusive). | | `--log-dir` | Read a decision-log directory other than `~/.agentos/logs`. | **Read the number correctly.** The baseline is *the most expensive model configured in `[router.tiers]`* — what every routed turn would have cost had it gone to your top tier — and not the model the request arrived with. Only input tokens are priced, at list rates, so the figure is a floor rather than a full-turn saving. The report covers routing alone: tool-result projection, short-reply enforcement, prompt-cache hits and thinking mode are excluded, even though the decision log carries them too. The `Requested` column names the model the turn asked for, which is *not* the price comparison — a turn can be routed back onto the requested model and still show a saving, because the top tier is dearer than both. Turns are logged only when the decision log is being written, so the window starts at your oldest retained `decisions-*.jsonl` file. Use diagnostics and replay when you need to understand why a turn behaved a certain way. For Prometheus metrics (`/metrics`), OTLP trace export, and log retention settings under `[observability]`, see [Configuration](https://useagentos.dev/docs/core/configuration#observability). `agentos replay` prints one recorded turn from the decision log as a transcript. It is read-only: no tools are re-executed. | Option | Purpose | | --- | --- | | `--session` / `-s` | Session key (required). | | `--turn` / `-t` | Turn ID (required). | Read: - [Usage and Cost](https://useagentos.dev/docs/core/usage-and-cost) - [Diagnostics and Replay](https://useagentos.dev/docs/core/diagnostics-and-replay) - [Configuration](https://useagentos.dev/docs/core/configuration) ## Doctor, models, migrate, reset ```sh agentos doctor # --deep is the default agentos doctor --quick --json agentos doctor --agent main --gateway ws://localhost:18791/ws agentos doctor --config ./agentos.toml # inspected when the local gateway is unavailable agentos doctor --token "$AGENTOS_TOKEN" # default: AGENTOS_GATEWAY_TOKEN, then auth.token agentos models list agentos models list --provider openrouter --capability tools --json agentos migrate # dry-run; auto-detects ~/.openclaw and ~/.hermes agentos migrate --source hermes --preset full --apply --migrate-secrets agentos migrate hermes --source <dir> --profile <name> --preset user-data agentos migrate openclaw --skill-conflict rename --overwrite --json agentos reset --key <session-key> ``` `agentos doctor` exits 1 when the install is not ready. It presents the gateway token from `--token`, `AGENTOS_GATEWAY_TOKEN` or `auth.token` in the config. Its `gateway` findings cover network exposure: a non-loopback bind without auth, wildcard `control_ui.allowed_origins`, CORS `*` with credentials off loopback, `trusted-proxy` mode without `auth.trusted_proxy`, failed-auth rate limiting off, loopback exempt from the lockout behind a same-host proxy, and a token shorter than 24 characters. When no gateway answers (one that refuses to start, or admits nobody) they are read from the config file instead. Their fix commands write that file (`config set` with `--config <file>`); see [Remote Access](https://useagentos.dev/docs/core/remote-access). `--deep` (the default) includes deeper memory diagnostics for `--agent` (default `main`); `--quick` runs the shallow checks only. `--gateway` (or `AGENTOS_GATEWAY_URL`) picks the gateway to ask, and `--config` names the config to inspect when the local gateway is unavailable. `agentos models list` talks to the running gateway and can filter by `--provider` and `--capability`/`-c`. `agentos migrate` with no subcommand scans `~/.openclaw` and `~/.hermes`; there `--source` takes the source ids (`openclaw`, `hermes`, comma-separated) and is required when both are found and stdin is not a TTY. `agentos migrate openclaw` and `agentos migrate hermes` take a source directory as `--source` instead. Every form is a dry-run report until `--apply`: | Option | Purpose | | --- | --- | | `--apply` | Apply the migration; without it only a dry-run report is produced. | | `--preset user-data\|full` | Migration preset (default `full`). | | `--profile <name>` | `hermes` only: Hermes profile name under `~/.hermes/profiles`. | | `--migrate-secrets` | Copy recognized secrets (off by default). | | `--overwrite` | Overwrite target workspace files after item-level backups. | | `--include` / `--exclude` | Comma-separated migration option ids to include or exclude. | | `--skill-conflict skip\|overwrite\|rename` | What to do when a skill already exists (default `skip`). | | `--persona-conflict` | `openclaw` and auto-detect only: resolve SOUL/USER/AGENTS conflicts with `prompt` (default), `use-agentos`, `use-openclaw`, `merge`, or `skip`. | | `--config` | AgentOS config path to write or preview. | | `--json` | Emit machine-readable JSON. | `agentos reset --key <session-key>` rotates the session to a fresh transcript through the gateway (`--gateway`, default `http://localhost:18791`). It exits 1 when the gateway refuses the reset, and the session is then preserved. ## MCP Client Servers `agentos mcp` edits the `[[mcp.servers]]` entries in the config file; no gateway is needed. `probe` and `doctor --probe` open a one-off connection from the CLI process itself (a stdio server is spawned as a child of your shell), list the server's tools, and close it. ```sh agentos mcp list [--json] agentos mcp status [--json] agentos mcp add fs --command npx --arg -y --arg @modelcontextprotocol/server-filesystem \ --arg /srv/data --cwd /srv --env LOG_LEVEL=warn --include 'read_*,list_*' --exclude write_file agentos mcp add docs --url https://mcp.example.com/mcp [--transport sse] [--header K=V] [--oauth] agentos mcp disable fs agentos mcp enable fs agentos mcp probe fs [--timeout 20] [--json] agentos mcp doctor fs [--probe] [--json] agentos mcp remove fs ``` | Command | Notes | |---|---| | `list` / `status` | Config-only view; `status` adds counts. `--json` rows carry `envKeys`/`headerKeys` (names only, never values). | | `add <name>` | Exactly one of `--command` (stdio; with `--arg` repeatable, `--cwd`, `--env K=V` repeatable) or `--url` (`--transport sse\|streamable_http`, default `streamable_http`; `--header K=V`, `--oauth`). `--include`/`--exclude` take globs, repeatable or comma-separated. Also `--tool-timeout`, `--connect-timeout`, `--disabled`, `--replace` (overwrite in place). The first server added switches `mcp.enabled` on; an explicit `mcp.enabled = false` next to existing servers is kept. | | `remove` / `enable` / `disable <name>` | Edit one entry; a disabled server is kept but never connected. | | `probe <name>` | Connect, list tools, mark which the tool filter registers, close. Exit 1 when unreachable. | | `doctor <name> [--probe]` | Validate the definition (command on PATH, `cwd` exists, URL shape, misplaced fields), then optionally probe and flag filter patterns that match no tool. Exit 1 on any error. | Every write validates the whole config, backs the file up, and rewrites it (comments are not preserved). `mcp` is operator-only: with a gateway running the change is held until `agentos config reload`, then applies on restart. Errors with `--json` go to stderr as `{"error":{"code":…}}` — `INVALID_ARGUMENT` (exit 2), `NOT_FOUND` / `ALREADY_EXISTS` (exit 1). Guide: [MCP Client Guide](https://useagentos.dev/docs/core/mcp). Settings without an `add` flag are edited in the file: per-server `defer_loading` (`"auto"` | `true` | `false`: keep the server's tool schemas behind `tool_search`), and under `[mcp]` `defer_tool_threshold` (8), `defer_total_tool_threshold` (20) and `instructions_max_chars` (2000; server text quoted in the system prompt, `0` = none). ## MCP Server Bridge ```sh agentos mcp-server run agentos mcp-server run --gateway ws://localhost:18792/ws ``` Read: [MCP Server Bridge](https://useagentos.dev/docs/core/mcp-server) ## Install Inventory `agentos dist` emits `workspace-state.json` — a reproducible, versioned inventory of the install for support, release QA, or environment comparison: ```sh agentos dist agentos dist --output workspace-state.json ``` With no flags the payload prints to stdout. `--output` (`-o`) writes it to the given file instead (creating parent directories) and prints the resolved path. The payload (`schema_version`, `agentos_version`, `python_requires`, `bundled_channels`, `bundled_tools`, `gateway_defaults`) is derived only from installed package metadata plus hard-coded constants — byte-identical per install, with no environment values, paths, or secrets. Read: [Operations](https://useagentos.dev/docs/core/operations#install-inventory) --- # Web UI > Source: https://useagentos.dev/docs/core/web-ui The AgentOS Web UI is the local control console for setup, chat sessions, approvals, channels, logs, agents, usage, and operational status. It is the best surface when you want browser-based chat, visible tool activity, durable approvals, and a quick view of runtime health. ## Start the Web UI Run the gateway in the foreground: ```sh agentos gateway run ``` Open: ```text http://127.0.0.1:18791/control/ ``` Or start a managed background gateway: ```sh agentos gateway start --json agentos gateway status ``` The default gateway binds to `127.0.0.1` for safety. For gateway lifecycle, host/port, and exposure details, see [Gateway](https://useagentos.dev/docs/core/gateway). ## React bundle and development Published AgentOS wheels contain a prebuilt React/Vite Control UI. The gateway serves that single application for the base route and every deep link; there is no legacy-console fallback. The SPA shell is never cached, while content-hashed assets are cached immutably. A source checkout must build the browser bundle before starting the production gateway: ```sh python scripts/build_control_ui.py build npm --prefix frontend run check ``` The shared build command requires Node.js 22 or newer, performs the clean npm install, builds and verifies the bundle, and generates its exact third-party license ledger. The source-install scripts perform it automatically. If a checkout is started without a bundle, the Control UI returns an actionable `503` instead of a blank page or a different interface. Gateway boot and `agentos doctor` also warn when a checkout's bundle is older than its frontend sources (`gateway.control_ui.dist_stale`). The warning is advisory: it never blocks serving the existing bundle and never degrades overall health status, because source mtimes are a hint rather than an oracle — `git checkout` and `git pull` rewrite them, so a freshly built bundle can be flagged. Rebuild with `python scripts/build_control_ui.py build`; `agentos doctor` clears on the next run, and a gateway restart clears the boot-time log line. Wheel installs ship no frontend sources and are never flagged, and the check is skipped entirely when the Control UI is disabled. A real-browser UI audit is opt-in and never part of the default test run. It boots two `agentos gateway run` processes on throwaway state directories (the default base path and a custom one) and checks every destination at 360, 768 and 1280 px in light and dark: page-level horizontal scroll, a document that scrolls at all (the shell is the viewport; only its panes scroll, and wheeling past a pane's end must not move the shell), console and network errors, axe-core (serious and critical violations fail), content clipped to zero size, interactive controls pushed outside the viewport or cut by a clipping box, a page header description squeezed beside its actions on a phone, segmented-control text off centre in its box, target sizes, a keyboard-only pass (visible focus at 3:1, no trap outside modals, Escape closes the top layer and focus returns to the opener), reduced motion, forced colors, deep links with reload, and legacy redirects. Screenshots and `results-*.json` land in `/tmp/agentos-ui-audit`: ```sh npm --prefix frontend exec -- playwright install chromium AGENTOS_WEBUI_UI_AUDIT=1 uv run pytest tests/functional/test_webui_ui_audit.py -q -s ``` `AUDIT_ONLY` (`matrix`, `targets`, `keyboard`, `motion`, `forced`, `deep`) and `AUDIT_VIEWPORTS` (`360`, `768`, `1280`) run a subset. For hot reload during frontend work, run the gateway and Vite together: ```sh agentos gateway run npm --prefix frontend run dev ``` Vite serves `/control/` and proxies the gateway API, the WebSocket, the root approvals REST routes and the `/ready` probe the truth badge reads (point it at another gateway with `AGENTOS_GATEWAY=http://127.0.0.1:<port>`). Production builds use relative assets plus a server-provided runtime base, so custom non-root mounts such as `/console/` work without rebuilding. Root, `/api`, and `/ws` mounts are rejected because they overlap the gateway's public endpoints. ### Conventions for console controls - **Disabled with a reason, never hidden or silent.** A control that cannot be used right now stays where it is, disabled, with the exact reason next to it ("The gateway is offline. Reconnect to use this."). The checks are headless and shared with the desktop app (`frontend/src/lib/disabled-reason.ts`: `gate(requireConnection(state), requireScheduler(down), …)` returns `{disabled, code, reason}`); the console renders the reason with its `DisabledReason` wrapper. A transient busy state is not a reason; a spinner already says that. - **Motion has a job and a budget.** Animation shows where something came from, confirms an action, shows live status or guides the eye on arrival; only live-status indicators loop. Interface transitions (hover, press, state changes, overlays and panels) take at most 300 ms; entrance choreography (a page or section arriving, spring-eased pops, a staggered list) at most 450 ms in total, duration plus stagger. Exits are never slower than their entrances. Durations and easings are tokens in `frontend/src/web/styles/tokens.css`, never literals, and `styles/motion.test.tsx` enforces all of this. Under reduced motion everything is instant (no delays either) except a slow opacity pulse on running indicators, and page transitions (the View Transitions API, main area only) are switched off. - **Every RPC method the console calls is listed** in `frontend/src/lib/required-methods.ts` (the desktop's extra ones in `desktop/src/renderer/src/lib/required-methods.ts`). A vitest fails when a literal `rpc.call('…')` is missing from the list, and `tests/test_console_required_methods.py` fails when a listed method is not in the gateway's advertised `features.methods`. Names built at runtime are listed by hand. ## Layout and routes The console is chat-first. On screens wider than 768 px it has three columns: - **Rail** (left edge): the agent switcher, **New session**, the **Sessions** and **Pages** view buttons and **Search**; at the bottom **Home**, **Inbox** (with a badge counting approvals, agent questions and runtime issues) and the status menu (connection state, theme, keyboard shortcuts, Settings). - **List pane**: the Sessions list or the Pages catalog. The catalog is a compact list in two groups (Overview: Home, Usage, Inbox; Work: Sessions, Projects, Automations) with Settings at the foot; Sessions shows the session count (with a live dot while one runs) and Inbox how many items wait. Arrow keys, Home and End move between its links. Activate the selected view's button again, or press Ctrl+B (⌘B on macOS), to collapse it. Drag its edge (or focus the edge and use the arrow keys) to resize it; the width is remembered by the browser. A fresh load always starts with the pane open. - **Main area**: the current route. The Sessions list shows every session from `sessions.list`, grouped **By date** (Pinned, Today, Yesterday, Previous 7 days, Older) or **By project** (Pinned, one section per project, No project). Each row is a link, so a middle-click or Ctrl/⌘-click opens the session in a new tab. A row shows the session's title (its name, else its derived title; an unnamed session reads "New conversation" with its short id beside the agent), its channel as an icon, its agent and when it was last updated, plus a running indicator while a task is queued or running. Child sessions (subagents) are folded under their parent, which shows how many it has. The filter box matches titles and keys; the filter menu narrows by agent, channel or project; **Clear filters** resets them all. A row's ⋯ menu (also right-click, or Shift+F10 on a focused row) holds Open in new tab, Rename, Pin/Unpin (and Move up/down for pinned rows, which can also be dragged), Move to project, Reset and Delete (both confirmed first), Export as Markdown and Copy session key. The list refreshes on `sessions.changed` and every 5 seconds while the tab is visible. Pins are stored on the gateway (`sessions.pin`), so the desktop app, `agentos sessions pin` and the agent's `session_pin` tool share one Pinned section; a session pinned elsewhere appears after the ones arranged here. The order of the Pinned section and the grouping choice are stored in the browser. Picking an agent in the rail's switcher makes it the default for New session and filters the Sessions list to it until the filter is cleared. At 768 px and below the rail and list pane become a drawer, opened from the header's menu button or a rightward swipe from the left edge. The header keeps a New session button. A pending approval from a session other than the one on screen appears in the approval tray at the bottom right of every page. It can collapse to a count but stays until every request is resolved. It starts collapsed on phones and on chat pages (the open session has its own approval card above the composer, and the expanded tray would cover the newest lines); once you expand or collapse it, that choice holds as you move between pages. ### Routes All routes live under the console base path (`/control` by default) and work as deep links, through reload and browser history. | Route | Shows | | --- | --- | | `/` | Redirects to `/chat` on every screen size. | | `/chat` | The last active session, or the default webchat session. | | `/chat/<agent>/<rest of key>` | One session. | | `/new` | New session. | | `/home` | Home: readiness, usage and live gateway activity. | | `/sessions` | Sessions: search, filter and manage every session. | | `/projects` | Projects. | | `/projects/<project>` | One project. | | `/usage` | Usage. | | `/automations` | Automations (scheduled jobs). | | `/inbox` | Inbox. | | `/settings` | Settings. | | `/settings/<section>` | One Settings section. | | `/mcp/oauth/callback` | Finishes MCP OAuth, then shows Settings › MCP. | A session key `agent:<agent>:<part>:<part>…` maps to `/chat/<agent>/<part>/<part>…`, with each part percent-encoded. Any other key, or one whose agent part is not a normalized agent id, maps to `/chat/~/<whole key, encoded>`. An unknown path shows a not-found page that names the path as plain text and links to Home and Chat. ### Legacy URLs Links from the previous console redirect (replacing the history entry, so Back skips them) and keep the query parameters that still apply: | Old URL | New URL | | --- | --- | | `/overview` | `/home` | | `/cron` | `/automations` | | `/projects?project=<id>` | `/projects/<id>` | | `/chat?session=<key>` | `/chat/<agent>/<rest of key>` | | `/chat?agent=<agent>` | `/chat/<agent>/webchat/default` | | `/health` | `/settings/health` | | `/channels` | `/settings/channels` | | `/channels?view=setup` | `/settings/channels?setup=1` | | `/mcp` | `/settings/mcp` | | `/skills` | `/settings/skills` | | `/memory` | `/settings/memory` | | `/agents` | `/settings/agents` | | `/env` | `/settings/environment` | | `/logs` | `/settings/logs` | | `/approvals` | `/settings/approvals` | | `/config` | `/settings/advanced` | | `/setup` | `/settings/setup` | | `/settings?step=channels` | `/settings/channels?setup=1` | | `/settings?step=<step>` | `/settings/setup?step=<step>` | ## Main Areas Chat is the center of the console; everything else is a page in the rail's **Pages** view or a section of [Settings](#settings). | Page | Route | Use it for | | --- | --- | --- | | Chat | `/chat/…` | Run and resume sessions, follow tool activity, read artifacts and cards, compact. | | Home | `/home` | A dashboard under a greeting and a readiness pill: readiness (checks passing as a ring; when not ready, the findings that need attention, each leading to Health), provider and route, uptime, usage (all time, plus how many sessions were active today) with a chart of tokens per session, sessions by channel and when they were last active over the past day, a countdown to the next automation run, and a live event feed. Each figure loads on its own and links to its detail. | | Sessions | `/sessions` | Every session in one list: a summary line (the total, an open/completed/failed/aborted breakdown and how many are executing now), search and filter menus for agent, project and status, a lifecycle chip per row, inline rename, a row menu with Open chat and Open in new tab, bulk delete, move to a project, a new-session dialog that can create an agent, orphan flags. | | Projects | `/projects` | A gallery of projects; group sessions, edit each project's shared knowledge (injected into every member session), and start a new chat inside a project at once, under the project's agent. A project's page switches to another project from its breadcrumb. | | Usage | `/usage` | Spend for the sessions active in a range as the lead figure, with sessions, the average and the token mix (input, output, cache read, cache write) as one stacked bar; the top sessions charted beside spend by model (a ring and a ranked list); the sessions table; CSV export. The sessions table fits its card: a narrower one drops the cache columns, a phone-width one shows each session as a card of labelled values. | | Automations | `/automations` | What runs next and the next 24 hours as lanes, then scheduled jobs and their run health; create (blank or from a template), edit, run now, pause, delete, run history. | | Inbox | `/inbox` | Everything waiting on you, grouped into approvals, agent questions and runtime issues, answered in place. | **Home** sums tokens and estimated spend over every session: the gateway keeps per-session lifetime totals only, so there is no per-day spend figure. Next to it, Home says how many sessions were active today (since local midnight). **Usage** lists the sessions active in the chosen range (All time, the last 7, 14 or 30 days) with their lifetime totals, charts the top 20 of them by tokens or cost, rolls usage up by model, and exports the rows in range as CSV. A range picks sessions; it does not split a session's usage by day. The page leads with the spend in range and where its cost comes from; the model rollup shows each model's share of spend as a ring and a ranked list. **Sessions**, **Home** and **Projects** load the newest 500 sessions. With more than that, they say so ("Showing the newest 500 of N"); counts, search and filters on the page cover only those, and a project whose session count is larger than what is loaded says so too. ## Gateway connection ### Connect screen When the gateway requires a token (`auth.mode = "token"`) and this browser tab has none, or the gateway refuses the tab's token, the console shows a full-page **Connect** screen instead of the workspace. Nothing behind it is rendered or requested. It takes the gateway token and, when the console should reach a different gateway, its WebSocket URL; it shows the gateway's address and where the token comes from (`auth.token`, or `AGENTOS_GATEWAY_TOKEN`). - A rejected token keeps the screen up with "The gateway rejected this token." and keeps the URL you entered. - Too many failed sign-ins (`AUTH_RATE_LIMITED`) disable the form and say that sign-in is rate limited. The console does not retry by itself. - If the gateway does not answer within 10 seconds, the screen says it could not be reached; a connection that is refused outright says so at once. The form stays usable during an attempt: correct the address and connect again at any time. - A new address is saved for this browser only after that gateway connects, so a mistyped or unreachable one does not stick across reloads. **Settings › Gateway** changes the same connection from inside the console. The token is required only when the gateway uses token auth (`auth.mode = "token"`); otherwise the WebSocket URL can be changed on its own. **Disconnect** closes the connection and stops reconnecting until you press **Reconnect** or reload the page. After a switch the section shows the new address and "Connected to <host>." once that gateway answers. Connected to a gateway other than the one that served the page, the console reaches it only over its WebSocket: the page's security policy allows HTTP to its own origin only, and the tab's token is never sent to any other address. Approvals (the inbox, the tray and the approval mode) work over the socket. The elevated-execution switch, uploads of files over 2 MB and cards whose data loads over HTTP are not available there and say so. Open the console from that gateway's own address to use them. ### Credentials in a link A link may carry the token once, as `?token=…` or `#token=…`, for example `http://127.0.0.1:18791/control/chat#token=abc`. Before anything else runs, the console stores it for this tab only (`sessionStorage`, key `agentos.wsToken`) and replaces the URL, so the address bar and Back never show it. A new tab starts without a token, except one opened with a session's **Open in new tab**, which copies this tab's sign-in. A `gatewayUrl` parameter is never applied silently: a dialog shows the full address and what will be sent first, and the URL is only used after you confirm, and only in a top-level window (never inside a frame). Your current token is never sent to that gateway: it is used only if the same link carries a `token` (held with the address and used only for that gateway; **Stay here** discards it), otherwise the Connect screen asks for one. The address is saved for this browser only after that gateway connects; until then a reload returns to the previous gateway. The switch replaces this tab's stored token, so the previous gateway's token must be entered again to switch back. ### Short drops and restarts A connection loss shorter than 2 seconds changes nothing on screen: the status stays as it was and no control is disabled. After that, the status changes and disabled controls say why. A message sent while the socket is reconnecting is delivered once when it is back, or shown as not sent with **Retry**; it is never lost silently. When the gateway announces an in-place restart (`shutdown` with `restart_expected_ms`, for example after **Restart gateway** in Settings), the console shows **Restarting gateway…** instead of an error, reconnects on the gateway's timing, and refreshes the open view once the hello succeeds. Cached data (agents, projects, sessions, the update notice) is refreshed after every reconnect, and dropped when the console connects to a different gateway. If an open tab's console is older than an upgraded gateway (`PROTOCOL_MISMATCH`), the console says a newer console is available and offers **Reload**. It may reload by itself, but at most once per console version within 60 seconds, so it can never loop. ## Runtime status (truth badge) The status button at the bottom of the rail answers "is what I am seeing true and fresh". It shows one of six states and how fresh the view is: | State | Meaning | | --- | --- | | Ready | Connected, frames are arriving, and the doctor reports no error-level finding. | | Degraded | Connected, but a doctor finding is at error level, `/ready` reports `safe_mode` or `draining`, or no frame has arrived for 2.5 tick intervals (the view is a snapshot). | | Connecting | The WebSocket is opening, `/ready` reports `starting`, or the gateway announced an in-place restart (`shutdown` with `restart_expected_ms`) and is on its way back. | | Blocked | The gateway refused the handshake, read from its typed error: bad credentials (`UNAUTHORIZED`), too many failed sign-ins (`AUTH_RATE_LIMITED`), or a different protocol version (`PROTOCOL_MISMATCH`; when the console is the older side, reloading the page fixes it). The console does not retry these by itself. | | Offline | No connection. What is on screen is the last snapshot. | | Unknown | Connected, but the doctor report has not arrived or could not be loaded, so "Ready" cannot be claimed. | Next to the state is the source and its age: `Live · 12 s` (age of the last frame the gateway sent), `Snapshot · 3 min` (the connection dropped; data is from before), or `Unavailable` (never connected). Open the status menu for the reason and exactly one recovery action: **Retry connection** (reconnects at once, skipping the backoff, and opens a new socket when the current one still looks open but has gone silent), **Open attention inbox**, or **Open Health**. A connection with no frame for 2.5 tick intervals is dropped and reopened by itself. The badge refreshes from the connection itself: the hello, every event frame, the gateway's `tick` (every 30 s), and a shallow `doctor.status` plus `GET /ready` (its `state`: starting, ready, draining, safe_mode, and the `failing` checks) read on connect and every fourth tick (a `health` event or a `state_version` revision triggers an extra read, once the gateway sends them). It runs no polling timer of its own; a one-second display clock only ages the "Live · 12 s" readout. Screen readers hear the state when it changes, not the ageing freshness. ## Attention inbox **Inbox** (`/inbox`, `g i`, or the rail's Inbox button) lists everything that waits on you. The rail button carries a badge with the count, and a new item is announced to screen readers: - **Approvals** of every namespace (the same queue as Settings › Approvals and the approval tray). The same command waiting in several sessions is one item, "Seen in N sessions", and each occurrence keeps its own **Approve once** / **Deny** and a link into its session. Each card names the requesting agent and has a **Copy command** button. A push notification for an approval opens `/inbox?approval=<id>`, which scrolls to that approval and focuses it. - **Agent questions** (`ask_user`): the option chips and a free-text reply, sent as your next message in that session (to every session, when the same question was asked in several). On every connect the console asks the gateway for the questions its 100 most recently updated sessions end on (`sessions.questions`), so the inbox and its badge list them after a reload without opening each session; after that new questions arrive live. A question whose session was deleted disappears. - **Runtime issues**, typed from `doctor.status` findings and the connection state: `gateway_unreachable`, `auth_failed`, `protocol_mismatch`, `model_auth_required`, `rate_limited`, `channel_terminal`, `safe_mode`, `update_failed` and `doctor_warning`. Each offers the actions that fit it: the doctor's fix steps in place (each command with a copy button), a jump to the right settings screen, **Retry connection**, and **Dismiss** (for this browser session only). While the console is offline only the connection issue is listed; the last doctor report is not repeated as if it were current. Approvals come from the same store as Settings › Approvals, which the gateway keeps current with `approval.requested` / `approval.resolved` events (one backfill per connect), and the list updates when that store changes; the inbox adds no timer and no polling of its own (**Re-check** asks for one backfill), and items show when they started waiting ("since 11:32"). An empty inbox says "All caught up" only while the console is connected. The inbox groups items by kind, with a count in each group's header. Each item is a compact row (its title, a one-line preview and when it started waiting) that opens in place to the decision; the first row of each group, and the approval a notification points at, start open. A resolved item folds away. ## Keyboard Shortcuts `Mod` is `⌘` on macOS and `Ctrl` elsewhere. Press `?` (or `Mod+/`) to open the shortcut overview, which shows the keys for your platform. ### Command palette `Mod+K`, or the rail's **Search** button, opens the command palette. Type to search, in labelled groups, across **Sessions** (titles and keys), **Pages**, **Settings** sections and **Actions**: New session, Toggle sidebar, Switch to system / light / dark theme, Open keyboard shortcuts, Retry connection, Open Inbox, Compact current session and Export current session. An action that cannot run right now is listed as disabled with its reason (for example, Compact while a turn is running). Arrow keys move, `Enter` runs, `Escape` closes and returns focus to where it was. If sessions cannot be loaded, the Sessions group says "Couldn't search sessions. Try again." while the other groups keep their matches. ### Global | Keys | Action | | --- | --- | | `Mod+K` | Open the command palette | | `Mod+B` | Toggle the sidebar (list pane; the drawer on phones) | | `Mod+/` | Show keyboard shortcuts | | `?` | Show keyboard shortcuts | | `Mod+Shift+O` | New session | | `Escape` | In chat: stop the running turn, or recover queued messages | ### Navigation chords Press `g`, then a destination key within **1.5 seconds**: | Keys | Goes to | | --- | --- | | `g c` | Chat | | `g h` | Home | | `g i` | Inbox | | `g s` | Sessions | | `g p` | Projects | | `g u` | Usage | | `g r` | Automations | | `g ,` | Settings | | `g n` | Settings › Channels | | `g m` | Settings › MCP | | `g k` | Settings › Skills | | `g a` | Settings › Agents | | `g y` | Settings › Memory | | `g e` | Settings › Environment | | `g l` | Settings › Logs | | `g v` | Settings › Approvals | | `g o` | Home (the former Overview chord) | ### Composer | Keys | Action | | --- | --- | | `Enter` | Send (or `Mod+Enter`, per Settings › Appearance) | | `Shift+Enter` | New line | | `/` | Open the slash command menu | | `ArrowUp` | Edit the last message (empty composer) | | `Alt+ArrowUp` | Take the newest queued message back into the composer | | `Tab` | Use the suggested next prompt (empty composer) | > [!NOTE] > Single-key shortcuts and chords are ignored while focus is in a text field > and while a dialog is open. `Mod+` shortcuts (the palette, the sidebar, the > overview, New session) also work from the composer. ## Settings Everything you configure lives under **Settings** (`/control/settings`, or **Settings** in the status menu). A **Search settings** field at the top of its sidebar matches section names, descriptions and field labels; choosing a field opens its section and focuses it. `/control/settings` itself summarizes readiness and setup progress. On a phone the sidebar and a section never share the screen: a section opens on its own with **All settings** above it to go back to the list. | Group | Section | Holds | | --- | --- | --- | | General | Appearance | Theme (System, Light, Dark), text size, send shortcut, show thinking, visual effects. Browser-only; applies at once. | | General | Notifications | The Web Push toggle for approval notifications. | | Connections | Gateway | Connection URL, auth mode, version and identity; change credentials, reconnect, disconnect, restart. | | Connections | Channels | Adapter status, pairing approve, deny and revoke (Telegram, and Discord, Slack or MS Teams with pairing on), and the channel setup dialog. | | Agents | Agents | Create, edit, customize and delete agents. | | Agents | Models & routing | Provider setup (current values, router support), Pilot Router mode, judge / safety-net / Jev settings, translation cap and the tier table including the image tier, subscription logins. | | Agents | Search | Web search and X search setup, X search sign-in. | | Agents | Skills | Installed, partner and community skills; install, remove, update, dependencies, missing env keys. | | Agents | MCP | The runtime toggle, servers, connect and disconnect, OAuth. | | Agents | Memory | Curated memory, the knowledge base, raw sources, search, reindex, embeddings. | | Agents | Media | Image generation and audio. | | Security | Approvals | Default mode, approval strategy, browser elevated mode, pending requests (with **Refresh**). | | Security | Environment | Set, unset, reveal and import environment variables. | | System | Health | Doctor findings with fix steps, marked when diagnostics are incomplete, a repair is pending or the config does not match. | | System | Logs | The live log tail, filters, follow and export. | | System | Advanced | The full configuration editor: a form built from `config.schema`, or YAML. | | System | Debug | Snapshots of status, health, doctor, models and the last heartbeat, recent events, and (with diagnostics enabled) a manual RPC tool. | | System | Updates | Check for and apply updates, with the preflight. | | System | About | The version and third-party licenses. | **Guided setup** (`/control/settings/setup`) walks through provider, router, extras (search, memory embeddings, image generation, audio) and a finish summary. While setup is incomplete, a prompt at the top of the console links to it. The catalog forms (Models & routing, Search, Media, Guided setup) start from the saved values and send every field they show, because each onboarding operation rewrites its whole section. Only providers the gateway can run are offered. Search, X search and image generation have an **API key environment variable** field; a pasted key replaces it for that save. X search has an **Enable X search** switch, shows which xAI credential is in use, and offers **Sign in with xAI** or **Sign out of xAI**. **Advanced** builds its form from the gateway's `config.schema`: enum values become choices, descriptions become help, sensitive fields are masked until revealed, read-only keys (`host`, `port`, `config_path`, `auth.token`, `auth.password`) are shown but not editable, and a key the schema does not describe is still editable, typed from its value. Each row is labelled with its dotted config path, the schema title beside it, and a filter box narrows the rows. Optional values offer a **Default** choice (booleans and enums) or are unset when emptied (text). A JSON value that does not parse is marked and blocks Save. The YAML view applies the whole document with `config.apply`; its draft is kept when the configuration changes underneath it, with a notice. It cannot be applied while form edits are pending, and the form is read-only while a YAML draft is pending. **Reload** loads the current configuration (disabled while there are unsaved edits). The hub reads one redacted `config.snapshot` composite for a coherent view of the catalog, readiness, active configuration, revision, persistence target, restart state, and runtime/disk coherence. Writes use the narrowly scoped onboarding operations or `config.patch` / `config.apply`; the snapshot itself is read-only. ### Configuration write safety Every section that writes the gateway configuration keeps unsaved edits in a sticky save bar ("2 unsaved changes", **Review changes** as `path: old → new`, **Discard**, **Save**), and asks before you navigate away with edits. A newly typed secret is masked in **Review changes**. Each write carries the revision the first edit was made against as `expectedRevision`. If another client saved in the meantime nothing is written: **Reload** loads the newer configuration and **Overwrite** reapplies your edits on top of it; when a refetch shows the configuration moved while edits are unsaved, that choice is shown straight away. A validation error is shown at the field it names and every edit stays in place. While the gateway reports a pending restart (`config.snapshot`'s `pendingRestart` / `restartReasons`), a notice docked at the bottom of the section (where the save bar was, so the page does not move) names the reasons and offers **Restart gateway** or **Later**; it appears for restarts caused by any client and survives a reload, and **Later** hides it until another change needs a restart. A one-time secret (a provider, search, media or Jev key) is cleared from the form immediately after a successful write, even when the follow-up refresh cannot complete. Gateway configuration writes are persist-first transactions: 1. validate a cloned candidate configuration; 2. verify `expectedRevision` and the live/disk coherence state; 3. atomically persist the candidate; 4. update the running configuration; 5. hot-apply the adapters that support it. If persistence fails, the running configuration and runtime adapters remain unchanged. If persistence succeeds but a hot-apply adapter fails, the persisted configuration remains authoritative and the gateway records a pending restart reason instead of reporting the change as fully live. An external edit to the active config file is fail-closed. In that state, `config.snapshot` returns `revision: null`, `diskDiverged: true`, and `writeBlocked: true`; Settings explains why, offers **Reload**, and disables the writes of Guided setup, Models & routing, Search, Media and Advanced until the file is reloaded. Reload or restart the gateway with that file before editing again. Refreshing only the browser cannot reconcile a stale running configuration. `host`, `port`, `config_path`, `auth.token`, and `auth.password` are display-only in Advanced. The WebSocket config mutation RPCs reject attempts to retarget the active config file or replace runtime-owned authentication credentials. Other authentication settings, such as `auth.mode`, remain editable and may require a gateway restart — `auth.mode` accepts only `none`, `token`, or `trusted-proxy`, and any other value is rejected by the mutation RPC rather than saved. Restart reporting is deliberately conservative. Mutation responses expose `restartRequired`; subsequent snapshots expose cumulative `pendingRestart` and `restartReasons` for boot-captured settings and failed hot applies. This covers areas such as memory, channels, sandbox/bind posture, task runtime, server middleware, MCP discovery, tools/skills loading, state paths, heartbeat, and diagnostics. Treat a restart advisory as part of completing the change rather than as a save failure. ### MCP Open **Settings › MCP** to add and manage external MCP connections. The screen supports local `stdio`, legacy SSE, and Streamable HTTP servers. Remote servers can use custom headers or OAuth. OAuth tokens are stored separately from `config.toml` in the AgentOS state directory. AgentOS applies mode `0600` inside a `0700` directory on POSIX systems; Windows uses the current user's state-directory ACL. The featured Robinhood Trading connection uses: ```text https://agent.robinhood.com/mcp/trading ``` It is configured as Streamable HTTP with OAuth. Saving the connection opens the provider authorization flow and loads its tools without requiring a gateway restart. Agentic trading involves significant risk. Review the server's access and action permissions before authorizing it. ### Skills Open **Settings › Skills** (`/control/settings/skills`) to see what is installed and what the agent can actually reach. The **Installed** tab groups cards by where a skill came from, not by which directory holds it: | Group | Contains | | --- | --- | | Partners | Skills published by an AgentOS partner | | Shipped with AgentOS | Skills that ship with the release | | Installed from a hub | Skills you installed with `agentos skills install` or from this screen | | Your local skills | Skill directories you added yourself | Partners wins over the other three, so a partner's skills stay under one heading whether they shipped with AgentOS or you installed them from that partner's hub. Partner identity comes from an allowlist inside AgentOS: a skill manifest can only select a recognized publisher by id, so a third-party skill cannot borrow a partner's name, link, or logo by writing them into its own frontmatter. Only a skill that ships with the release may select an id at all — an installed one is branded by the hub catalog row it came from — so dropping a directory into a skills path cannot put a card in the Partners group. The storage layer (`bundled`, `managed`, `personal`, …) is still shown, as a chip on each card, because it decides which skill wins a name collision. It no longer decides what heading the card sits under. **Update** and **Remove** follow what the install record actually supports rather than the layer. A hub-installed skill whose files no longer sit where the lockfile recorded them keeps Update — an update re-fetches by identifier — but loses Remove, and the dialog says why instead of offering a button that would fail. #### Ready is not the same as offered A card's status dot answers "is this skill set up". A second, separate label answers "is the agent being offered it right now", and a skill can be fully ready and still withheld. When it is, the card and its dialog say which of these applies: the manifest disables model invocation, a requirement is missing, a tool it needs is not enabled in this session, a native tool supersedes it, relevance filtering skipped it for that message, or the injected skills block hit its character budget. Nothing is shown when the skill is offered — the absence of a label is the normal case. #### Community tab Browsing and searching a hub also surfaces skills you have already installed from that source, including ones the catalog does not list — a skill installed straight from a GitHub URL appears alongside catalog rows rather than vanishing from the page it was installed on. Installed rows are marked and appear after catalog results. Installing or removing a skill updates the Installed marker immediately, without a page reload. ### Environment Open **Settings › Environment** (`/control/settings/environment`) to manage the variables in `~/.agentos/.env` without touching a shell. Variables are grouped by what needs them — LLM provider, search, memory, each installed skill, and your own additions — with the description and, where the skill declared one, a link to where the credential is obtained. A skill listed as needing setup can be fixed from its own dialog in Settings › Skills too: the Missing block offers **Set <VAR>** next to the existing install action. A variable that is not set but is already obtainable elsewhere shows a **Use <source>** button instead of asking you to go find a value — today that is the GitHub CLI for `GITHUB_TOKEN` and `GH_TOKEN`, when `gh auth login` has been run. Deciding whether to offer it never reads the credential, and importing only happens when you click. The imported value is a copy and will not follow that tool's own rotation. Values are masked. **Reveal** asks for confirmation, is rate limited, writes an audit line, and hides the value again after thirty seconds. Setting a variable applies it to the running gateway, so a skill that was ineligible becomes eligible immediately — on this screen, in Settings › Skills, and for the agent itself on its next turn. Provider keys additionally need a restart, and the screen says so when that is the case. Two things the screen deliberately makes visible: - **Locked variables.** Names that steer subprocess execution or AgentOS runtime posture, or outbound routing (`PATH`, `LD_PRELOAD`, `AGENTOS_AGENT_PERMISSIONS`, `HTTP_PROXY`, …) show a lock instead of an edit control. See [Configuration](https://useagentos.dev/docs/core/configuration#what-cannot-be-written-through-agentos). - **Shadowed variables.** If the shell that started the gateway exported a variable, that value wins over the file and editing here has no effect until the export is removed. The screen warns rather than letting you save repeatedly and conclude it is broken. ### Logs and diagnostics For local diagnosis: ```sh agentos diagnostics on agentos gateway status agentos doctor ``` Use Settings › Logs and Settings › Health to correlate provider readiness, channel state, session state, and user-visible errors. ## Chat Sessions ### Layout The chat workspace is one centered column. Your messages are right-aligned bubbles; each reply opens with the agent's name (and the model, when known), then full-width prose. Tool calls and reasoning gather in an activity block that folds into one line (**Worked for …**) when the turn ends. Hover or focus a message to copy it as Markdown or see when it was sent. The header shows the session title (its name, else its first message, else **New conversation**; activate it to rename in place), the agent, channel and project, the session ID (activate it to copy the full key), a **Panels** toggle and a ⋯ menu (Rename, Compact, Reset session (confirmed first), Export as Markdown, Copy session key). It stays visible while the transcript scrolls. Opening, reloading or switching to a session lands on its latest message. While you are at the end of the transcript, new content keeps the latest in view. Scroll up and following pauses — the text you are reading does not move — and a **Latest** button appears when new content arrives; activate it, scroll back down, or send a message to follow again. Reaching the top loads older history above without moving what you were reading; a first page too short to scroll loads older messages on its own. Older history you loaded stays when a turn ends. A turn the gateway resumed after a restart shows the note "The gateway restarted during this reply; the agent picked it up again." above the reply, instead of the instruction the gateway sent to resume it. Between sending and the first output the transcript shows **Working…**. Messages waiting on the gateway (queued from another tab or channel, or about to be added to the running turn) are listed below the conversation. ### Turns, tool rows and Markdown Once a turn finishes with an answer, the reasoning, commentary and tool calls before the answer fold into one **Worked for 42s · 3 tools** disclosure; the answer stays fully visible. A turn still running, or one that ended without an answer, stays expanded, and a failed tool call after the answer stays visible below it. Folding only changes the display; history is untouched. A turn looks the same after a reload as it did live. Each tool call is a compact row: icon and name, a short detail (the command, query or path), its state (running, done or **Failed**, always with an icon and the word as well as the colour) and its duration once it finishes. Activate the row (click, Enter or Space) to see its arguments and result. A long result shows a preview and **Open in side panel**. Consecutive tool calls and reasoning read as one activity thread, and content that arrives while a turn runs eases into place; history does not animate. Markdown in messages is sanitized: scripts, event handlers, `javascript:` links, HTML classes written by the model and anything outside an allowlist are removed. Images in replies load only when they are inline (`data:` PNG, GIF, JPEG or WebP) or local (`blob:`); any other image, including same-origin and protocol-relative ones and image buttons (`<input type=image>`), is shown as a link. QR codes (`agentos-qr:`) are drawn locally. Task-list checkboxes are read-only. Links to other sites open in a new tab with `rel="noopener noreferrer"`. Code blocks are highlighted in colours that suit the theme and have a **Copy** button; wide code and tables scroll inside their own box. A turn that fails shows its reason inline with **Try again** (resends the message) and **Edit message** (puts it back in the composer); both stay after the conversation reloads, and a tool call the failed turn left unfinished stops spinning. A message that could not be delivered during a connection drop shows **Not sent** with **Retry**. ### Composer The composer grows with your text. Settings › Appearance chooses the send key: **Enter** (Shift+Enter for a new line) or **Ctrl/⌘+Enter** (Enter for a new line). An Enter that confirms an input-method composition never sends, and on phones Return always adds a line — use the Send button. Each session keeps its own unsent draft (and staged attachments) while you switch sessions. Under the text field: attach files (also paste or drop them; they appear in a tray with remove buttons), the **Model route** picker (Auto/Pilot Router, or **Default · <model>** when the router is off, a pinned tier, or a named model — the session's route hold), the **Capabilities** menu (plan mode, execution mode, Pilot Router, visual effects) and the session's token and cost readout. The Capabilities menu's **Execution mode (elevated)** checkbox is what the previous console showed as the Elevated pill. Send is disabled, with the reason, while an attachment is still uploading. Type `/` at the start for the slash command menu (arrow keys, Enter, Escape). Only commands the gateway lists run; any other text starting with `/` (a file path, say) is sent as a message. Start a message with `//` to send a leading slash literally (`//etc` sends `/etc`). The output of commands such as `/model` appears in the conversation as a local note: it is not sent to the agent and not kept in history. After a turn ends the composer may show a suggested next prompt as its placeholder; press Tab on an empty composer to use it. The main button follows the session: **Send** when idle, turning into **Stop** while a turn runs (calls `chat.abort`), with **Queue** next to it once you have typed something. After Stop the turn shows **Stopping…** while the gateway winds it down, and the button reads **Stop now**: pressing it (or Escape) again sends a second `chat.abort`, which ends the turn at once. A refused stop is reported. Messages sent while a turn runs wait in a queue kept per session for the life of the tab (switching sessions keeps it). They are listed above the composer, where each can be edited or removed. The queue sends its next message when the turn ends normally or a compaction finishes; after Stop or a failed turn the queued text comes back into the composer instead. Answers to question cards, plan approvals and **Try again** also wait in the queue while a turn runs. Escape (outside an input-method composition) stops a running turn, or with nothing running takes the whole queue back; Alt+↑ takes back the newest queued message. The console takes the gateway's word on whether a turn is running. Opening a session in the middle of a run shows the run so far (its text, tool calls and plan, with a note when earlier output was cut); a reconnect replays from the last event seen. If live updates were missed, a toast says so and the conversation is reloaded, and a running turn with no events for 210 seconds is checked against the gateway again. Long replies are drawn once per frame. ### Side panel and approvals The side panel opens beside the transcript for full tool output, artifacts and reasoning, one tab per item. Drag its edge to resize it (the width is remembered); Escape closes it and returns focus to the control that opened it. When the open session's turn needs an approval, the request docks above the composer with the decisions it allows, and the turn shows **Waiting for approval**. Requests from other sessions appear in the approval tray. ### New session `/new` (rail **New session**, `Mod+Shift+O`) greets you with one large composer. Its toolbar holds the **Agent** chip (preset to the active one) and the **Project** chip (optional); each opens a menu with a check on the current choice. Attach files with the paperclip, by pasting, or by dropping them anywhere on the page. The starter suggestions under the composer fill it in (they do not send). **Start** (the round button, or the send key from Settings › Appearance) creates the session, sends the message and opens it; while it cannot run, its tooltip and description say why. If creation fails, the page keeps your message and attachments and shows the error; if the first message fails, **Start** again sends into the same new session instead of creating another. A link may preset the choices: `/new?project=<id>` preselects the project and the agent that owns it, `?agent=<id>` an agent, and `?prompt=<text>` fills in the first message. An agent or project from the link that no longer exists is ignored, and agent or project lists that fail to load show an error with **Retry**. The Skills **Use** button opens chat with the composer pre-filled the same way (`/chat?prompt=`). ### Model reasoning (thinking) When the routed model streams reasoning (Anthropic thinking blocks, DeepSeek `reasoning_content`, or local `<think>` models), the WebUI shows it live in a collapsible block that folds away as soon as the reply text starts. Replies whose reasoning was persisted show a collapsed **Thinking** block in history; the reasoning body loads on first expand (it is not shipped with history pages). Turn it off with `control_ui.show_thinking = false` (or `AGENTOS_CONTROL_UI_SHOW_THINKING=false`) — the gateway then neither streams thinking events nor serves reasoning bodies. This is WebUI-only either way: channel adapters (Slack, Telegram, …) never receive thinking. ### Plan mode Flip **Plan mode** in the run-modes popover (or type `/plan`) to make the session research-only: the agent keeps its read, search, and analysis tools but every mutating tool is withheld until you approve a plan. When the agent finishes planning it calls `exit_plan_mode`, its turn ends, and the chat shows the plan in a card with an **Approve plan** button. Approving turns plan mode off and sends the go-ahead; typing feedback instead keeps plan mode on and refines the plan. Plan mode is per-session and lives in gateway memory — a gateway restart clears it. ### Agent questions (ask_user) When the agent needs a decision that is genuinely yours — scope, a hard-to-reverse action, conflicting instructions — it can call the `ask_user` tool. The chat renders a question card with clickable options (plus a free-text field); picking an answer sends it as your next message and the agent continues from there. Asking ends the agent's turn, so nothing blocks while you decide, and typing a reply in the composer works exactly the same as clicking the card. Open questions also appear in the [attention inbox](#attention-inbox), answerable from there. ## Manual Compaction Long sessions can be compacted from chat. If no compaction is needed, the UI reports: ```text Already within context budget; no compact was applied ``` If compaction is running, wait for its terminal state before assuming the next message has the compacted context. See [Compaction and Cache Continuity](https://useagentos.dev/docs/core/features/compaction-and-cache). ## Artifacts When the agent publishes a file, the Web UI shows an artifact card. Use artifact cards for: - generated HTML prototypes; - reports and briefings; - exported data files; - PDFs, slide decks, images, and other generated outputs. Images and audio play inline in the card. The console loads them, and every download, through short-lived ticketed URLs bound to its connection, so no token ever appears in a page URL. An artifact published as `application/vnd.agentos.chart+json` renders as an interactive candlestick chart instead of a download chip — the `gmgn-market` and `gmgn-token` skills use this for token price charts. For the chart payload shape, channel delivery limits, and artifact recovery, see [Artifacts and Media](https://useagentos.dev/docs/core/artifacts-and-media). ## Approvals Some tools require confirmation. The approvals area gives operators a durable place to approve or deny sensitive actions instead of burying the decision in chat text. Use the approvals area when: - the agent wants to write files; - a command requires elevated permissions; - a channel or external action needs human confirmation; - unattended automation should pause before a risky operation. Settings › Notifications › *Push notifications for approvals* sends a notification to this browser for every new approval, even with the console closed (HTTPS or `localhost` only); see [Approvals and Permissions](https://useagentos.dev/docs/core/approvals-and-permissions#where-a-prompt-reaches-you). Every approval card (the tray, the card docked above the composer, Settings › Approvals and the Inbox) names the requesting agent when the request says which, and offers **Copy command** for a command. While the gateway connection is down the cards stay listed, with their buttons disabled and the reason shown, since an answer could not be delivered. A pending approval from another session waits in the approval tray at the bottom right of every page; it can collapse to a count but stays until every request is resolved, so the rest of the console and its shortcuts stay usable. Deciding several approvals in quick succession sends every decision. The [attention inbox](#attention-inbox) lists the same approvals next to agent questions and runtime issues. ## Automations **Automations** (`/automations`, `g r`) is the former Cron view. It opens with **Up next** (the job that runs soonest, with a countdown that ticks every second, and the next few jobs after it) beside **Next 24 hours**, one lane per enabled job with a mark for every run. Each job is a row led by its schedule in words (the editor adds a plain-language explanation with the next runs, worked out in the job's timezone, UTC when it has none, and shown in local time), with the cron expression, the next-run countdown, the last run, delivery target, payload and run health. **New automation** opens the editor, which also sets the failure destination; an empty page explains that scheduled jobs appear there and offers **New automation** and three templates, each opening the editor filled in. Rows offer **Run now**, **Pause**/**Resume**, the run history with a summary of the last runs and each run's output, **Edit**, and in the row menu **Copy ID**, the overlap policy and **Delete** (confirmed first). **Run now** reports a run that failed, or that did not start (busy, disabled, blocked), as a failure. Rows refresh live when a run finishes (`cron.run.finished`) and the page subscribes again after a reconnect; the job list is also re-read every 60 seconds while the page is visible. Automations covers scheduled jobs only: DCA mandates, price triggers, brackets and missions are not shown there (see [Not in the web console](#not-in-the-web-console)). ### Run health A job that keeps failing is marked on its row: a **Degraded** badge, the consecutive failure count and the last error. They come from the `health` block on `cron.list` (the engine calls a job degraded at 3 failures in a row); a gateway older than that is read from the job's `consecutive_errors` and last error with the same threshold. When the job carries an overlap policy (`concurrency`), the **Overlap** choice in the row menu sets it (`forbid` skips a run while one is going, `replace` stops the running one, `allow` runs them side by side) through `cron.update`; it does not appear when the job has no `concurrency`. **Run** and **Pause** are disabled, with the reason, while the gateway is offline or after the scheduler answered that it is not running. ## Update Banner If a newer release of `use-agent-os` is available on PyPI, the status menu shows an **Update available** badge, and a dismissible notice at the top of the console links to Settings › Updates. The check matches the 24h throttling behavior of the CLI update checks. Dismissing the notice suppresses it for that release version (persisted in local storage); the badge in the status menu stays. Both honor the global `updates.notify` setting and the `AGENTOS_NO_UPDATE_NOTICE` environment flag. **Update now** opens a preflight before anything runs. The update restarts the gateway, so the preflight lists what that would interrupt: running sessions (`sessions.list`), scheduled jobs due in the next 10 minutes (`cron.list`), and pending approvals. A pending approval blocks the update, with the reason and a way to the inbox; running sessions and due jobs only warn, and the update starts once you confirm (**Update anyway**). A failed update is also listed in the attention inbox. ## Not in the web console The rebuilt console leaves out a few things the previous one had, on purpose: - **Trading actions.** LP, DCA, market and trigger/bracket cards in chat are read-only: they refresh, but collect, remove, add and the DCA and trigger actions are only in the desktop app (and the CLI). - **Engine-run objects in Automations.** Automations covers scheduled jobs only. DCA mandates, price triggers, brackets and missions are managed from the desktop app or the CLI (`agentos trade …`). - **The Home recent-sessions panel.** The Sessions list in the rail shows the newest sessions on every page, Home included. - **Home's Disconnect button.** Use **Disconnect** in Settings › Gateway. - **Sessions paging.** The rows-per-page selector and previous/next paging are replaced by **Show more**. - **Per-day usage.** Home and Usage show lifetime totals per session; the gateway keeps no per-day record. - **Advanced per-section tabs.** The filter box above the form narrows the rows instead. - **Capability badge chips** on the Search and Media cards. The one-line status under each capability carries the same information. - **Model-id suggestions in the router form**, and the warning when a tier names a model id the provider does not list. - **A dedicated control for an agent's `subagents.max_concurrent_children`.** Edit it in the `agents` value in Settings › Advanced. ## Safety The Web UI is local by default. If you bind the gateway to a public interface, configure token auth and network controls first: ```sh agentos gateway run --listen 0.0.0.0 --port 18791 ``` Do not expose an unauthenticated gateway to the public internet. For the supported ways to open the console from another machine, see [Remote Access](https://useagentos.dev/docs/core/remote-access). --- # Desktop App (macOS) > Source: https://useagentos.dev/docs/core/desktop-app AgentOS App is the native desktop app for macOS 13 or newer, on Apple silicon and Intel. It installs the engine for you, starts and supervises the local gateway, and gives you chat and the Trading Desk in one window. It talks to the same gateway as the [Web UI](https://useagentos.dev/docs/core/web-ui) and the [CLI](https://useagentos.dev/docs/core/cli), so sessions, projects, approvals and scheduled jobs are shared between all three. ## Install 1. Download the dmg for your Mac from the [latest release](https://github.com/use-agent-os/agent-os/releases/latest): `AgentOS-<version>-arm64.dmg` for Apple silicon, `AgentOS-<version>.dmg` for Intel. The app is signed with a Developer ID and notarized, so it opens without any Gatekeeper workaround. 2. Drag AgentOS into Applications and open it. 3. On first launch the app looks for an installed `agentos` CLI. If none is found (or it is older than the app), the setup screen offers **Install**: it installs the `use-agent-os` engine — the same package the terminal install uses — with no terminal, Python or `uv` needed. If a gateway is already running on the configured endpoint, the app connects to it instead; **Connect to an existing gateway instead** does the same for a gateway on another host (see [Using a gateway on another machine](#using-a-gateway-on-another-machine)). 4. Pick a provider. OpenCAP is listed first as **Recommended**; any provider in the catalog works. **Test key** checks the key against the provider before you save, and the last step tries it for real. **Skip for now** leaves a "Choose a provider" card on Home until one is configured. The managed gateway's output goes to `~/Library/Logs/AgentOS/gateway.log` (Settings › Advanced › App logs). Settings › Advanced also has **Reinstall engine** and **Remove engine**; removing the engine keeps `~/.agentos`. ## Using a gateway on another machine The app does not have to run the gateway itself. Settings › Gateway › Connection has a **Run mode**: **Managed** (the default) starts and supervises `agentos gateway run` on this Mac; **External** only connects to a gateway that is already running, on this machine or on another one — a server, a VPS, a home box. For an external gateway set: - **Protocol**: **HTTP** for a plain bind (loopback, an SSH tunnel, a LAN bind with a token) or **HTTPS** for a gateway behind TLS (a reverse proxy, Tailscale Serve, `[tls]` in its config). The WebSocket follows: `ws://` with HTTP, `wss://` with HTTPS. - **Host** and **Port**: where the gateway answers, as the app will reach it. Behind a proxy on `https://agent.example.com` that is host `agent.example.com`, port `443`. - **Auth token**: the gateway's `auth.token`. A gateway reached from another machine must enforce one (`auth.mode = "token"`); the app sends it as a bearer token on every request and on the WebSocket connect. Then press **Save**. If the app was running a gateway of its own at that moment, it stops it — the app no longer manages one — and connects to the endpoint you entered; a gateway it had merely adopted (one started from a terminal) is left running. A gateway on another host must also know the origin the app will present, which is the gateway's own: declare it there with `agentos config set gateway.public_origin https://agent.example.com --config ~/.agentos/config.toml` and restart it. The recipes, and the `agentos doctor` checks to run before exposing anything, are in [Remote access](https://useagentos.dev/docs/core/remote-access). For a full walkthrough from the published image, see [Run the gateway in a container](https://useagentos.dev/docs/core/container-gateway). In external mode the app only reports the gateway's state: the light in the sidebar footer, the Process row in Settings › Gateway and the menu bar item show whether it is reachable, and none of them starts, stops or restarts it — the gateway belongs to whoever runs it. The one action left is **Reconnect**, offered when the saved endpoint differs from the one the app is connected to. Configuration changes that need a restart (providers, channels, the router) still ask the gateway to restart itself in place, as they do from the Web UI. To go back, set **Run mode** to **Managed**. A host that is not on this Mac (the external gateway's) is replaced with the local default, HTTP on `127.0.0.1:18791`, since a managed gateway binds here; a local host and port you chose before are kept. Switching back to **External** before saving restores the endpoint you had. On **Save** the app starts its own gateway, or adopts one already answering on that endpoint, and connects to it. ## Chat and Trade The mode pill at the top of the window reads **Chat | Trade** (⌘⇧T switches). - **Chat** is the conversation surface: streaming replies, tool activity, approvals, plan cards, `ask_user` question cards and artifacts — the same transcript the Web UI shows, in the desktop's own styling. - **Trade** opens the Trading Desk: wallets, swaps, holdings, orders, history and allowances. See [Trading](https://useagentos.dev/docs/core/features/trading). The pill enters Trade at your newest desk chat. Any chat with the trading agent, started from Trade or with the **+** on the Trading desk project folder, opens in Trade when you pick it in the sidebar; every other chat opens in Chat. The strip next to the pill shows **AWAITING** while a decision is waiting for you and **RUNNING** while a mission is in flight. ### Run modes The sliders button left of the paperclip in the composer opens **Run modes** for the open session: | Control | What it does | | --- | --- | | Execution | Approval prompts or bypass for this session. The global default is shown next to it. | | Pilot Router | Turns [model routing](https://useagentos.dev/docs/core/features/pilot-router) on or off for this session. | | Plan mode | Research-only until you approve a plan (same as typing `/plan`; see [Plan mode](https://useagentos.dev/docs/core/web-ui#plan-mode)). | | Usage | The session's token usage so far. | ### Files and cards in the chat A file the agent generates shows as a **file card**: a tile drawn by kind (spreadsheet, document, PDF, presentation, archive, data, code, web page), the file name, a subtitle such as "Spreadsheet · XLSX · 5 KB", and a **Download** button. Images and audio play inline. Trading commands run with `--json` publish cards the chat renders live: - **DCA mandates** show a countdown to the next buy, spent-of-cap progress, average buy price vs now and a buys chart, with **Approve & start**, **Pause**, **Buy now** and **Stop** on the card. See [DCA](https://useagentos.dev/docs/core/dca). - **Uniswap V4 liquidity** cards show a pool, its range distribution or a position. See [LP cards](https://useagentos.dev/docs/core/lp-cards) and [LP writes](https://useagentos.dev/docs/core/lp-write). The trading desk's **Liquidity** tab lists every liquidity position the desk's wallets hold on Uniswap (V2, V3, V4), Aero and Aerodrome, on Base and Robinhood Chain: the pair, the range with the price marked on it, what is deposited, unclaimed fees and gauge rewards, and the value. Out-of-range positions come first. The engine reads the chain only while the tab is open and serves its cache in between. A Uniswap V4 row has **Collect** and **Remove** buttons: each prepares an order that waits for your approval on the Approvals tab, and nothing is signed before that. Positions on the other protocols are listed only. See [the liquidity book](https://useagentos.dev/docs/core/lp-book). ## Sidebar The sidebar lists your sessions, grouped by Today, Yesterday and This week, with project folders above them. - **Projects** are folders. Drag a session onto a folder to file it there (onto the "Sessions" header to unfile it). The `+` just left of a folder's chat count starts a new chat in that project with its agent; it appears on hover or keyboard focus. Click a folder to open its page, where the title renames on click and the shared brief saves itself (⌘S saves now). See [Projects](https://useagentos.dev/docs/core/sessions#projects-group-sessions-and-share-knowledge). - **Session names** come from the first message, whether the chat started here, in the Web UI or in a channel such as Telegram. A name you set is never overwritten. See [Session titles](https://useagentos.dev/docs/core/configuration#session-titles). - **Right-click a session** to rename, pin, mark as unread, export as Markdown, move it to a project, archive or delete it. - **Pinned** sessions sit in their own section at the top of the sidebar, above Projects. Right-click a session and choose **Pin** (or **Unpin**), or ask the agent in chat ("pin this session"). Pins are stored on the gateway, so the Web UI shows the same ones; a pinned session filed in a project appears both on top and in its folder. See [Pin a Session](https://useagentos.dev/docs/core/sessions#pin-a-session). ### Selecting several sessions | Action | Effect | | --- | --- | | ⌘-click | Add or remove one row from the selection. | | ⇧-click | Select the range from the last row clicked, in the order shown (chats inside open project folders included). | | ⌘A | Select every row shown. | | Escape | Clear the selection. | Right-click inside the selection for one menu that acts on all of it: **Pin**, **Mark as unread**, **Archive** and **Delete N sessions…** (asked once). Rows the gateway could not delete stay selected and a toast gives the count. A plain click still opens a chat and clears the selection. ## Scheduled jobs and skills **Scheduled jobs** (⌘⇧J) opens as a panel over the current view, so checking a schedule never leaves the conversation. Jobs use the same `cron.*` model as the Web UI and `agentos cron`, with a natural-language schedule builder. See [Scheduling](https://useagentos.dev/docs/core/scheduling). **Skills** (⌘⇧K) browses and installs skills; see [Skills](https://useagentos.dev/docs/core/features/skills). ## Quick Ask Press **⌥ Space** in any app to open a small prompt over it, the way Spotlight works. Type a question and press **Return** to ask it in a new chat, or **⌥ Return** to add it to the chat the window was on (or the last one you opened). AgentOS comes forward on that chat with the reply streaming. **Escape** or a click elsewhere closes the prompt without sending; what you typed is still there next time. Settings › Behaviour › Quick Ask turns the shortcut off or moves it to ⌃ Space or ⌘⇧ Space. If another app already uses the key, the pane says "Unavailable"; choose another one. The prompt works while the app is running, even with its window closed. A question asked while the gateway is stopped waits in the chat and is sent once the gateway is running again. ## Runtime status and what needs you The toolbar's status capsule shows the same runtime truth as the Web UI's status button at the bottom of the rail: **Ready**, **Degraded**, **Connecting**, **Blocked**, **Offline** or **Unknown**, with how fresh the view is (`Live · 12 s`, `Snapshot · 3 min`, `Unavailable`). Click it for the reason and one way forward. Because the app runs the gateway, a stopped gateway reads Offline and offers **Start gateway** (an external gateway offers **Retry connection** instead: the app never starts or stops a gateway it does not manage). The tray icon beside it opens **Needs you**: approvals of every kind, agent questions (`ask_user`) and runtime issues in one list, with a count on the icon. Approve, deny, pick an answer or type a reply right there; the same command waiting in several sessions is grouped ("Seen in N sessions") and each occurrence links to its session. Runtime issues come from the doctor and the connection: open the fix steps in place, jump to the right Settings section, dismiss for this session, or **Restart gateway**, which asks before restarting. Questions are collected from the sessions this window has open; the gateway does not list unanswered questions. ## Notifications The app notifies you when a reply finishes or fails, when an approval is needed, when a scheduled job runs, and when the gateway stops on its own. While you are watching the session in question it only plays the sound. The toolbar bell keeps recent notifications, a Do not disturb switch (30 min, 1 h, 3 h, until tomorrow 9:00) and a sound toggle. Settings › Notifications holds the per-event switches, the minimum reply length, the sound, and the Dock badge and bounce. If nothing shows, check that AgentOS is allowed in System Settings › Notifications and that no Focus mode is on. ## Settings Open Settings with ⌘, or the toolbar gear. Escape or **Done** closes it. | Group | Sections | | --- | --- | | Agent | Providers, Pilot Router, Skills, Channels, Environment, Trading | | App | Gateway, Appearance, Notifications, Security, Behaviour, Shortcuts | | More | Advanced, About | Providers and Pilot Router edit the gateway's own configuration through the same guided setup the Web UI uses. Appearance holds the theme (system/light/dark), the colour palette, text size, reduced transparency and the optional pet mascot. Behaviour holds open at login, what to open at launch, stopping the gateway on quit, the Quick Ask shortcut, and Return vs ⌘Return to send. Channels is the Web UI's Channels screen inside the app: every messaging adapter the gateway is configured with (Telegram, Discord, Slack, Microsoft Teams, Email), its live status, when it connected and how often it has been restarted. **Add channel** opens a sheet built from the gateway's adapter catalog: pick the adapter, paste what it needs, save; **Configure** reopens it for an existing channel with the adapter and name locked, and a secret left blank keeps the one already stored. Each card has an Enabled switch, Restart and Remove, and a Telegram card lists who is waiting to pair and who is in, with Pair, Deny and Disconnect. Changes to the configuration restart a gateway the app manages so they apply at once; with an external gateway the pane only says to restart it on its host, with no **Restart gateway** button (the app does not run that process). Providers and Router do the same. Environment is the Web UI's Environment screen inside the app: every variable the gateway, its providers and your skills read, grouped by what uses it, with set, missing and shadowed counts. Set, replace, import from a source that already holds the credential, or remove a variable in `~/.agentos/.env`; **Add variable** stores one of your own. Listings never carry a value. Showing a secret asks first, is rate limited by the gateway, and hides again after 30 seconds. ## Updates The app and the engine update together from one release. - New releases show up as an **Update** pill in the toolbar and a single notice. Nothing downloads or installs until you click: **Update** updates the engine in place, then downloads the app; **Restart** installs it. The pill stays until the release is fully applied. - Settings › About has an **Engine** card and an **App** card. Each shows the running version and a **Latest** row with the newest version ("Not checked yet" before the first check) and, while the app downloads, the download percent beside it. - An engine update restarts the gateway, so it goes through a preflight in Settings › About first: running sessions, scheduled jobs due in the next 10 minutes, and pending approvals. A pending approval blocks the update (with a way to **Needs you**); running work only warns, and the update starts once you confirm (**Update anyway**). The notice's **Update** opens that preflight too. - Scheduled jobs the gateway reports as degraded carry a **Degraded** chip with the failure streak, and the last error, in the job's detail pane. - After `agentos upgrade` in a terminal, the app offers **Restart gateway** so the running gateway picks up the new engine. - With an external gateway (Settings › Gateway › Run mode External) the engine on this Mac is not the one running, so it is left out: no **Update** for it, no **Restart gateway**. Instead, when the connected gateway runs an older release than the latest, the toolbar shows **Gateway outdated** and About has a **Gateway** card with only its running version and the latest. There is no button: update the gateway on its own host (`agentos upgrade`, or pull the new image) and restart it there. The App card updates as usual. ## Keyboard Shortcuts The full list is in Settings › Shortcuts. | Keys | Action | | --- | --- | | ⌥ Space (from any app) | Quick Ask (Settings › Behaviour) | | ⌘N | New session | | ⌘⇧O | New chat in this agent | | ⌘, | Open settings | | ⌘⇧K | Open skills | | ⌘⇧J | Open scheduled jobs | | ⌘⇧T | Switch Chat / Trade | | ⌘⇧S | Show or hide the sidebar | | ⌘+ / ⌘− / ⌘0 | Larger UI / smaller UI / actual size | | Escape | Stop the current reply, or close a sheet | | Return (or ⌘Return) | Send; the other key adds a new line (Settings › Behaviour) | | ↑ / ↓ | Previous or next message you sent | | / | Slash commands | | ⌘S | Save a project brief now | ## Troubleshooting - **"The gateway is not running."** Start it from the sidebar, or open Settings › Gateway for Start, Stop and Restart and the endpoint. See [Gateway](https://useagentos.dev/docs/core/gateway). - **"Gateway exited with a configuration error (exit 78)."** The gateway the app started refused its configuration (a config file that does not parse or validate, a migration that cannot apply). The app does not change your configuration: `agentos doctor` has no automatic fix, so the app runs `agentos doctor --json` once to name the problem (the first error finding and its fix command appear in Settings › Gateway and the sidebar tooltip), retries the start once in case it was already fixed, and then shows the error. Fix what doctor names, then press Start. - **Gateway shows "starting" for a few seconds.** The app reports the gateway running once its `/ready` probe answers, after the channels have started; until then the chat keeps connecting on its own. - **Install failed.** The failure screen offers Retry, Copy output and Show log in Finder; the log is in `~/.agentos/logs/bootstrap-<timestamp>.log`. - **Copy diagnostics** in Settings › Advanced copies a report with the gateway token redacted, for a bug report. For building the app from source, see [`desktop/README.md`](https://github.com/use-agent-os/agent-os/blob/main/desktop/README.md). --- # Sessions and History > Source: https://useagentos.dev/docs/core/sessions Sessions are durable AgentOS conversations. They let you inspect past work, resume a conversation, export a transcript, or stop a turn that is still running. Use sessions when you want to: - continue a previous chat from the CLI or Web UI; - find the session key for an artifact, cost report, or channel thread; - export a transcript for debugging or sharing; - abort a long-running turn without deleting the session; - delete old sessions after you no longer need them. ## Requirements Session commands use the gateway RPC surface. Start or connect to the gateway before running most session commands: ```sh agentos gateway run ``` Or use the managed background gateway: ```sh agentos gateway start --json agentos gateway status ``` ## List Recent Sessions ```sh agentos sessions list agentos sessions list --limit 20 agentos sessions list --status idle agentos sessions list --agent main agentos sessions list --channel telegram agentos sessions list --since 2026-05-01 agentos sessions list --search api-refactor ``` `--search` (`-q`) matches the session name, key, subject, and model, so a renamed session is findable by the label you gave it. Use `--json` for scripts: ```sh agentos sessions list --json ``` ## Inspect a Session ```sh agentos sessions show <session-key> agentos sessions show <session-key> --json ``` The output includes the resolved session key, agent id, status, model, update time, title, and the latest preview when available. ## Rename a Session Sessions are auto-named. Give one a label you will recognize later: ```sh agentos sessions rename <session-key> "api-refactor" agentos sessions rename api-refactor "bug-46" # target by the current name agentos sessions rename <session-key> --clear # back to the auto name ``` Inside a chat, `/rename <name>` renames the session you are in; `/rename` with no argument clears the name. Names are trimmed, collapsed to a single line, and capped at 120 characters. Once set, the name shows in `sessions list`, the chat toolbar, and the Web UI session list, and `resume`/`show`/`--search` all accept it in place of the key. You can also just ask the agent — "call this session api-refactor". The `session_rename` tool renames the session the agent is running in, and only that one; asking it to clear the name drops back to the auto name. ## Pin a Session Pinned sessions sit in a **Pinned** section at the top of the session list, in the Web UI and in the desktop app (there, above the project folders). Pin the ones you keep coming back to: ```sh agentos sessions pin <session-key> agentos sessions pin api-refactor # target by name or short id agentos sessions unpin <session-key> ``` In the Web UI and the desktop app, right-click a session and choose **Pin** or **Unpin**. You can also ask the agent — "pin this session", or "pin the session called api-refactor". The `session_pin` tool pins the session the agent is running in unless you name another one. Pins are stored on the gateway, so every client shows the same Pinned section. A pinned session stays listed however old it gets, and pinning is not activity: the session keeps its place in time. Deleting a session removes its pin. ## Resume a Session ```sh agentos sessions resume <session-key> ``` This opens terminal chat on the existing session. Use it when you want to keep the same conversation state instead of starting a fresh chat. ## Abort a Running Turn ```sh agentos sessions abort <session-key> agentos sessions abort <session-key> --json ``` Abort stops the running turn if one exists, together with any coding-agent or subagent runs it spawned, and returns once they have ended. It does not delete the session. A turn that is streaming or between steps when you stop it is asked to stop first. The model's stream is closed at once, no further request is sent, and the turn ends on its own with its reply so far marked `[interrupted]`. If it has not stopped within `task_runtime.turn_cancel_grace_seconds` (default `5`; `0` stops at once), its task is cancelled. Stopping it a second time during that grace cancels it at once. A turn running tools, or an ACP harness turn, is cancelled at once, so a stop never waits on a long tool. ```toml [task_runtime] turn_cancel_grace_seconds = 5 ``` A turn that is aborted while tools are running leaves a transcript the next turn can replay as is. Every tool call that had not finished gets a "Cancelled" error result, and the turn ends with a note telling the model it was interrupted, so tools may have partly run. Subagents of one parent session run at most two at a time by default. More spawns are accepted and wait in spawn order (`sessions_spawn` reports them as `queued`); children of other parents are not held back. Change the default with `subagents.max_concurrent_children` (`0` = no per-parent limit), or per agent with `subagents.max_concurrent_children` in its entry. The hard cap on how many children a parent may have at all is still `max_children_per_session`. ```toml [subagents] max_concurrent_children = 2 ``` Child runs have a separate nested pool of `task_runtime.max_nested_concurrency` slots across all parents (default: the value of `max_concurrency`) that only children use. While a parent's turn is still running (for example waiting on a child with `sessions_yield` and a `session_key`), its children take nested slots first, so they still start when every shared slot is busy. Any other child takes a shared slot first and a nested one when the shared slots open to children are taken. In the shared pool children always leave `subagents.subagent_reserved_slots` (default `2`, at most `max_concurrency - 1`) free, so your own message starts at once even while children of finished turns are still running. A child keeps its slot until it ends. Running turns never exceed `max_concurrency + max_nested_concurrency`, at any nesting depth, whatever `max_concurrent_children` is. ```toml [task_runtime] max_concurrency = 4 # max_nested_concurrency = 4 # default: max_concurrency ``` A chain of parents each waiting inline on its own child can fill both pools; the extra children then wait for a slot until something ends (the inline wait has its own timeout). If the gateway restarts while subagent runs are in progress, they are not resumed. Each is marked `abandoned` (reason `process_restart`), and their parent is woken once with all of its children's results, so it does not wait forever. A second restart does not announce the same children again. Waking the parent is durable. Each wake is written to the session database before it is sent, and counts as delivered only once the task runtime accepts it. If sending fails, for example while the runtime is draining, the wake is retried after 1 s, then 5 s, then 30 s, then every minute, for up to 30 minutes. A wake still pending when the gateway stops is sent by the next boot. A parent is never woken twice for the same group of children, and an aborted parent is not woken at all. - A parent that closes its spawn group (`sessions_yield` without a `session_key`) while children still run records the group as `awaiting`. The last child's completion turns it into the pending wake. If the gateway stops in between, the next boot wakes the parent of every closed group whose children have all ended. - A parent whose interrupted turn is being resumed by restart recovery is not also woken for its abandoned children; their results are still added to its transcript. - A wake whose delivery has had no outcome for 10 minutes is taken over and retried; one still not delivered 30 minutes after it was written is given up (`delivery_timeout`). Only then does the session's task-group card show the group as failed. - Deleting a session (or pruning stale sessions) deletes its wake records. Delivered, given-up and awaiting records are deleted after 7 days. ## Export a Transcript Export Markdown: ```sh agentos sessions export <session-key> agentos sessions export <session-key> --output session.md ``` Export JSON: ```sh agentos sessions export <session-key> --format json --output session.json ``` Exported transcripts are useful for bug reports, audits, or moving a task into a document. Transcripts export messages from the gateway's active chat history window (up to the 200-message gateway limit). Remove secrets, private local paths, provider tokens, and private channel identifiers before sharing an export publicly. ## Delete a Session ```sh agentos sessions delete <session-key> agentos sessions delete <session-key> --yes ``` Deleting a session is for cleanup. Export first if you may need the transcript later. ## Projects: Group Sessions and Share Knowledge ```sh agentos projects create "Token research" --knowledge-file notes.md agentos projects move <session-key> <project-id> # 'none' detaches agentos projects show <project-id> agentos projects update <project-id> --knowledge "Revised shared context" agentos projects delete <project-id> # sessions survive, detached ``` A **project** groups chat sessions and carries a shared **knowledge** text. Projects sit above agents: sessions of any agent can join the same project, and the project page lists its sessions grouped per agent. Every session in the project gets the knowledge injected into its system prompt as a `Project Knowledge` block on every turn — edit the knowledge and the next turn of every member session sees the new version. A project's `agent` field is only the **default agent** that "New chat in project" starts sessions with, not a membership boundary. - Create a session directly inside a project from the Web UI Projects page ("New chat in project"), or move existing sessions in and out at any time. - Deleting a project **never deletes its sessions** — they detach, keep their history, and simply stop receiving the shared knowledge. - The agent can manage projects from prompting via the `projects_create`, `projects_list`, `projects_update`, and `projects_move_session` tools, and can search sibling transcripts with `session_search scope=project`. These tools are scoped to the calling session — knowledge is readable/writable only for the session's own project, and only the calling session itself can be moved — because knowledge a tool writes lands in every member session's system prompt. Cross-project management stays on the Web UI / CLI surface. - Existing databases migrate automatically on gateway start: old sessions come up project-less (`project_id` empty) and behave exactly as before. ## ACP Harness Sessions When the agent delegates to an external coding harness with `sessions_spawn(runtime="acp", acp_agent="claude", ...)`, the child is a regular session whose key looks like `agent:main:acp:1a2b3c4d`. It shows up in `agentos sessions list`, keeps its own transcript and token/cost totals, and its final answer is pushed back to the parent with a `Stats:` line. `oneshot` children close after one turn; `persistent` ones accept `sessions_send` follow-ups (`steer` cancels the running turn first). `agentos acp sessions` lists the harness side (process, resume record), `agentos acp cancel <key>` stops a running turn and `agentos acp close <key>` ends the harness. See [ACP Coding Harnesses](https://useagentos.dev/docs/core/acp-agents). ## Web UI Workflow The Web UI uses the same session system. In the control console, the **Sessions** list in the rail lists, searches and opens sessions (by name as well as by key); a row's `⋯` menu (or right-click) has Open in new tab, Rename, Pin, **Move to project** (choose a project, or **No project** to detach the session), Reset, Export, Copy session key and Delete. The **Sessions** page (`/control/sessions`) does the same in bulk; click a row's name to rename it inline — Enter saves, Escape cancels, and an empty value clears the custom name. In Chat, the header `⋯` menu has Rename, Compact, Reset session, Export and Copy session key; the header shows the name once set. See [Web UI](https://useagentos.dev/docs/core/web-ui). Open: ```text http://127.0.0.1:18791/control/ ``` ## Troubleshooting If commands cannot reach the gateway: ```sh agentos gateway status agentos doctor ``` If old context appears summarized, the session may have compacted older history. This is normal for long sessions under context pressure. Export the session when exact text matters. Read next: - [Compaction and Cache Continuity](https://useagentos.dev/docs/core/features/compaction-and-cache) - [Web UI](https://useagentos.dev/docs/core/web-ui) - [Operations](https://useagentos.dev/docs/core/operations) --- # Glossary > Source: https://useagentos.dev/docs/core/glossary This glossary defines common AgentOS terms in user-facing language. It is not a runtime design document. ## Agent A named AgentOS identity with defaults such as model, workspace, name, and description. The built-in `main` agent is always available. Read: [Durable Agents](https://useagentos.dev/docs/core/agents) ## Artifact A file or media output produced by a run, such as an HTML page, report, image, spreadsheet, PDF, or slide deck. Read: [Artifacts and Media](https://useagentos.dev/docs/core/artifacts-and-media) ## Approval A human decision required before a sensitive tool action can continue. Approval behavior depends on the surface, permission profile, and tool policy. Read: [Approvals and Permissions](https://useagentos.dev/docs/core/approvals-and-permissions) ## Channel A messaging integration such as Telegram, Slack, Discord, terminal, or websocket-style clients. Read: [Channels](https://useagentos.dev/docs/core/channels) ## Compaction The process of reducing old context in a long session so the agent can continue within the model's context budget. Read: [Compaction and Cache Continuity](https://useagentos.dev/docs/core/features/compaction-and-cache) ## Diagnostics Runtime logging controls used to understand routing, provider behavior, compaction, tool compression, cache behavior, and delivery failures. Read: [Diagnostics and Replay](https://useagentos.dev/docs/core/diagnostics-and-replay) ## Gateway The local server behind the Web UI, channels, sessions, approvals, diagnostics, usage, and RPC clients. Read: [Gateway](https://useagentos.dev/docs/core/gateway) ## Memory Durable user or project context that can be searched and recalled later without stuffing every old transcript into the active prompt. Read: [Memory](https://useagentos.dev/docs/core/features/memory) ## Permission Profile The chosen tool-access posture for a run, such as `restricted`, `on`, `bypass`, or `full`. Read: [Approvals and Permissions](https://useagentos.dev/docs/core/approvals-and-permissions) ## Provider An LLM backend configured for AgentOS, such as OpenRouter, OpenAI, Anthropic, Gemini, DeepSeek, DashScope, or Ollama. Read: [Providers and Models](https://useagentos.dev/docs/core/providers-and-models) ## Replay A read-only view of a recorded turn from the decision log. Replay does not re-run tools. Read: [Diagnostics and Replay](https://useagentos.dev/docs/core/diagnostics-and-replay) ## Scheduler The `agentos cron` feature for recurring and one-time AgentOS runs. Read: [Scheduling](https://useagentos.dev/docs/core/scheduling) ## Session A durable conversation or task history. Sessions can be listed, resumed, exported, aborted, or deleted. Read: [Sessions and History](https://useagentos.dev/docs/core/sessions) ## Skill A reusable package of task-specific guidance, scripts, or workflow instructions that AgentOS can load when needed. Read: [Skills](https://useagentos.dev/docs/core/features/skills) ## Pilot Router AgentOS's local routing layer for choosing an appropriate model tier per turn. Every routing strategy — the default `pilot-v1` local ML model and the LLM judge — runs inside it. Read: [Pilot Router](https://useagentos.dev/docs/core/features/pilot-router) ## pilot-v1 The default Pilot Router strategy: an AgentOS-native, English-optimized local ML model (MiniLM embeddings + ONNX) that picks the tier on-device with no LLM call. Read: [Pilot Router](https://useagentos.dev/docs/core/features/pilot-router#the-pilot-strategy) ## Tool Compression A context-saving feature that keeps large tool results useful while sending a smaller preview to the model. Read: [Tool Compression](https://useagentos.dev/docs/core/features/tool-compression) ## Workspace The local directory a task is allowed or expected to work in. Workspace flags help contain file and shell work. Read: [Tools, Approvals, and Sandbox](https://useagentos.dev/docs/core/tools-and-sandbox) --- # Feature Catalog > Source: https://useagentos.dev/docs/core/features AgentOS combines a personal-agent runtime with model routing, tools, memory, channels, scheduling, and reusable skills. ## Product Surfaces | Surface | What it is for | | --- | --- | | Web UI | Local control console, setup, chat sessions, approvals, logs, channels, and usage surfaces. | | CLI chat | Interactive terminal agent work. | | CLI agent | Single-turn automation, CI-like runs, and benchmark-style invocations. | | Gateway RPC | Local server surface for Web UI, CLI clients, channels, and external clients. | | Channels | Telegram, Slack, Discord, terminal, and websocket-style integrations. | ## Distinctive Features ### Agentic Trading Trading is a first-class capability. A featured Robinhood Trading MCP preset and bundled skills cover market research, portfolio analysis, order execution, and liquidity management, behind explicit confirmation and the standard approval layers. Read: [Agentic Trading](https://useagentos.dev/docs/core/features/agentic-trading) ### Pilot Router Local routing for model tier selection. It is designed to keep easy turns cheap and reserve expensive models for work that needs them. Read: [Pilot Router](https://useagentos.dev/docs/core/features/pilot-router) ### Tool Compression Large tool outputs are projected into compact provider-visible previews while the runtime can keep richer raw results out-of-band. Read: [Tool Compression](https://useagentos.dev/docs/core/features/tool-compression) ### Memory Durable memory lets AgentOS recall useful user preferences, project notes, and previous task traces without forcing every old transcript into the active prompt. Read: [Memory](https://useagentos.dev/docs/core/features/memory) ### Skills Skills package task-specific guidance and scripts so the agent can load the right operating instructions only when a task needs them. Read: [Skills](https://useagentos.dev/docs/core/features/skills) ### ACP coding harnesses The agent can hand coding work to Claude Code, Codex, Gemini CLI, Cursor, GitHub Copilot, OpenCode and 20 more external coding agents over the Agent Client Protocol: `sessions_spawn(runtime="acp")` starts the harness as a child session with structured events, permission prompts routed to the approval queue, resume, cancel, and token/cost accounting, and the result is pushed back to the parent. `agentos acp run` drives one by hand. Read: [ACP Coding Harnesses](https://useagentos.dev/docs/core/acp-agents) ### Browser automation The `browser` tool drives a real Chromium — navigate, read pages as accessibility snapshots, click, type, run JavaScript, and answer dialogs — via the `agent-browser` engine, with SSRF, secret, and eval policy enforced in AgentOS. Managed headless by default; opt-in attach to your own Chrome. Read: [Browser automation](https://useagentos.dev/docs/core/features/browser) ### Compaction and Cache Continuity Long sessions can compact old context, preserve recent task state, and report compaction lifecycle events. Read: [Compaction and Cache Continuity](https://useagentos.dev/docs/core/features/compaction-and-cache) ### Sessions and Durable Agents Sessions preserve conversation continuity, exports, and running-task control. Durable agents provide named identities and defaults for recurring workstreams. Read: [Sessions and History](https://useagentos.dev/docs/core/sessions) and [Durable Agents](https://useagentos.dev/docs/core/agents) ### Usage, Diagnostics, and Permissions Usage reports explain recent model spend. Diagnostics and replay help inspect a turn after it runs. Permission and approval controls keep tool access matched to the task. Read: [Usage and Cost](https://useagentos.dev/docs/core/usage-and-cost), [Diagnostics and Replay](https://useagentos.dev/docs/core/diagnostics-and-replay), and [Approvals and Permissions](https://useagentos.dev/docs/core/approvals-and-permissions) ## Core Runtime Capabilities - Unified `TurnRunner` path across Web UI, CLI, and channels. - Provider abstraction for OpenAI-compatible APIs, Anthropic, Ollama, and other configured backends. - Streaming responses, tool calls, retries, approvals, artifacts, and final usage accounting. - Durable session storage with transcript, summaries, context states, and replay support. - Per-agent workspaces and durable agent entries. - Subagent support for bounded delegation. ## Tools AgentOS includes tools for: - Filesystem read/write/edit/list/glob/grep. - Shell commands, background processes, and code execution. - Git status, diff, log, and commit. - Web search and web fetch. - Memory search/save/get/delete. - Session search, session spawn/send/history/status. - Artifact publication. - Image generation, PDF, TTS, and media workflows. - Spreadsheet, PPTX, DOCX, CSV, and PDF authoring through bundled skills. - Cron and gateway administration. - Skill listing, viewing, creating, editing, and installing dependencies. Read: [Tools, Approvals, and Sandbox](https://useagentos.dev/docs/core/tools-and-sandbox) ## Skills Bundled user-facing skills include: - `deep-research` - `summarize` - `memory` - `cron` - `github` - `docx` - `pptx` - `xlsx` - `pdf-toolkit` - `html-to-pdf` - `multi-search-engine` - `weather` - `tmux` - `sub-agent` Read: [Skills](https://useagentos.dev/docs/core/features/skills) ## Scheduling The `cron` command group manages scheduled AgentOS runs: ```sh agentos cron list agentos cron add \ --every 1h \ --text "Summarize important project updates" \ --name hourly-project-check agentos cron status <job-id> agentos cron run <job-id> agentos cron runs <job-id> ``` Scheduled jobs can deliver work through configured surfaces such as channels or webhooks depending on the configured job. Read: [Scheduling](https://useagentos.dev/docs/core/scheduling) ## Migration AgentOS can import compatible state from OpenClaw and Hermes Agent: ```sh agentos migrate openclaw --json agentos migrate openclaw --apply agentos migrate hermes --json agentos migrate hermes --apply ``` Read: [MIGRATION.md](https://github.com/use-agent-os/agent-os/blob/main/MIGRATION.md) --- # Agentic Trading > Source: https://useagentos.dev/docs/core/features/agentic-trading AgentOS treats trading as a first-class capability. Market research, portfolio analysis, and order execution reach the agent through partner-authorized connections and skills that ship with the product, so you do not have to wire up an unofficial API or paste credentials into a chat window. Three mechanisms provide it: - **MCP connections** — a featured Robinhood Trading preset in the Web UI, and any other MCP server you choose to add. - **Bundled skills** — trading, research, and liquidity skills installed with AgentOS and loaded only when a task needs them. - **Partner skills** — Bankr and Capminal skills you install in one click from the Community hub. Both run behind the same approval and sandbox layers as every other tool. > Agentic trading involves significant risk. Review a connection's access and > action permissions before authorizing it, and read > [Approvals and Permissions](https://useagentos.dev/docs/core/approvals-and-permissions) before > letting any automation place orders. ## Robinhood Trading MCP The Web UI ships a featured preset for Robinhood Agentic Trading. | Setting | Value | | --- | --- | | Endpoint | `https://agent.robinhood.com/mcp/trading` | | Transport | Streamable HTTP | | Authorization | Provider-hosted OAuth flow | Open **Settings › MCP**, select the Robinhood Trading preset, and save it. Saving opens the provider authorization flow and loads the server's tools without a gateway restart. For scripted deployments, declare the same server in TOML: ```toml [mcp] enabled = true connect_timeout_seconds = 10 [[mcp.servers]] name = "robinhood-trading" transport = "streamable_http" url = "https://agent.robinhood.com/mcp/trading" oauth = true tool_timeout_seconds = 30 ``` See [Configuration](https://useagentos.dev/docs/core/configuration) for the full MCP configuration reference and [Web UI](https://useagentos.dev/docs/core/web-ui) for the connection UI. ### Account scope Robinhood's own documentation defines the product scope; the live authenticated MCP schemas are authoritative for tool names, parameters, supported order types, and available asset classes. - The connected agent can **read** all Robinhood accounts, including account numbers, positions, balances, transaction and order history, watchlists, and scans. - Trade **placement** is restricted to the dedicated Robinhood Agentic account, even though read access is broader. ### How the agent is expected to behave The bundled `robinhood-agentic-trading` skill encodes the operating rules: 1. Confirm the connected server is the intended Robinhood Trading endpoint. 2. Complete the provider-hosted authentication flow. Never ask for OAuth codes, access tokens, account numbers, or credentials in chat. 3. Discover the current tools and read their complete input schemas before planning calls. Never invent a tool name, parameter, enum value, order type, or asset class. 4. Re-discover tools after reconnecting, or when a schema error indicates that capabilities changed. 5. If the connection, authentication, or a required tool is unavailable, stop and explain the gap rather than substituting an unofficial API. ## Bundled trading and research skills These install with AgentOS and load on demand. Skills marked `risk: high` declare `signing` capability. The ones that sign with a hot-wallet key of their own (`senior-unilp-manager`, `poolsdotfun-token-launcher`, `gmgn-swap`, `gmgn-cooking`) never see that key in the agent's shell; AgentOS passes it to a single direct run of the skill's entry point, and asks you to approve any run that moves funds — see [Safety model](#safety-model). | Skill | What it does | | --- | --- | | `robinhood-agentic-trading` | Account and portfolio analysis, market research, order preview, placement, cancellation, rebalancing, and bounded automation over the Trading MCP. | | `robinhood-rwa-addresses` | Resolves a company name or ticker to its Robinhood tokenized-asset token on Robinhood Chain (`4663`) — symbol, contract address, chain id, decimals. Public data source, no key. | | `gmgn-swap` | Buy and sell tokens on Solana, BSC, Base, and Ethereum: single swap, multi-wallet batch, limit orders, stop loss, take profit, and trailing variants. | | `gmgn-market` | Price charts (K-line, OHLCV), trending rankings by volume, new launchpad listings, and hot-search rankings. | | `gmgn-token` | Per-token research: price, market cap, liquidity, holders, top Smart Money and KOL positions, security audit, and social links. | | `gmgn-portfolio` | Wallet analysis: holdings, realized and unrealized P&L, win rate, history, and developer-wallet token history. | | `gmgn-track` | Real-time buy and sell activity from Smart Money wallets, KOL wallets, and wallets you follow. | | `gmgn-holder-analysis` | Holder-structure analysis: chip distribution, entry cost, whale and dev behavior, and risk wallets. | | `gmgn-wallet-analysis` | Copy-trade dossier on one wallet: four pass/fail gates (authenticity, currency, reachability, survivability), what it holds and buys now, copy window, and a size cap. | | `gmgn-wallet-score` | Wallet scoring across three angles: track record, copy-tradeability (with a latency/slippage/gas backtest), and developer reputation for token-launcher wallets. | | `gmgn-cooking` | Token creation and launchpad launches, and launchpad creation statistics. | | `senior-unilp-manager` | Uniswap V4 liquidity on Base (`8453`) and Robinhood Chain (`4663`): inspect pools and positions, then mint, increase, decrease, collect fees, or burn. | The GMGN skills require a `gmgn-cli` install plus `GMGN_API_KEY` and `GMGN_PRIVATE_KEY`. The signing key authorizes orders — treat it as a credential. See [Skills](https://useagentos.dev/docs/core/features/skills) for how skill requirements and secrets are declared and surfaced. ## Partner trading skills from the Community hub These do not ship in the wheel. They are published by partners on the allowlist below and install in one click from **Skills > Community** (or with `agentos skills install <name>`). Because their publisher id arrives from the catalog row rather than from the skill text, they keep their brand on the card while a look-alike dropped on disk does not — see [Safety model](#safety-model). | Skill | Publisher | What it does | | --- | --- | --- | | `bankr` | Bankr | Natural-language crypto trading, tokenized stocks and ETFs (spot or leveraged), portfolio balances with P&L, transfers, token deploys, and automated trading across Base, Ethereum, Polygon, Solana, Unichain, Arbitrum, BNB Chain, and Robinhood Chain. Also fronts the Bankr LLM gateway. | | `aero-stock-lp` | Bankr | Range-LP Coinbase tokenized equities (NVDA, AAPL, GOOGL, META) and AERO/USDC on Aerodrome Slipstream (Base): open, recenter, and exit concentrated-liquidity positions, check pool status, NAV, and yields, and get a portfolio pass with P&L and projected APR. Routes each position to the higher-yielding side — staked for AERO emissions vs unstaked for trading fees — at entry and on every manage pass. Writes go through the Bankr arbitrary-transaction flow. | | `capminal` | Capminal | Cap Wallet operations: deploy tokens via Clanker, Liquid, or Virtuals, claim rewards, manage limit, stop-loss, TWAP, and DCA orders, bridge between Base and Robinhood Chain, and discover x402 APIs. | Each publisher carries further skills in the same catalog; browse the Community tab to see the current list. `bankr` needs the `@bankr/cli` install and a Bankr login; `aero-stock-lp` runs on top of that same Bankr wallet, funded with USDC on Base; `capminal` needs `CAP_API_KEY`. All three authorize spending — treat them as credentials and read [Skills](https://useagentos.dev/docs/core/features/skills) for how requirements are surfaced before an install. ## Local by default AgentOS runs on your own machine. For trading, that changes three things. **Credentials stay on the device.** MCP authorization tokens are written to a `0700` directory on POSIX systems; Windows uses the current user's state-directory ACL. The GMGN request-signing key (`GMGN_PRIVATE_KEY`) and the Uniswap LP signing key (`UNIV4_LP_PRIVATE_KEY`) are local environment values. Nothing is escrowed with a hosted service, and the agent never asks you to paste a credential into chat. **The routing decision never leaves the machine.** The Pilot Router classifies each turn on-device, so a strategy prompt is not shipped to a third party merely to decide which model should handle it. Only the turn that actually runs reaches your chosen model provider. See [Pilot Router](https://useagentos.dev/docs/core/features/pilot-router) for the classifier and its alternatives. **Always-on work runs on hardware you already have.** Scheduled and recurring trading tasks execute through the local gateway rather than a rented agent cloud — see [Scheduling](https://useagentos.dev/docs/core/scheduling). Combined with router-driven model selection, running an agent continuously stays inexpensive. What still leaves the machine is exactly what has to: the broker or exchange API calls themselves, and the model turns you route to a remote provider. ## Safety model Trading skills are held to a stricter standard than ordinary tools. - **Operator approval for every skill write that moves funds.** The skill hot-wallet keys — `UNIV4_LP_PRIVATE_KEY`, `POOLSFUN_PRIVATE_KEY`, `GMGN_PRIVATE_KEY` — are held back from every process the agent can drive (its shell, `execute_code`, cron scripts, MCP servers, coding agents). AgentOS hands one only to a direct invocation of that skill's own entry point, runs its packaged copy itself without a shell, and for a `--broadcast`, a ratchet `arm --confirm`, or a GMGN `swap` / `multi-swap` / `order strategy create|cancel` / `cooking create` first asks you to approve that exact command. `/elevated`, `bypass` and auto-approve do not answer that prompt. The unattended `ratchet.py tick --broadcast` gets the key without asking, but fires only mandates whose `arm` you approved, with the bounds you approved, and always pays the signing wallet itself. Keep these keys in **Settings > Skills**: a key in a file the agent's shell can read (`~/.config/gmgn/.env`) is outside this custody. - **Explicit confirmation.** Skills tagged `[FINANCIAL EXECUTION]` do not act on an inferred intent; they show the user the specific action first. That is the model's instruction; the approval above is what enforces it. - **Dry run by default.** `senior-unilp-manager` splits reads from writes. Its read script cannot sign at all, and a write is a dry run unless it is given both `--broadcast` and the plan hash printed by that same dry run. The plan hash binds the broadcast to the plan that was shown; it is not an approval — the agent can read it back — which is why the broadcast also waits for yours. - **Pinned GMGN CLI.** The `gmgn-*` skills install `gmgn-cli@1.7.1`, and AgentOS refuses to hand `GMGN_PRIVATE_KEY` to any other installed version. That CLI has no confirmation prompt of its own; the approval above is the gate. - **Schema truth.** The agent plans against the live authenticated schemas of the connected server, not remembered API shapes. - **Publisher verification.** A skill cannot mint its own brand. Only bundled skills that ship inside the wheel may name a publisher, and the displayed name, URL, and logo always come from an internal allowlist — currently Robinhood, Bankr, and Capminal. Every other skill takes its brand from the catalog row that installed it, so a look-alike dropped on disk renders as an ordinary unbranded skill. - **Standard approvals.** Everything above sits on top of the normal permission and sandbox layers described in [Approvals and Permissions](https://useagentos.dev/docs/core/approvals-and-permissions) and [Tools, Approvals, and Sandbox](https://useagentos.dev/docs/core/tools-and-sandbox). ## Related - [Web UI](https://useagentos.dev/docs/core/web-ui) - connecting and authorizing MCP servers. - [Configuration](https://useagentos.dev/docs/core/configuration) - MCP and skill configuration. - [Skills](https://useagentos.dev/docs/core/features/skills) - skill discovery, install, and authoring. - [Approvals and Permissions](https://useagentos.dev/docs/core/approvals-and-permissions) - permission tiers and approval prompts. --- # Wallets and Trading > Source: https://useagentos.dev/docs/core/features/trading AgentOS can hold EVM wallets of its own and swap tokens on **Base** and **Robinhood Chain** through a pluggable swap provider: the **AgentOS Aggregator** (default, no key) or the **Uniswap Trading API** (fallback, needs a free API key). The engine owns everything: the encrypted wallet vault, the ledger with cost basis and PnL, quote and swap execution, and the guardrails that bound what an agent may do on its own. The desktop app's Trading page, the `agentos wallet` / `agentos trade` commands and the bundled `wallet-trading` skill are all clients of the same gateway RPC surface (`wallet.*`, `trading.*`). > Swaps move real money and cannot be undone. Start with small amounts, keep > the daily cap low, and treat the vault directory like an SSH key. ## What it does - **Wallets** — create new keys or import a private key / keystore JSON; export either form after re-entering the vault password; label, rename, remove; one wallet is *primary* and is the default for every command. A wallet made or imported without a label is named after its address: its first five characters and its last four (`0xAbC_1234`). - **Bulk wallets** (desktop: *Create new › Bulk create* and *Import Wallets › Bulk import*) — `wallet.createBatch` makes 1–30 wallets at once, each from its own 12-word BIP-39 phrase (the key is the phrase's first account, `m/44'/60'/0'/0/0`, so any wallet app that restores the phrase lands on the same address). The vault keeps the keys and never the phrases: the batch's keys and phrases wait in gateway memory for 15 minutes (forgotten on `wallet.lock`) and `wallet.exportBatch` hands them over once the operator confirms with the vault password, or with Touch ID in the desktop, which downloads them as `no,address,private_key,seed_phrase` CSV. `wallet.importBatch` imports up to 100 raw private keys (one per row in the app) and answers each row by its index — `imported`, `exists`, `invalid` (with why) or `skipped` — without echoing a key back. `wallet.removeBatch` (desktop: *Manage wallets › Select*) removes up to 100 wallets under one vault-password check, all or none: an address the vault does not hold refuses the whole list. Each removed wallet's DCA mandates and triggers end with it, as with `wallet.remove`. - **Balances and portfolio** — native ETH and every ERC-20 the wallet holds, priced through DexScreener (CoinGecko as fallback), with cost basis, realized (FIFO) and unrealized PnL, 24h change, gas spent, and allocation. Per wallet and across all wallets. Every number is read from the RPC; on Base, Blockscout is only asked *which* tokens a wallet holds, so a token received before the wallet was imported shows up without a full resync (Robinhood Chain's Blockscout refuses non-browser clients, so there the sweep and the token registry are the only sources). Clients read the ledger, never the chain: the sync loop (every `sync_interval_seconds`), every settled swap and an explicit `--refresh` (throttled) are what read the chain. A `balanceOf` the node fails to answer leaves the stored amount alone and marks that wallet/chain read `partial` (`failed` when the node was unreachable), which `wallet.balances` reports per chain and the CLI prints under the table. `trading.status` and `trading.portfolio` carry `syncing` and `syncKind`, why the pass in flight runs: `background` (the loop's own clock), `requested` (a resync, a wallet import, a `--refresh`) or `initial` (a wallet/chain swept for the first time, or rebuilt); `null` while none runs. The desktop shows "Syncing" for the last two only: with many wallets the background pass runs most of the time. - **Junk stays out of sight** — anyone can airdrop a token to any address. A token is hidden automatically when nobody lists it (not in the chain's token lists), nobody trades it (no DexScreener pool with at least $1,000 behind it; an unreachable price source is not a verdict) and the wallet never acted on it (never sold, sent, swapped or quoted it). Hidden tokens keep their ledger rows — the balance is real — but are left out of balances, portfolio, history, the totals, the agent's view and the sync's every-60-seconds scan (they are re-read hourly and re-judged daily, so a real launch that gains a pool resurfaces on its own). The desktop shows "N junk tokens hidden" with a Show toggle and a per-token hide/keep; the CLI has `--hidden` and `agentos trade hide`/`unhide`. A user's choice is final, and quoting or swapping a hidden token shows it again. - **History** — deposits, withdrawals, swaps (yours, the agent's, or external), approvals and gas, rebuilt from the chain itself: ERC-20 `Transfer` logs plus native balance reconciliation. No indexer is needed for this; where one exists it only widens the set of tokens the sweep reads. A full resync drops and rebuilds the ledger. - **Swaps** — quote, approve (a plain ERC-20 approval to the provider's spender: the AgentOS Router or 0x's AllowanceHolder for the aggregator, Uniswap's proxy for Uniswap, no Permit2 signatures), sign and broadcast, then confirm from the receipt. A Uniswap quote that carries `permitData` anyway is untrusted input: it is signed only when it is a Permit2 `PermitSingle` / `PermitTransferFrom` on the order's chain and the canonical Permit2 contract, for the order's sell token and at most its amount, to a Universal Router pinned for the chain, with every deadline under an hour away — and what is signed is rebuilt from those checked fields. Anything else (an EIP-3009 transfer, a DAI or EIP-2612 permit, another spender, an unlimited amount) fails the order with `trading.permit_refused` before a signature exists. A swap can target one wallet, several, or all of them as a batch; one wallet failing never blocks the others. - **Agent trading** — the agent signs on its own within code-enforced limits (below). Orders above the per-order threshold wait for a human in the desktop app; the agent is told the outcome and decides what to do next. - **Liquidity book** — every liquidity position the vault's wallets hold, across Uniswap V2/V3/V4, Aero and Aerodrome on Base and Robinhood Chain, staked positions and their rewards included. Cached by the engine and read only while someone looks (`docs/lp-book.md`); the desktop's Liquidity tab shows it. - **Uniswap V4 liquidity** — read a token's pools, their liquidity ranges and the vault's positions (cards in the chat, `docs/lp-cards.md`), and change them: collect fees, remove liquidity (100 % burns the NFT), add liquidity (mint, or top up a position) on Base and Robinhood Chain. Every LP write is an order that **always waits for approval**, whoever asked; on approval the engine re-checks the pool against the approved bounds, approves exactly what the call may pull (ERC-20 → Permit2 → PositionManager, 30-minute Permit2 expiry, never unlimited), sends `modifyLiquidities` and books the receipt as `lp_collect` / `lp_remove` / `lp_add` entries. Nothing is swapped to make up a missing side. Contract: [LP writes](https://useagentos.dev/docs/core/lp-write). - **DCA mandates** — a recurring buy the engine owns: `agentos trade dca create ETH --usd 10 --every 1d --cap 300`. The cap, schedule, `--runs` and `--max-price` guards are ledger rows, enforced by the engine on every tick; each buy is an ordinary swap order under the agent guardrails (a buy under the threshold executes on its own, a larger one parks). An agent may only *propose* a mandate (`awaiting_approval`); the user approves it once from the chat card, the Missions panel or `agentos trade dca approve`. The card in the chat shows the next buy countdown, spent of cap, average buy price vs now and a buys chart, with Pause / Buy now / Stop on the desktop. Contract: [DCA mandates](https://useagentos.dev/docs/core/dca). ## Chains | Chain | Id | Explorer | Notes | | --- | --- | --- | --- | | Base | 8453 | basescan.org | Uniswap Universal Router 2.0 default | | Robinhood Chain | 4663 | robin.etherscan.io | Router 2.1.1 only; public RPC needs a `User-Agent` and has no archive data | Only these two chains are enabled. Funds move between them only through `agentos trade bridge` (Relay): ETH↔ETH and USDC↔USDG, both directions; a bridge from an agent always waits for approval, and the order is `confirmed` only once the fill has landed on the destination chain ([Bridge](https://useagentos.dev/docs/core/bridge)). Native ETH is `0x0000…0000` in the API. A swap into native ETH on an L2 may deliver **WETH** instead; the order then reports `deliveredToken` and the app offers a one-click unwrap (`trading.unwrap`, a `withdraw(uint256)` on the WETH contract). ## Swap providers | Provider | Key | Notes | | --- | --- | --- | | `aggregator` (default) | none | AgentOS DEX at `https://agg.useagentos.dev`, an HTTP API in front of 0x Swap v2. One `GET /v1/quote` returns the price *and* the unsigned calldata, including the ERC-20 approval when one is needed. 20 bps integrator fee, reported in the quote and already deducted from the output. Quotes expire in 30 s upstream; the engine stops trusting them at 20 s. | | `uniswap` | Uniswap Trading API key | Universal Router; `x-agent-info` attribution on every call. Quotes fresh for 30 s. | The aggregator holds no key of its own and neither signs nor broadcasts: reading it cannot move funds. Before anything is signed the engine checks the one relation its calldata cannot hide — the approval's `spender` must be the same contract the swap transaction is sent `to`, and that contract must be one the engine pins itself: the AgentOS Router (`0x4cf93bac8920b1efc92b0d2c84dcbe56802e530c`, the same immutable contract on Base and Robinhood Chain, which the gateway quotes through in contract mode) or 0x's AllowanceHolder (`0x0000000000001ff3684f28c67538d4d072c22734`, when it quotes 0x directly), or one the operator added with `trading.aggregator_trusted_spenders` — and refuses the quote outright otherwise. The approval is always for exactly the order's amount, never unlimited. The tokenised stocks (AAPL, TSLA, NVDA, SPY, … on Robinhood Chain; AAPLc, TSLAc, … on Base) are refused by 0x in either direction, at any size, at any time, for legal reasons (`trading.token_not_tradeable`). Uniswap trades them, and the AgentOS DEX carries Uniswap as a second source, so the engine names it per pair: when `trading.provider` is `aggregator` and either side is a tokenised stock (a row of the chain's stock list, or a name ending `• Robinhood Token`), the quote, the swap, DCA runs and trigger fires ask the DEX with `source=uniswap`. No Uniswap API key is needed and the quote and the order keep `provider: "aggregator"`. A `token_not_tradeable` the flag missed is asked once more from the Uniswap source. Only when that source cannot take the pair does the engine fall back to the Uniswap provider, if a key is configured (the order then records `provider: "uniswap"`); without a key the error is returned with *"The AgentOS DEX's Uniswap source could not take this pair. Retry later, or add a Uniswap API key (`agentos config set trading.uniswap_api_key <key>`) to route through Uniswap directly"* appended. Pairs without a Stock Token keep the configured provider. ETH, WETH and USDG trade normally there. Two more Robinhood Chain facts: the engine has no native USD price there yet, so `--usd` may be refused with `trading.unpriced` (size with `--amount`), and the bare symbol `USDC` resolves to unverified lookalikes (`TOKEN_UNVERIFIED`) — use an address the token search marks `verified: true`. The provider is read from `trading.provider` on **every** call, so switching takes effect immediately, no gateway restart. There is one canonical way to change it: write the config key. The CLI does `agentos trade provider uniswap` (`config.set trading.provider`); `trading.setProvider {provider}` is a thin RPC wrapper over the same `config.set` path. The desktop app swaps through the AgentOS DEX only: it offers no provider to choose and no Uniswap key to enter, and when the gateway's config names another provider it says so and offers one button that sets it back (`trading.setProvider {provider: "aggregator"}`). Prices, balances and history never depend on the provider (DexScreener / CoinGecko / your RPC node); only quoting and calldata do. Which tokens are `verified`, and which are tokenised stocks, comes from AgentOS's own [token lists](https://github.com/use-agent-os/agent-os-token-list), the same ones the AgentOS DEX uses: `base_tokens.json` and `base_stock_tokens.json` on Base, `robinhood_tokens.json` and `robinhood_stock_tokens.json` on Robinhood Chain. The gateway downloads them on first use and keeps them in memory. Each list is re-checked every 15 minutes with its ETag, so an unchanged list costs a `304`, and a download replaces the held copy only when its version is newer: a new release of a list is picked up without a restart, and never rolled back. A list that cannot be reached is asked again after 2, 5 and 15 seconds, then once a minute, while the held copy keeps answering. A token outside the lists is still found by address or through DexScreener, and is shown as unverified. ## Configuration ```toml [trading] enabled = true provider = "aggregator" # or "uniswap" aggregator_base_url = "https://agg.useagentos.dev" aggregator_trusted_spenders = [] # extra aggregator spender/target contracts, on top of the built-in pins uniswap_api_key = "" # only for provider = "uniswap"; or set UNISWAP_API_KEY uniswap_api_key_env = "UNISWAP_API_KEY" approval_threshold_usd = 100.0 # agent orders above this wait for approval daily_cap_usd = 1000.0 # per wallet, agent-initiated swaps only; 0 = agent swaps off approval_ttl_seconds = 900 # unanswered approvals expire agent_max_price_impact_pct = 5.0 # agent orders above this wait for approval even under the threshold agent_max_slippage_pct = 5.0 # an agent asking for more slippage is refused default_slippage_pct = 0.5 # omit to let the provider pick (auto slippage) unlock_mode = "auto" # or "manual": the vault never stores its password, and auto is refused sync_interval_seconds = 60 price_ttl_seconds = 20 [trading.rpc_urls] "8453" = "https://mainnet.base.org" # optional overrides, by chain id or key "4663" = "https://rpc.mainnet.chain.robinhood.com" ``` RPC resolution order per chain: `trading.rpc_urls`, then the environment variables `RPC_BASE_URL` (8453) / `RPC_ROBINHOOD_URL` (4663), then the public default. A custom RPC serves everything that needs a fresh answer (orders, nonces, receipts, fees, the sync's block height, logs and native balance). The wallet sync's bulk ERC-20 balance read goes to the chain's public node first, as one Multicall3 call per wallet, and falls back to the custom RPC when the public node does not answer. Every `[trading]` key is also an environment variable with the `AGENTOS_TRADING_` prefix (`AGENTOS_TRADING_DAILY_CAP_USD=250`, `AGENTOS_TRADING_PROVIDER=uniswap`). The API key is redacted in `config.snapshot` and every public config view like any other `*_api_key`; `rpc_urls` values are shown as scheme and host only (`https://base.drpc.org/…`) because dRPC, Alchemy and Infura keys live in the path. Writing that redacted form back through `config.apply` / `config.patch` keeps the stored URL. `aggregator_base_url` must be `https`; `http` is accepted only for `127.0.0.1`, `localhost` or `::1`. `aggregator_trusted_spenders` adds contracts an aggregator quote may name as the approval spender and send the swap to, on top of the two the engine pins itself (the AgentOS Router and 0x's AllowanceHolder). It is for when the gateway moves to a contract this build does not know yet: rather than waiting for a release, the operator verifies the new address and adds it: ```bash agentos config set trading.aggregator_trusted_spenders '["0x…"]' ``` It only adds; the built-in pins always stay trusted, and the approval's spender must still be the contract the swap is sent to. Each entry must be a 0x address (a mixed-case one must pass its EIP-55 checksum; the zero address is refused), and is stored lower-cased. It takes effect on the next quote, without a restart. Like every `trading.*` key it is operator-only: an agent cannot add a spender. Trust only a contract you have checked — a spender the wallet approves can move up to the approved amount of that token. Get a key from the Uniswap developer dashboard; the desktop's **Settings → Trading** pane has a *Test key* button (`trading.probe`). ## Security model - Keystores are standard Ethereum **keystore v3** JSON files under `~/.agentos/wallets/` (directory `0700`, files `0600`), all encrypted with one vault password. A random *verifier* keystore in `index.json` lets the engine check a password without touching any wallet key. - **Unlock modes**, both OS-independent (no Keychain, no Electron store): - `auto` — the password sits in `~/.agentos/wallets/unlock.key` (`0600`), sealed with AES-256-GCM under a key kept **outside** the state directory (`AGENTOS_VAULT_KEK`, else Windows DPAPI, else a `0600` file under the OS state dir; `AGENTOS_VAULT_KEK_DIR` relocates it, and a key already stored in the default directory is moved on the next auto unlock; the container's `compose.yaml` puts it on its own volume), and the gateway unlocks at first use. This is what unattended agent missions need. The file and its key are both needed, but a process running code as this OS user can read both, exactly as the gateway does — `agentos sandbox` or `manual` unlock is the real boundary against that. A legacy plain-text `unlock.key` still works and is sealed in place on first unlock. The key is injected with `[trading] unlock_mode = "auto"` the default. - `manual` — nothing on disk; unlock per gateway session from the app or `agentos wallet unlock`. Keys live only in the gateway's memory. - **Lock** (`agentos wallet lock`, `wallet.lock`) holds in both modes, and across gateway restarts, until you unlock with the password: `unlock.key` is not read while it holds. Nothing signs: agent swaps fail `wallet.locked`, due DCA buys and armed triggers wait (no failed runs, no auto-pause; alerts still ring), and approving an order is refused with the order left parked. `wallet.status` says `lockedByOperator`. - Export (keystore or raw private key) and wallet removal always ask for the vault password, whatever the mode. Private keys never appear in logs, RPC responses (other than `wallet.export` and `wallet.exportBatch`), or the ledger. `wallet.exportBatch` serves only a batch `wallet.createBatch` made in the last 15 minutes, only while the vault is unlocked, and only with the vault password or `touchId: true` — the desktop sends that after its own Touch ID prompt, the same renderer-side gate that stands in front of every vault write. An empty password is refused, not read as either. - Removing a wallet stops every DCA mandate, trigger and bracket bound to it (`wallet removed`) and rejects what they parked. Importing the same key again is a new wallet as far as approvals go: nothing comes back. - **Ledger seals.** The engine does not sign what it merely reads back from `state/trading.sqlite`. Every order is sealed when the engine writes it, and every mandate, trigger and bracket when you approve it (or create it yourself): an HMAC over the terms that decide what is signed (wallet, chain, tokens, amounts, recipient, slippage and floors, the bridge or LP plan, batch, expiry; for a mandate or trigger its size, price condition and validity), bound to the wallet's incarnation. The key is derived from the vault's password-encrypted secret and exists only in gateway memory while the vault is unlocked, so approving or creating a mandate, trigger or bracket needs an unlocked vault. The seal is checked before every signature and before every DCA buy or trigger fire; a row changed outside the engine is refused (`trading.integrity`; a mandate or trigger is stopped), and the gateway broadcasts `trading.integrity.alert`. Seals survive restarts and password changes; the first unlock after the upgrade that introduced them seals what was already live. - Before signing, the engine checks balances, simulates the transaction with `eth_call`, and validates what the provider returned: an approval must be a plain `approve(spender, amount)` on the token being sold, to a spender the provider is known to use, for no more than the order (or the conventional unlimited allowance); a swap must come from the signing wallet, on the order's chain, carrying exactly the order's native value (zero for an ERC-20 sale), and not be addressed to the wallet or the sold token itself. Anything else is refused unsigned. - `~/.agentos/wallets/` (and any `unlock.key`) is a sandbox *sensitive path*: the agent's file tools cannot read it, and a recursive read, copy or archive of a *parent* directory (`grep -r ~/.agentos`, `cp -r ~`, `tar` of the state root, the `execute_code` equivalents) is refused too, so the vault cannot be swept up from above. The agent trades through the gateway, which is the only thing that needs the keys. So is the ledger, `state/trading.sqlite` with its `-wal`/`-shm`/`-journal` files (file mode `0600`), any copy named `trading.sqlite`, and the pre-upgrade snapshots under `state/snapshots`: the agent reads its orders and history through the gateway, never the file. - Token metadata from third-party APIs is data, not instructions: the skill tells the agent to ignore anything in a token name that reads like a command, and genuine Robinhood Stock Tokens are preferred over lookalikes that reuse the same ticker. ## Who is the agent? Guardrails are only worth anything if the gateway, not the client, decides who is asking. `agentos.gateway.agent_surface` computes an *agent binding* for every admitted connection. One rule orders the signals: **a sign that an agent is asking outranks any proof an agent could have read.** Strongest first: 1. **An agent token.** When an agent turn spawns a shell — or the scheduler runs a `cron --script` job — a token is minted and passed to the child as `AGENTOS_AGENT_TOKEN`; the CLI presents it back and the connection is bound to that session and agent. A script job therefore trades under the agent's rules. A connection that presents *any* agent token — one this gateway does not know (minted before a restart, or made up) included — is an agent's, and an operator secret next to it is ignored. 2. **The peer process (Linux).** The gateway looks up which process holds the client end of a local connection. One the gateway spawned, directly or not — an agent's shell, a background process, `execute_code`, an ACP harness, an MCP server — is an agent's whatever it presents. 3. **The desktop's operator secret.** The desktop app spawns the gateway and hands it a random secret (`AGENTOS_OPERATOR_SECRET_FILE`, a `0600` file the gateway deletes after reading; `AGENTOS_OPERATOR_SECRET` as a fallback, scrubbed from the environment). It never sits on disk or in the environment afterwards, so the app stays the operator even while an agent shell runs. 4. **From another machine, the gateway token.** Neither secret reaches a gateway on another host (a container behind a reverse proxy), so a Control WebSocket that authenticated with the gateway's bearer token from another machine is the operator's too: the desktop app in External mode, the web console and a remote CLI can create, import and unlock wallets and approve orders. The peer is the socket's own address — an `X-Forwarded-For` header never counts — and it must be neither loopback nor one of the gateway host's own addresses: a process on that host which read the token (from `config.toml` or the environment) and dialled the LAN or container address is still on that host. HTTP RPC (`POST /api/v1/rpc`) does not apply this rule. The gateway also keeps its token out of every process an agent runs, whichever variable it came from (`AGENTOS_AUTH_TOKEN`, `AGENTOS_GATEWAY_AUTH__TOKEN`, the hooks token), and drops it from its own environment after boot. 5. **An exec window.** While any agent shell is running (background processes and `execute_code` runs included), a new connection is the agent's unless one of the signals above says otherwise — *including one that presents the operator file below*. A person who opens the CLI in that window gets the agent's rules, which fail safe: their order waits for approval instead of executing, and an approval they try to give is refused with a reason. Approve in the desktop app, or retry once the agent's shell has finished. 6. **The operator file.** The gateway writes its own secret to `<state dir>/wallets/operator.secret` (`0600`, rotated at every boot; the state dir is `~/.agentos` unless `AGENTOS_STATE_DIR` moves it). The CLI reads it only outside an agent's session: never when `AGENTOS_AGENT_TOKEN`, `AGENTOS_SESSION_KEY`, `AGENTOS_AGENT` or `AGENTOS_ACP_LEASE` is present (even empty), and never when a running gateway is among its ancestors, so `env -u` / `env -i` gain nothing. It counts on the WebSocket handshake only. The wallets directory, wherever the state dir is, is a sensitive path for an agent's shell and file tools. 7. **Nothing.** A connection with no secret, no token and no open window is unbound and gets the agent's rules as well: a process an agent detached (`setsid`, `nohup`, `&`) that connects later gains nothing. This is a guardrail, not a sandbox: on a host without the OS sandbox, a process an agent detached and that was re-parented away from the gateway can still read the operator file once no agent shell is running. Turn the sandbox on (`agentos sandbox`) where that matters. An agent-bound connection is `initiator: agent` whatever it declares, and its orders are filed under the session the binding names. These RPCs are **operator-only** and answer an agent with `trading.operator_required`: `wallet.setup`, `unlock`, `lock`, `setUnlockMode`, `changePassword`, `create`, `createBatch`, `import`, `importBatch`, `export`, `exportBatch`, `rename`, `remove`, `setPrimary`; `trading.orders.approve`, `trading.orders.reject`, `trading.tokens.hide`, `trading.unwrap`, `trading.lot.setCost`, `trading.probe` with an `apiKey` (testing a key that is not in config) and `trading.sync` with `full` (dropping and rebuilding the ledger). Every config write (`config.set`, `config.patch`, `config.apply`, onboarding) of any `trading.*` key is refused from an agent as well (as an invalid request, not with a `trading.*` code), and an edit of the config file itself never changes the trading settings of the running gateway: the watcher holds it until the user runs `agentos config reload` or restarts. So `agentos trade approve`, `agentos wallet export` or `agentos config set trading.daily_cap_usd` simply fail inside an agent turn. `wallet.status` and `trading.status` answer an agent without `vaultPath`. A `note` on a swap, send or revoke is stored as the approver will see it: control and bidi characters are dropped, whitespace is collapsed, and it is cut at 240 characters. Token symbols and names (whatever a contract's `symbol()`/`name()` or a feed returns) are stored the same way, without control, bidi or zero-width characters, and a failed order never keeps the caller's unparsed amount. `agentos trade` and `agentos wallet` show any such character left in what they print as a visible escape (`\x1b`, `\u202e`), never send it to your terminal; `--json` output `\u`-escapes C1, bidi and invisible characters (the parsed data is unchanged). `trading.swap` and `trading.send` take a `clientOrderId`: a repeat call with the same id returns the existing order instead of placing a second one (`agentos trade swap|send --client-id`). Swap targets and approval spenders are pinned to the provider's known contracts (a quote naming another address is refused, not signed); the gas limit is the provider's or the estimate plus 20 %, and an order the wallet cannot fund (value plus gas at the quoted fee) is refused before signing. `trading.rpc_urls` are shown host-only in every public config view (`config.snapshot`, `agentos config get`) because provider keys live in the URL path; `trading.aggregator_base_url` must be `https` (plain `http` only for a loopback host). This is not a full sandbox (a same-user process can still read files); it is the difference between a guardrail a prompt can talk its way around and one it cannot. ## Guardrails Code-enforced, and applied to agent-initiated swaps only. | Rule | Default | Outcome when hit | | --- | --- | --- | | Per-order threshold | 100 USD | order parks as `awaiting_approval`; desktop notifies you | | Daily cap per wallet | 1,000 USD (local calendar day) | order is `rejected` outright, not queued; the cap is per wallet, so `--all-wallets` spends up to N caps; an order counts as max(in, out) in USD — but only while the sell side has a feed price; `spentTodayUsd` counts confirmed spend plus orders still in flight, so a burst cannot race its own confirmations; **0 switches agent swaps off** (there is no "unlimited") | | Price-impact ceiling | 5 % (`agent_max_price_impact_pct`) | order parks as `awaiting_approval` even under the USD threshold. "Price impact" here is the price vs reference (it includes the venue fee and feed skew), not pool depth alone. A provider's own figure (Uniswap's `priceImpact`) is cross-checked against the engine's feed and the larger one counts; when the feed cannot price a side the impact is unknown and the order parks, whichever provider quoted it | | Slippage ceiling | 5 % (`agent_max_slippage_pct`) | quote or swap refused with `trading.slippage_too_high`; nothing is queued | | Unpriced order | — | treated as above threshold (fails closed). An agent swap whose **sell** side has no usable feed price (none, zero or non-finite) is unpriced even when the buy side has one: the token you receive never sizes the order on its own. The order shows its value as unknown, not $0 | | Approval TTL | 15 min | `expired`; agent is told | | LP writes (`trade lp collect/remove/add`) | — | **always** park as `awaiting_approval`, from the agent and from you; an agent's `add` counts toward the daily cap (over it: `rejected`), `collect`/`remove` never do; on approval a pool that moved past the approved bounds fails the order with `trading.price_moved` | | Bridges (`trade bridge create`) | — | judged like a send: an agent's **always** parks as `awaiting_approval` and counts toward the daily cap (over it, or with the cap at 0: `rejected`; unpriced: waits); on approval Relay is quoted again, and a fill below the approved floor (1 %) sends the order back for approval (a manual one fails `trading.price_moved`) | Manual swaps from the app or CLI are your own decision: they never queue and do not count toward the agent's cap; if the price moved more than twice the slippage between the quote and the send they fail with `trading.price_moved` so you re-quote with open eyes. `trading.swap` (and `agentos trade swap --expected-out-raw … --min-out-raw …`) accepts the quote's `expectedOutRaw` / `minOutRaw` so the fill is checked against the quote you actually saw: it refuses with `trading.price_moved` when the fill would be more than 2× the slippage worse. Approving an agent order re-quotes it; if the market moved that much since you approved, it goes back to `awaiting_approval` with reason `price moved since approval; please re-approve` instead of executing. `trading.limits` and `trading.status` report every limit (`approvalThresholdUsd`, `dailyCapUsd`, `approvalTtlSeconds`, `agentMaxPriceImpactPct`, `agentMaxSlippagePct`) and `spentTodayUsd`. Every quote result and order carries `provider` (`aggregator` / `uniswap`), `expiresAt` (about 20 s for an aggregator quote, 30 s for a Uniswap one) and `warnings` (a clamped slippage, a route the venue could not fully simulate). The aggregator publishes no price-impact figure and prices gas in ETH rather than dollars, so the engine fills both in from its own price feed before the guardrails read them — `agent_max_price_impact_pct` keeps biting on a thin route whichever provider found it. Order statuses: `quoted → awaiting_approval | submitted → confirmed | failed`, with `approved`, `rejected` and `expired` in between (`expired` is an approval nobody answered within the TTL). Rejection `reason`s: a text starting `daily cap` from the cap, `user` or `user: <text>` from the person; a failed order's reason is `<code>: <message>`. A `submitted` order is never orphaned: after a gateway restart, or if its confirm task died, the housekeeping loop picks it up and keeps waiting for the receipt (`recover_submitted`); after 6 hours without one it is marked `failed` ("transaction never mined"). An approval transaction that is not mined within the wait window fails the order with `trading.tx_pending` (retry once it lands). Every change is broadcast on the gateway WebSocket (`trading.changed`, `trading.approval.requested`, `trading.order.finished`), so the desktop never polls for it. A row that failed its seal is announced as `trading.integrity.alert` (`kind` order / mandate / trigger, `id`, `verdict` missing / mismatch, `wallet`, `message`). ## How the agent uses it The bundled `wallet-trading` skill drives the `agentos wallet` and `agentos trade` commands with `--json`. Typical missions: - "Swap 50 USDC to ETH on Base" — `agentos trade swap --chain base --in USDC --out ETH --amount 50 --wait --wait-seconds 600 --json`; a parked order is waited out with `agentos trade order <id> --wait --wait-seconds 600 --json` (`--wait-seconds` without `--wait` returns at once). - "DCA 20 USDC into ETH every day" — a cron job running the swap; each run is a separate order under the same limits, with its own `--client-id` (minute resolution: `dca-eth-$(date +%Y%m%dT%H%M)`). - "Buy WETH if it drops 5%" — quote/price checks on a schedule, swap when the condition holds, report the tx hash and explorer link. - "Rebalance wallets A and B" — `--wallet A --wallet B` or `--all-wallets`; each wallet reports its own result. Amounts are always human units (`0.5`, `1000`), never wei. See [CLI Reference](https://useagentos.dev/docs/core/cli) for the full command reference. ## RPC surface Every client goes through the same gateway methods: | Method | What it does | | --- | --- | | `trading.status`, `trading.limits`, `trading.probe`, `trading.network` | readiness (no `vaultPath` for an agent), the guardrails and today's spend, provider reachability (with `apiKey`: operator-only), head block / gas / RPC latency per chain | | `trading.setProvider` | switch the swap provider (a wrapper over `config.set trading.provider`) | | `trading.tokens.search`, `trading.tokens.resolve`, `trading.tokens.hide` | search a chain's tokens; resolve one address to its metadata (symbol, decimals, verification, price); hide or show a token (operator-only) | | `trading.quote`, `trading.swap`, `trading.send`, `trading.unwrap` | price a swap; place one (per wallet, several, or all); send a token to one or many recipients as one batch; unwrap WETH delivered by a swap (operator-only). `swap` and `send` take `clientOrderId` (idempotency: the same id returns the same order) and a `note` that is sanitised (control/bidi characters, 240 chars) | | `trading.allowances.list`, `trading.allowances.revoke` | live ERC-20 allowances with exposure; `approve(spender, 0)` | | `trading.orders.list`, `trading.orders.get`, `trading.orders.wait`, `trading.orders.batch` | orders (filter by status, wallet, `kind`); one order; block until it settles; every leg of a multisend by `batchId`. An order awaiting approval carries `approval`: what one approve releases (`orderIds`, `legCount`; for a batch leg also `totalRaw`/`total`/`totalUsd` and `unpriced`). A single order's `approval.digest` is on the order itself; a batch's only on `trading.orders.batch` (`approval`, with every leg's `recipient` and amount) | | `trading.orders.approve`, `trading.orders.reject` | the user's decision on a parked order (operator-only). `approve` takes `approvalDigest`, the `approval.digest` the order (or its batch) showed: **required for a multisend** (without it: `trading.approval_binding_required`; one approve runs every awaiting leg) and checked when given for a single order; a digest that no longer matches — a leg changed, added or dropped since it was shown — is refused with `trading.approval_changed`. The digest covers chain, wallet, tokens, raw amounts, recipients, provider, slippage, the approved floor, the plan and the expiry of every leg; the engine holds each leg to it again where the transaction is built and signed, and a send or revoke to its exact `to`/`value`/`data`, so a parked order changed after the approval is failed, not signed | | `trading.decode` | explain a transaction hash or raw calldata | | `trading.lp.pool`, `trading.lp.ranges`, `trading.lp.position`, `trading.lp.positions` | Uniswap V4 read-outs (read-only, allowed for an agent): a token's deepest pool, its liquidity distribution, one position NFT, every position of the vault's (or given) wallets; each echoes `request: {kind, params}` so a card can re-read itself. Payloads: [LP cards](https://useagentos.dev/docs/core/lp-cards) | | `trading.lp.book` | every LP position of the vault's wallets across Uniswap V2/V3/V4, Aero and Aerodrome, from the engine's cache (read-only, allowed for an agent). Params: `wallet`, `chainId`, `refresh`. Answers at once and refreshes behind the answer when the cache is stale; `trading.changed` (`reason: "lp"`) says when. Contract: [The liquidity book (trading.lp.book)](https://useagentos.dev/docs/core/lp-book) | | `trading.lp.collect`, `trading.lp.remove`, `trading.lp.add` | Uniswap V4 writes (allowed for an agent: they only create an order, which always parks for approval). Params mirror the CLI in camelCase — `chainId`, `tokenId`, `pct`, `slippagePct`, `token`, `usd`, `amountBase`, `amountQuote`, `range`, `toPosition`, `wallet`, `note`, `clientOrderId`; the answer is `{"order": …}` with `plan`. Contract: [LP writes](https://useagentos.dev/docs/core/lp-write) | | `trading.bridge.quote`, `trading.bridge.create`, `trading.bridge.status`, `trading.bridge.routes` | bridge ETH or USDC↔USDG between Base and Robinhood Chain through Relay (allowed for an agent: `create` only creates an order, which always parks for approval). `chainId`/`chain` is the origin, `toChainId`/`toChain` the destination, `token`, exactly one of `amount` / `amountUsd` / `amountPct`, `wallet`, `note`, `clientOrderId`, `wait`; `status` takes `orderId` or Relay's `requestId`. The order stays `submitted` until the fill lands, then `confirmed`. Contract: [Bridge](https://useagentos.dev/docs/core/bridge) | | `trading.dca.create`, `trading.dca.get`, `trading.dca.list` | DCA mandates (agent-callable; an agent's `create` parks as `awaiting_approval`): propose a recurring buy, read one, list live ones (`all` for finished). Every answer is a full card payload with `request` echoed. Contract: [DCA mandates](https://useagentos.dev/docs/core/dca) | | `trading.dca.approve`, `trading.dca.reject`, `trading.dca.pause`, `trading.dca.resume`, `trading.dca.stop`, `trading.dca.run`, `trading.dca.update` | the user's decisions on a mandate (operator-only): start it, pause/resume, stop for good, buy now, change cap / size / cadence / max price | | `trading.history`, `trading.portfolio`, `trading.chart`, `trading.sync`, `trading.lot.setCost` | the ledger; holdings with PnL; price history for a token (GeckoTerminal on Base, the engine's own snapshots on Robinhood Chain); re-read the chain (`full`, a rebuild, is operator-only); correct a lot's cost basis (operator-only) | ## Ledger and PnL `~/.agentos/state/trading.sqlite` holds tokens, entries (history), FIFO lots, realized PnL, orders, daily spend, sync cursors, balance cache, the outcome of each wallet/chain read (`chain_reads`) and price snapshots. A release that ships a ledger repair migration flags it: `agentos trade status --json` (and `trading.status`) then carries `ledgerRepair` ("full sync required"); run `agentos trade sync --full` once after upgrading and the flag clears. Cost basis for a deposit is the token's USD price at that block (CoinGecko range; spot price with `cost_basis_source = "approx"` when history is unavailable). A holding's cost can be corrected by hand with `trading.lot.setCost`. Selling consumes the oldest lots first; the difference to proceeds is realized PnL. Gas is booked per entry and shown separately in totals. A bridge is two entries under one order: a `withdraw` on the origin chain when the deposit mines, and a `deposit` on the destination chain when Relay's fill lands. Charts come from GeckoTerminal on Base; on Robinhood Chain the engine serves its own price snapshots (one per held token per sync). ## Related - [Agentic Trading](https://useagentos.dev/docs/core/features/agentic-trading) — the Robinhood MCP and partner skills. - [CLI Reference](https://useagentos.dev/docs/core/cli) — `agentos wallet` / `agentos trade`. - [Approvals and Permissions](https://useagentos.dev/docs/core/approvals-and-permissions). --- # LP cards > Source: https://useagentos.dev/docs/core/lp-cards Artifact type: `application/vnd.agentos.lp+json`. Uniswap V4 liquidity read-outs rendered as cards in the chat transcript. The engine produces the payload (`agentos trade lp …`), the transcript renders it (`frontend/src/views/chat/transcript/lp.ts`). This file is the contract between the two; change it before changing either side. Phase 1 is read-only. Chains: Base (8453) and Robinhood Chain (4663). ## How a card reaches the chat ``` agentos trade lp pool PEPE --chain base --json ``` 1. The CLI calls the gateway (`trading.lp.pool` …), which runs the read in the engine with the engine's own RPC configuration (`trading/chains.py`), not the skill's env variables. 2. With `--json` the result is printed as JSON on stdout (the agent reads that) and — unless `--no-card` is given — also written to `lp-cards/<kind>-<slug>-<utc stamp>.json` under the working directory (the agent's workspace; the 20 newest files are kept), followed by one last stdout line ``` publish_artifact path=<file> mime=application/vnd.agentos.lp+json ``` which the gateway auto-publishes as a turn artifact (see `src/agentos/tools/builtin/artifacts.py`, "Inline artifacts announced on stdout"). No `publish_artifact` tool call is needed. Human (non-`--json`) runs print a table and write no card. 3. The transcript sees an artifact with that MIME type, fetches the body and mounts a card in place of the artifact chip. Errors (pool not found, RPC down, a token address given as `--wallet` → `trading.lp.not_a_wallet`) are `{"error": {"code", "message"}}` on **stderr** with a non-zero exit and **no card**: the agent answers in text. An empty `positions` result **is** a card (the empty state). ## Payload All amounts that come from the chain are decimal **strings** (`raw` is the integer in base units, `human` is already divided by decimals). USD values are JSON numbers or `null` when no price is known — never `0` for "unknown". ### Envelope (every kind) ```jsonc { "version": 1, "kind": "pool" | "ranges" | "position" | "positions", "chain": Chain | null, // null only for kind=positions (each row carries its own) "asOfBlock": 21044901, // block the reads were made against (0 if unknown) "fetchedAt": "2026-09-27T09:30:00Z", "partialScan": false, // true when any scan was truncated; the card shows a badge "warnings": ["string"], // human-readable, may be empty "request": { "kind": "pool", "params": { "target": "0x…", "chainId": 8453 } } // what ↻ refresh re-runs: the read RPC's own params (position: tokenId+chainId; positions: chainIds/wallets/all/budgetSeconds) } ``` ```jsonc Chain = { "id": 8453, "key": "base" | "robinhood", "name": "Base", "explorer": "https://basescan.org" } Token = { "address": "0x…", "symbol": "PEPE", "decimals": 18, "priceUsd": number | null } Amount = { "raw": "1240000000000000000000000", "human": "1240000", "usd": number | null } Range = { "tickLower": -201000, "tickUpper": -180000, "priceLower": number, "priceUpper": number, // quote per 1 base token "mcapLower": number | null, "mcapUpper": number | null } // USD, null when base has no supply/price Pool = { "poolId": "0x…", "hook": "0x…" | null, "tickSpacing": 200, "feePct": "1%", // lpFee already formatted; dynamic-fee pools: "dynamic" "tick": -190000, "liquidity": "raw string", "priceUsd": number | null, // base token, USD "mcapUsd": number | null, "tvlUsd": number | null } Wallet = { "address": "0x…", "label": string | null, "inApp": boolean } Status = "in-range" | "above-range" | "below-range" | "closed" // above-range: current price is above the position's upper bound (all quote); below: all base ``` `base` is the token the user asked about (or `currency0` when a poolId was given), `quote` is the other side. Prices are quote-per-base; USD values come from the engine's price lookup. ### kind = "pool" ```jsonc { ...envelope, "token": Token, "quote": Token, "pool": Pool, "reserves": { "base": Amount, "quote": Amount }, "safety": { "launcher": { "name": "Clanker" | null, "address": "0x…" | null }, "locked": true | false | null, // null = unknown "note": string | null // e.g. "LP owned by launchpad locker" }, "topRanges": [ { ...Range, "liquidity": "raw", "share": 0.42, "owner": "0x…" | null } ] // ≤ 5, by liquidity desc; may be empty } ``` ### kind = "ranges" Liquidity distribution. ```jsonc { ...envelope, "token": Token, "quote": Token, "pool": Pool, "current": { "tick": -190000, "priceUsd": number | null, "mcapUsd": number | null }, "segments": [ { ...Range, "liquidity": "raw", "share": 0.0–1.0, // share of the sum of segment liquidity "base": Amount, "quote": Amount, "active": boolean } // active = contains the current tick ], "scan": { "mode": "ticks" | "logs", "scannedWords": 12, "fullWords": 40, "truncated": false } } ``` Segments are contiguous and sorted by `tickLower` ascending. The chart's x-axis is market cap (`mcapLower`/`mcapUpper`); when those are `null` for every segment the renderer falls back to price. ### kind = "position" ```jsonc { ...envelope, "position": Position } Position = { "chain": Chain, "tokenId": "48213", "owner": Wallet, "token": Token, "quote": Token, "pool": Pool, "range": Range, "status": Status, "liquidity": "raw", "principal": { "base": Amount, "quote": Amount, "usd": number | null }, "fees": { "base": Amount, "quote": Amount, "usd": number | null }, "valueUsd": number | null, // principal.usd + fees.usd, null when either side is unpriced "band": string | null, // the skill's mcap band label, e.g. "$2.1M – $9.8M" "distancePct": number | null // how far the current price is outside the range, in %, null when in range } ``` ### kind = "positions" ```jsonc { ...envelope, "chain": null, "asOfBlocks": { "base": 21044901, "robinhood": 62942097 }, // per scanned chain; asOfBlock is the first "wallets": [ Wallet ], // the wallets that were scanned "chains": [ Chain ], // the chains that were scanned "positions": [ Position ], // already sorted, see below "totals": { "valueUsd": number | null, "feesUsd": number | null, "count": 3, "outOfRange": 1 } } ``` `totals` cover every position found. `valueUsd` sums the priced positions (a warning counts the unpriced ones). `feesUsd` sums the priced fees; when nothing priced remains except zeros it is `null` rather than a misleading `$0.00`, with a warning. `positions` holds at most 50 rows; `totals` always cover every position found, and a warning says how many were left out. Sort order is fixed by the engine and preserved by the renderer: out-of-range first (`above-range`, `below-range`), then in-range, each group by `valueUsd` desc; positions with `valueUsd: null` last within their group and flagged "no price"; `closed` positions are omitted unless `--all`. ## CLI surface ``` agentos trade lp pool <token|poolId> [--chain base|robinhood] [--quote SYMBOL] [--json] [--no-card] agentos trade lp ranges <token|poolId> [--chain base|robinhood] [--json] [--no-card] agentos trade lp position <tokenId> --chain base|robinhood [--json] [--no-card] agentos trade lp positions [--wallet ADDR]… [--chain base|robinhood]… [--budget-seconds N] [--all] [--json] [--no-card] ``` - `<token>` accepts an address or a ticker the engine can resolve on that chain. - `positions` with no `--wallet` scans every wallet in the engine vault on both chains. With `--wallet` only the named addresses (or vault labels) are scanned; an address outside the vault gets `inApp: false`. A `--wallet` that is an ERC-20 contract is refused with `trading.lp.not_a_wallet`. - `--chain` is optional on `pool`/`ranges`: Base is tried first, then Robinhood Chain. On `positions` it is repeatable (no `--chain` = both); a repeat on the other commands is refused with `INVALID_ARGUMENT`. - `positions` stops discovering at `--budget-seconds` (default 25, 5–300) and returns what it has, flagged `partialScan` with a warning naming what was skipped. USD prices are looked up for the listed rows' tokens plus a bounded batch; the rest are valued at their own pool's price. - Every command is read-only and allowed on the agent surface. - A read takes 5–15 s typically, up to 30 s on two chains; run once, in the foreground. ## Rendering rules (frontend) - One renderer, four layouts, keyed by `kind`. - Header: base/quote symbols, chain, fee, and a status pill (`in-range` green, `above-range`/`below-range` amber, `closed` grey). - Footer: `#tokenId · owner (short) · as of block N · <relative time>`, plus copy-address and open-in-explorer actions. Relative time is computed from `fetchedAt` at mount and refreshed once a minute. - `partialScan: true` → a "partial scan" badge next to the chart, never a silent chart. - USD `null` → render "—" with a "no price" hint; never `$0`. - The distribution chart is plain SVG (no new dependency): bars per segment, x-axis in market cap (fallback price), a marker for the current value, hover shows the segment's range, liquidity share and both amounts. - Empty `positions` → an empty-state card: "No Uniswap V4 positions in `<wallets>` on `<chains>`". - The renderer lives in the shared frontend; the desktop restyles it through `desktop/src/renderer/src/views/chat/chat.css` using `data-lp-*` hooks so the desktop card looks distinct from the web one. --- # LP writes > Source: https://useagentos.dev/docs/core/lp-write Phase 1 (`docs/lp-cards.md`) reads Uniswap V4 liquidity. Phase 2 lets the desk act on it — collect fees, remove liquidity, add liquidity — through the **same order pipeline as swaps and sends**: an order row, guardrails, `awaiting_approval`, the operator approves (desk ApprovalCard or `agentos trade approve`), the engine signs with the vault, broadcasts, waits for the receipt and settles into the ledger. Nothing in this phase signs with a private key from the environment; the skill's `lp_write.py` stays as it is for the main agent, the desk never uses it. Chains: Base (8453) and Robinhood Chain (4663). Scope: `collect`, `remove`, `add` (mint a new position or increase an existing one). Not in scope: creating pools, ratchets/auto-rebalancing, swapping to obtain the other side. ## Policy - **Every LP write parks for approval**, whatever the initiator and whatever the amount (like a send from the agent). `guardrails.evaluate_lp_write` returns `needs_approval` for `collect`/`remove`; for `add` it also returns `blocked_daily_cap` when the deposit's USD value would exceed the daily cap (an `add` counts toward `daily_spend`; `collect`/`remove` do not). - Approval TTL = the existing `approval_ttl_seconds`. On approve the plan is **re-validated** against the current pool state: for `add`, the required amounts are recomputed and if they exceed the approved maxima the order fails `trading.price_moved`; for `remove`, the expected amounts are recomputed and if the minimums can no longer be met it fails `trading.price_moved`. Deadline = latest block timestamp + 600 s, set at execution, never at creation. - Slippage default 1 % (`--slippage`), applied as maxima on `add` and minima on `remove`; `collect` has no slippage (zero-liquidity decrease). - The daily cap applies to agent-initiated `add` only (manual adds park but are not capped, as for swaps). A native deposit keeps a gas reserve back. Approvals are re-read live at execution; a top-up of a position with uncollected fees uses INCREASE + CLOSE_CURRENCY (the SETTLE_PAIR form reverts when fees exceed what a side owes). - No auto-swap: if the wallet lacks a side for `add`, the order is refused with `trading.insufficient_balance` naming the missing amount; one-sided ranges (entirely above or below the current price) need only one token and are the cheap way to test. - Wallets: the position's owner must be a vault wallet (`collect`/`remove`); `add` uses the primary wallet unless `--wallet` names another vault wallet. ## Order model New `kind` values in the `orders` table (free TEXT today; add them to `ORDER_KINDS`): `lp_collect`, `lp_remove`, `lp_add`. Columns map as: | column | lp_collect | lp_remove | lp_add | |---|---|---|---| | `token_in` / `token_out` | base / quote of the pool | same | same | | `amount_raw`, `amount_human` | 0 | liquidity removed (raw L) | liquidity added (raw L) | | `value_usd` | fees expected (USD) | principal + fees expected | USD deposited | | `slippage_pct` | null | pct | pct | | `quote_json` | `LpPlan` (below) | `LpPlan` | `LpPlan` | | `recipient` | owner wallet | owner wallet | null | | `note`, `client_order_id`, `initiator`, `session_key`, `batch_id` | as for swap/send | | | ```jsonc LpPlan = { "op": "collect" | "remove" | "add", "chain": Chain, // as in lp-cards.md "tokenId": "48213" | null, // null for a fresh mint until confirmed "increase": boolean, // add: true when --to-position was given "pool": { "poolId", "poolKey": {currency0, currency1, fee, tickSpacing, hooks}, "tick", "sqrtPriceX96", "feePct" }, "token": Token, "quote": Token, // base = the token the user named / currency that is not the known quote "range": Range, // tickLower/Upper + price + mcap bounds (lp-cards.md) "liquidity": "raw L delta", "pct": 100, // remove only "expected": { "base": Amount, "quote": Amount, "usd": number | null }, // what moves "bounds": { "base": "raw", "quote": "raw" }, // add: maxima; remove: minima; collect: 0/0 "fees": { "base": Amount, "quote": Amount, "usd": number | null }, // uncollected fees at plan time (collect/remove) "positionValueUsd": number | null, // remove/collect: the position's value before "approvals": [ { "token": "0x…", "symbol", "step": "erc20->permit2" | "permit2->posm", "amountRaw": "…", "needed": boolean } ], // add only "oneSided": "base" | "quote" | null, // add: range entirely on one side "simulation": { "ok": true, "gasUsed": 210000, "method": "eth_simulateV1" | "eth_call", "revert": null }, "gasUsd": number | null, "slippagePct": 1.0, "planHash": "0x1a2b3c4d", // keccak of the canonical plan, first 4 bytes (as the skill does) "createdAtBlock": 21044901 } ``` Confirmed orders add to the order JSON: `txHash`, `explorerUrl`, `gasUsd`, `received` / `spent` (`{base: Amount, quote: Amount}` from the receipt's transfers), and for a mint the new `tokenId` (from the PositionManager Transfer log). `approval_tx_hash` holds the last approval tx as for swaps; the plan's `approvals[]` get `txHash` entries as they are mined. ## Execution (engine) `service._execute` gains `_execute_lp` (all three ops) and `_confirm` gains `_settle_lp`. 1. **Load** the position (`lp._load_position`) / pool (`lp.pool_states`) through a `ChainEnv` built by `lp._engine_env` (engine RPC, engine prices). 2. **Build the plan** with the skill's encoders, loaded through `lp.unilp()` (add `v4_actions`, `abi_codec`, `simulate` to `_MODULES`): - collect → `build_collect_plan(pool_key, token_id, recipient)` - remove → `pct == 100` → `build_burn_plan(...)` (decrease + burn + take), else `build_decrease_plan(pool_key, token_id, L, a0min, a1min, recipient)`; mins via `with_slippage_down` - add → mint: size `L` from the deposit with `v4_math.get_liquidity_for_amounts`, required amounts with `get_amounts_for_liquidity(round_up=True)`, maxima via `with_slippage_up`; `build_mint_plan(pool_key, lo, hi, L, a0max, a1max, recipient)`; increase: `build_increase_plan(pool_key, token_id, L, a0max, a1max, recipient)`. Native currency0 ⇒ `value = a0max` (the encoder already appends SWEEP). - calldata = `PositionManager.modifyLiquidities(encode_unlock_data(actions, params), deadline)`; the PositionManager address comes from the unilp chain registry. 3. **Simulate** (`unilp.simulate.simulate_call`, then `eth_call` fallback) before parking; a revert refuses the order with `trading.simulation_failed` and the decoded reason when available. 4. **Park** (`_decide_batch`) → `awaiting_approval`, emit `trading.approval.requested` as today. 5. **On approve**: re-validate (policy above), then for `add` run the approvals the plan marked `needed`, each through `_send` like swap approvals (gas recorded with `kind="approval"`): `ERC20.approve(Permit2, exact amount)` when the ERC-20→Permit2 allowance is short, then `Permit2.approve(token, PositionManager, amount160, expiration = now + 30 min)` when the Permit2 allowance or expiration is short. Exact amounts, never unlimited (the engine's rule; the skill's unlimited approve is not copied). Wait for each receipt before the next step. 6. **Send** the `modifyLiquidities` tx through `_send` (simulate, gas × 1.2, fee data, gas-USD ceiling, nonce, hash written before broadcast), then `_watch` → `_confirm`. 7. **Settle** (`_settle_lp`): parse the receipt's transfers for the wallet (`evm.receipt_transfers`), record ledger `entries` with new kinds `lp_collect` (tokens in), `lp_remove` (tokens in), `lp_add` (tokens out), plus `gas`; lots follow the deposit/withdraw convention (tokens received open lots at the settle-time price, tokens deposited consume lots FIFO); an agent-initiated `add` bumps `daily_spend` by its USD value (manual adds are not capped, as for swaps). Emit `trading.order.finished` and `trading.changed {reason:"order"}`. For a mint, read the new `tokenId` from the PositionManager `Transfer(0x0 → wallet)` log. 8. **Failure mapping** as for swaps: `trading.tx_failed` (reverted receipt), `trading.tx_pending`, `trading.gas_too_high`, `trading.insufficient_balance`, `trading.price_moved`, `trading.quote_expired` (approval TTL). ## RPC Agent-callable (they only create parked orders): `trading.lp.collect`, `trading.lp.remove`, `trading.lp.add`. Params mirror the CLI flags in camelCase (`tokenId`, `chainId`, `pct`, `token`, `usd`, `amountBase`, `amountQuote`, `range`, `toPosition`, `wallet`, `slippagePct`, `note`, `clientOrderId`). Response = `{"order": …}` like revoke/approve/wait; the order JSON (`_order_dict`) carries `plan` (= `LpPlan`, plus `wallet`, `positionManager`, `status`, `burn`, `value`, `actions`, `rangeSpec`, `rangeDefaulted`, `warnings`), `provider: "uniswap_v4"`. `trading.lp.add` accepts `token` | `target` | `poolId`, and `token` may be omitted with `toPosition`. Approval/rejection/wait stay on the existing operator-only `trading.orders.approve|reject` and `trading.orders.wait`. Read RPCs from phase 1 additionally echo `"request": {"kind", "params"}` in every card payload so a card can re-run itself (refresh). ## CLI ``` agentos trade lp collect <tokenId> --chain base|robinhood [--note "…"] [--client-id ID] [--wait --wait-seconds N] [--json] agentos trade lp remove <tokenId> --chain base|robinhood [--pct 100] [--slippage 1] [--note …] [--client-id …] [--wait …] [--json] agentos trade lp add <token|poolId> --chain base|robinhood (--usd X | --amount-base A [--amount-quote B]) [--range mcap:2M-10M | pct:20 | full | ticks:LO:HI] # default pct:20 around the current price [--to-position <tokenId>] [--wallet ADDR|label] [--slippage 1] [--note …] [--client-id …] [--wait …] [--json] ``` - Output is the order JSON like `trade swap`/`trade send`: `status` (`awaiting_approval` → `approved` → `submitted` → `confirmed` | `failed` | `rejected` | `expired`), `plan`, and after confirmation `txHash`, `explorerUrl`, `received`/`spent`, `gasUsd`, `tokenId`. - `--wait` blocks until a final status (same loop as swap). - With `--json`, after a **confirmed** order the CLI also publishes the refreshed **position card** (`lp position <tokenId>` payload; for a burn, the wallet's positions card) with the phase-1 marker, so the chat shows the new state without another command. - `--range mcap:LO-HI` accepts `2M`, `2.5m`, `750k`, `1e6`; `pct:N` = ±N % around the current price snapped to tick spacing; `full` = min/max ticks; `ticks:LO:HI` raw ticks (snapped, error if not aligned). - `--usd X`: the deposit is split between the two sides as the range requires at the current price (all on one side when one-sided); the CLI refuses with `trading.insufficient_balance` naming the short side. - Errors: JSON on stderr, exit 2 for input/`trading.invalid`, 1 for gateway/provider; new codes `trading.lp.not_owner` (position not in the vault), `trading.lp.position_closed`, `trading.simulation_failed`, `trading.lp.range_invalid`. ## Desktop and chat - **ApprovalCard** renders the three kinds: title (`Collect fees`, `Remove liquidity`, `Add liquidity`), position (`#id · PEPE / WETH · Base · 1%`), range (lower – upper, mcap when known) with in/out-of-range pill, facts: *you receive* (collect/remove: base + quote + USD), *fees included* (remove), *you deposit* (add: base + quote + USD), *minimum* / *maximum* (slippage bounds), *approvals needed* (add), *gas*, *order*, *expires*; risk stamps: `remove 100%` → "burns the position NFT", `add` one-sided → "one-sided: all `<token>` until price enters the range", `add` with a hook address → "pool has a hook". - **Desk ledger** labels: "Collect fees · #id", "Remove liquidity · #id · 100%", "Add liquidity · PEPE/WETH · $50", outcomes as for send. - **Position card actions** (phase-1 card, `kind=position` and rows of `positions` whose owner is `inApp`): `Collect fees` and `Remove…` (a small choice: 50 % / 100 %). Clicking calls the write RPC directly from the desktop (operator connection) with the card's `tokenId`/`chainId`; the order parks and the ApprovalCard appears in the Book; the button shows "awaiting approval" until `trading.order.finished` for that order, then the card refreshes itself. On the web the buttons are hidden (the web UI is agent-bound and cannot approve). - **Refresh** on every phase-1 card: re-runs `request` through the read RPC and swaps the payload in place; shows "as of block N · just now". - **Desk prompt v14**: teaches the three commands; "From you an LP write **always** parks as `awaiting_approval`, whatever the amount; `--wait` then blocks until the user decides"; reading rules: "collect fee của X" / "claim fees on X" → find the tokenId from `lp positions` when the user names a pair, not an id; "rút hết / remove all / close" → `remove --pct 100`; "rút một nửa / take half out" → `--pct 50`; "add $50 to X between 2M and 10M" → `add X --usd 50 --range mcap:2M-10M`; never pick a range the user did not state without saying which default was used (pct:20). Remove the phase-1 sentence that says writes are not available. ## Tests - Engine: `lp_world` gains a PositionManager that decodes `modifyLiquidities` calldata (actions + params) and applies it to the fake pool (liquidity, fees, NFT transfer/burn); tests for plan building per op, one-sided sizing, mcap/pct/full/ticks ranges, slippage bounds, simulation failure refusal, guardrail parking for agent and operator, daily cap on `add`, approve → approvals sequence (exact amounts, Permit2 expiry) → modifyLiquidities → settle entries/lots/daily_spend, re-validation failures (`price_moved`, `quote_expired`), not-owner / closed position, RPC surface (agent may create, approve is operator-only), CLI flags, `--wait`, the post-confirm card marker. - Frontend/desktop: ApprovalCard per kind (facts, stamps), ledger labels, position-card buttons (hidden on web, states on desktop), refresh (payload swap, "just now"). - Live (tester, real money, dust wallet): on Base, `add` a one-sided ~$0.05 ETH position in a hookless ETH/USDC pool above the current price → approve with `agentos trade approve` → `collect` (0 fees, must still confirm) → `remove --pct 100` → the ETH is back minus gas; every step visible as an ApprovalCard in the desk and as ledger entries. --- # The liquidity book (trading.lp.book) > Source: https://useagentos.dev/docs/core/lp-book Every liquidity position the engine's wallets hold, across protocols, the way a wallet tracker lists DeFi positions. The desktop's **Trade › Liquidity** tab reads it. The engine keeps the book (`src/agentos/trading/lp_book.py`), the readers fill it (`lp.py` for Uniswap V4, `lp_amm.py` for everything else). This file is the contract between the engine and its clients; change it before changing either side. The book itself is read-only. A Uniswap V4 row in the desktop's tab carries **Collect** (when fees are owed) and **Remove** (the whole position, fees included): each calls the LP writes ([LP writes](https://useagentos.dev/docs/core/lp-write)), which park an order for approval, and the tab moves to Approvals where its card is. The other protocols are listed, not managed. ## What is covered | Protocol | Kind | Base (8453) | Robinhood Chain (4663) | |---|---|---|---| | Uniswap V4 | concentrated | yes | yes | | Uniswap V3 | concentrated | yes | yes | | Uniswap V2 | pair | yes | yes | | Aero Slipstream | concentrated, stakeable | yes | yes | | Aero Basic (stable and volatile pools) | pair, stakeable | yes | yes | | Aerodrome Slipstream (three deployments) | concentrated, stakeable | yes | not deployed | | Aerodrome V2 | pair, stakeable | yes | not deployed | Aerodrome became Aero on 2026-10-21. The Aerodrome pools still hold liquidity, but their gauges stopped earning that day, so both generations are read and named apart. A *concentrated* position is an NFT with a price range. A *pair* position is a balance of the pool's own LP token; it has no range and no id. A *staked* position sits in a gauge instead of the wallet: it earns the gauge's reward token (xAERO on Aero, AERO on Aerodrome) and its trading fees go to the gauge. ## How it stays cheap The book is built to make few RPC calls. - **Nothing is read until someone asks.** A call answers at once from the ledger's cache (`lp_positions`, `lp_reads` in `trading.sqlite`). When the cache is older than 60 seconds the engine starts one refresh behind the answer and announces its end as `trading.changed` with `reason: "lp"`. A client that is not showing the book should not call it: a closed tab costs nothing. - **One pass for every wallet.** A refresh batches all wallets of a chain into the same Multicall3 calls, and the two chains run side by side. A wallet with nothing to show costs one multicall per chain. - **Enumerable where possible.** Uniswap V3, Aero and Aerodrome position managers are enumerable, so a wallet's ids are read from the chain (`balanceOf`, `tokenOfOwnerByIndex`) with no log scan. The ids are cached with the wallet's count and newest id; while both are unchanged they are not listed again, and emptied NFTs are not re-read. - **Pairs come from the ledger.** The candidates for an LP token are the ERC-20s the wallet sync already knows the wallet holds. Each is checked once: it must name a known factory, and that factory must name it back for its two tokens. The verdict is remembered either way. - **Gauges are walked rarely.** A staked position can only be found by asking gauges. Every gauge is asked on a wallet's first read, after the wallet's balances moved (at most every 5 minutes), on an explicit refresh, and every 6 hours. In between, only the gauges a wallet was last seen in are asked. Aerodrome's gauges are frozen, so they are walked on the first read and on an explicit refresh only. - **Uniswap V4 starts warm.** V4 has no enumerable index, so finding a position needs an indexer or a log search. The ids found are remembered; while they account for the wallet's NFT balance the search is skipped. A search that came up short and found nothing new is not repeated for 15 minutes unless a refresh is asked for; one that found something goes on at the next refresh. The search asks the configured RPC endpoint (`trading.rpc_urls`) for the whole Transfer history first, then the chain's public node. A node that serves neither is walked back in windows: where it serves a one-wallet filter over a wider span than a many-wallet one (Robinhood Chain's public node: 10,000,000 blocks against 100,000), one wallet at a time. That node throttles the walk, so the first read of many wallets there fills in over a few refreshes. - **The positions card shares those ids.** `trading.lp.positions` (`agentos trade lp positions`, what an agent runs) reads the chain live, but it verifies the remembered ids first and searches only for a wallet whose NFT balance they do not cover. What it finds for the vault's wallets is remembered for the book in turn. What never changes (which token is a pair, where a pool is, the gauge directory, cached id lists) is kept per chain under the state directory as `lp/amm-CHAINID.json`. Deleting it is safe: the next refresh rebuilds it. ## Request ```jsonc { "wallet": "0x… | label", // optional: one vault wallet (default: all of them) "chainId": 8453, // optional: one chain (default: both) "refresh": false // optional: read the chain now (honoured every ~10 s) } ``` Allowed for an agent (it is a read). Only vault wallets are covered; to read any address, use `trading.lp.positions` (Uniswap V4 only). ## Answer USD values are JSON numbers, or `null` when no price is known: never `0` for "unknown". Amounts from the chain are decimal strings. ```jsonc { "version": 1, "kind": "book", "ready": true, // every wallet/chain in scope has been read at least once "refreshing": false, // a refresh is running; trading.changed announces its end "readAt": 1794981234.5, // unix seconds of the oldest read behind this answer; null until ready "partialScan": false, // something could not be read; see warnings "warnings": ["string"], "wallets": [ { "address": "0x…", "label": "Main" } ], "chains": [ { "id": 8453, "key": "base", "name": "Base", "explorer": "https://basescan.org", "readAt": 1794981234.5, "asOfBlock": 58954977 } ], "protocols": [ { "key": "uniswap_v3", "name": "Uniswap V3", "count": 2, "valueUsd": 240.9 } ], "positions": [ BookPosition ], // at most 200 rows; sorted, see below "totals": { "valueUsd": 3007.34, "feesUsd": 37.35, "rewardsUsd": 0.23, "count": 8, "outOfRange": 3, "unpriced": 0 } } ``` `totals` cover every position, listed or not. A total no row could price is `null`. ### BookPosition A superset of the `Position` of [LP cards](https://useagentos.dev/docs/core/lp-cards); the shared fields mean the same. ```jsonc { "id": "8453:uniswap_v3:0x03a5…-5000150:0xowner", // stable across refreshes "protocol": { "key": "uniswap_v3", "name": "Uniswap V3", "kind": "concentrated" | "pair" }, "chain": Chain, "tokenId": "5000150" | null, // null for a pair "manager": "0x…" | null, // the NFT manager (not set for V4 or a pair) "owner": Wallet, // the wallet, also when the position is staked "token": Token, "quote": Token, "pool": { "poolId": "0x…", // the pool address (V4: the poolId) "feePct": "0.05%" | "dynamic" | "stable" | "volatile" | null, "tickSpacing": 10 | null, "tick": -200000 | null, "liquidity": "raw", "priceUsd": number | null, "mcapUsd": number | null, "tvlUsd": number | null }, "range": Range | null, // null for a pair "status": "in-range" | "above-range" | "below-range" | "full-range" | "closed", "liquidity": "raw", // a pair: the LP-token balance "principal": { "base": Amount, "quote": Amount, "usd": number | null }, "fees": { "base": Amount, "quote": Amount, "usd": number | null } | null, "staked": false, "gauge": "0x…" | null, "rewards": { "token": Token, "amount": Amount } | null, "share": 0.25 | null, // a pair: share of the pool, 0-1 "valueUsd": number | null, // principal + fees + rewards, where priced "band": string | null, "distancePct": number | null } ``` - `status` is `full-range` for every pair. - `fees` is `null` where there is nothing to collect apart from the position (Uniswap V2 fees compound into the reserves; a staked pair's fees belong to the gauge). For a staked concentrated position it holds only what was already owed when it was staked. - `rewards` is what the gauge would pay now. xAERO has no market of its own and redeems one-for-one for AERO, so on Base it is valued at AERO's price; where no price is known `amount.usd` is `null`. - A token no source prices is valued at its pool's own ratio against the priced side. ### Order Out of range first (`above-range`, `below-range`), then `in-range` and `full-range`, then `closed`; each group by `valueUsd` descending, unpriced rows last. Closed positions with nothing owed are left out. ## Events `trading.changed` with `reason: "lp"` after every refresh. A client showing the book re-reads it then; polling is only a backstop (the desktop asks every 30 seconds while the tab is open, which is also what keeps the cache warm). --- # Bridge > Source: https://useagentos.dev/docs/core/bridge The trading engine moves ETH and the USD stable between its two chains through [Relay](https://docs.relay.link) — a public, keyless REST API that prices a cross-chain transfer and answers with the unsigned origin-chain transactions that fund it. Relay holds no key and never broadcasts: funds move only when the vault signs the deposit. A bridge runs through the **same order pipeline as swaps and sends**: an order row, guardrails, `awaiting_approval`, the operator approves (desk ApprovalCard or `agentos trade approve`), the engine signs with the vault, broadcasts, waits for the receipt, follows the fill on the other chain and settles both legs into the ledger. Routes (`agentos.trading.bridge.CHAIN_BRIDGE_TOKENS`): a token bridges to the token on the other chain with the same asset, so the table is per-chain, not per-pair. | Direction | Asset | Origin token | Destination token | | --- | --- | --- | --- | | Base → Robinhood Chain | ETH | ETH | ETH | | Base → Robinhood Chain | USD | USDC `0x8335…2913` | USDG `0x5fc5…d168` | | Robinhood Chain → Base | ETH | ETH | ETH | | Robinhood Chain → Base | USD | USDG `0x5fc5…d168` | USDC `0x8335…2913` | Anything else — another token, another chain, the same chain twice — is `trading.bridge.unsupported_route`, with `details.supportedRoutes`. ## Policy - **An agent's bridge always parks for approval**, whatever the amount (`guardrails.evaluate_bridge` = `evaluate_transfer`: a bridge leaves the chain for good, like a send). It counts toward the agent's daily cap (origin notional in USD, in flight and once confirmed); over the cap, or with the cap at 0, it is `rejected`; unpriced, it waits rather than slipping past the cap. The notional comes from the engine's own price feed: the origin chain's price of the asset, else the destination chain's price of the same asset. Relay's own `amountUsd` never sizes the order. A manual bridge runs at once. - **Re-quote before signing.** The quote the user approved is a promise about the price only. At execution Relay is asked again; a fill below the approved floor (`BRIDGE_TOLERANCE_PCT`, 1 %) sends an agent's order back to `awaiting_approval` with the new numbers, and fails a manual one with `trading.price_moved`. - **What is signed is pinned, not read from the response.** The deposit must go `to` a Relay solver in `RELAY_SOLVERS` and carry calldata (that is what ties it to the request — a bare transfer to the solver would be lost); a native deposit carries exactly the order's value, an ERC-20 one none; the approval, when one is needed, is on the bridged token, to that same solver, and is re-encoded by the engine for exactly the order's amount (`_check_approval_tx`, then `_check_bridge_tx`). A `signature` step, an unknown step, two deposits — refused unsigned (`trading.bridge.unsupported_step`, `trading.tx_failed`). - **Gas is the desk's decision**, as for swaps: Relay's `gas` is taken only under the chain's cap, fees come from the node. ## Order model The row is the **origin side** of the transfer, shaped like a send: `chain_id` = origin, `token_in` = `token_out` = the origin token, `recipient` = the Relay solver, `provider = "relay"`, `kind = "bridge"`, `expected_out_raw` / `min_out_raw` in destination units (the same decimals on every route), `tx_hash` = the deposit. The destination side lives in `quote_json` (the *BridgePlan*): ```json { "kind": "bridge", "provider": "relay", "route": {"asset": "USD", "originChainId": 8453, "destinationChainId": 4663, "tokenIn": {...}, "tokenOut": {...}}, "amountRaw": "25000000", "quote": {"requestId": "0x…", "solver": "0x4cd0…bc31", "expectedOutRaw": "…", "rate": 0.997, "feesUsd": 0.03, "fees": {"gasUsd": …, "relayerUsd": …, "appUsd": …}, "timeEstimateSeconds": 1, "fetchedAt": …, "steps": [...]}, "approved": {"requestId": "0x…", "expectedOutRaw": "…", "minOutRaw": "…"}, "execution": {"requestId": "0x…", "approvalTxHash": null, "depositTxHash": "0x…", "depositBookedAt": …, "depositBlock": …, "depositGasWei": "…"}, "fill": {"status": "waiting|pending|success|failure|refund|unknown", "destinationTxHash": "0x…", "checkedAt": …, "attempts": 3, "receivedRaw": "…", "bookedAt": …, "lastError": null} } ``` The order JSON (`trading.order`, `trade order --json`) shows `tokenOut` as the **destination** token, `expectedOut` / `minOut` / `receivedOut` in its units, `recipientLabel: "Relay solver"`, `provider: "relay"`, and a `bridge` block: `originChainId`, `destinationChainId`, `destinationChain`, `asset`, `requestId`, `fillStatus`, `feesUsd`, `fees`, `rate`, `timeEstimateSeconds`, `approvalTxHash`, `depositTxHash`, `depositExplorerUrl`, `destinationTxHash`, `destinationExplorerUrl`, `checkedAt`. ## Lifecycle ``` quoted ──(manual)─────────────────────────────► approved ─┐ quoted ──(agent)──────────────────────────────► awaiting_approval ──approve──► approved ─┤ quoted ──(agent, over the cap)────────────────► rejected │ ▼ approved ── re-quote below the floor ────────► (agent) awaiting_approval · (manual) failed approved ── approve tx (if the allowance is short) → deposit signed ──► submitted submitted ── deposit reverted ───────────────► failed (gas entry) submitted ── deposit mined: `withdraw` booked on the origin; fill.status = waiting submitted ── Relay success: `deposit` booked on the destination ──► confirmed (spend counted) submitted ── Relay failure / refund ─────────► failed submitted ── no receipt or no fill after 6 h ─► failed ``` `confirmed` means the funds are on the destination chain. The waits (`trade order --wait`, `trading.orders.wait`), the in-flight cap and `recover_submitted` all work unchanged: the order simply stays `submitted` longer. **Fill tracking.** After the deposit is booked, a tracker polls `/intents/status/v3` with a short backoff (2 → 30 s) for up to 30 minutes, then leaves the order `submitted` with its reason; every housekeeping `tick` re-enters the settlement through `recover_submitted`, which starts a fresh tracker (the deposit half is skipped: `execution.depositBookedAt` is set), until 6 h after creation, when the order fails naming the request id. A gateway restart resumes the same way. `trading.bridge.status` reads Relay at most every 2 s per order; the tracker and a status call never book the arrival twice (one lock per order, and the arrival entry is keyed by the fill transaction and log index, so a sweep that saw the transfer first already booked it). **Ledger.** The origin leg is a `withdraw` entry under the order (FIFO lots consumed, gas on it); the arrival is a `deposit` entry on the destination under the same order (a new lot at the fill-time price). The sync treats the destination chain as busy while a bridge is `submitted`, so the arriving ETH is not booked twice as an anonymous deposit; a rebuild replays the origin leg like a send's. A refund books the withdrawal and, when the funds come back, an external deposit: net balance right, small realized-PnL noise. ## Surface - CLI: - `agentos trade bridge quote --chain base --to-chain robinhood --token ETH (--amount 0.01 | --usd 20 | --pct 50) [--wallet A] --json` - `agentos trade bridge create … [--note …] [--client-id …] [--wait] [--wait-seconds 1..900] [--as-agent] --json` → `{"order": …}` - `agentos trade bridge status ORDER_ID|REQUEST_ID --json` → `{"order": …, "bridge": …}` - `agentos trade orders --kind bridge` - RPC: `trading.bridge.quote`, `trading.bridge.create` (`chainId|chain`, `toChainId|toChain`, `token`, exactly one of `amount` / `amountUsd` / `amountPct`, `wallet`, `note`, `clientOrderId`, `wait`), `trading.bridge.status` (`orderId` or `requestId`), `trading.bridge.routes`. - Desktop: the full desk's ticket switches **Swap | Bridge**, and the BOOK beside the chat has a **Bridge** tab. Both are the same form over `trading.bridge.quote` and `trading.bridge.create` (`initiator: "manual"`, so it runs at once after the confirm sheet, behind Touch ID when on); the order is then followed on Orders like any other bridge. - Config: `trading.relay_base_url` (https, or http on loopback). - Errors: `trading.bridge.unsupported_route` (exit 2, `details.supportedRoutes`), `trading.bridge.provider` (Relay unreachable or refusing; exit 1), `trading.bridge.unsupported_step`, `trading.bridge.not_found`, plus the shared `trading.insufficient_balance`, `trading.unpriced`, `trading.price_moved`, `trading.tx_failed`, `wallet.locked`. --- # DCA mandates > Source: https://useagentos.dev/docs/core/dca Artifact type: `application/vnd.agentos.dca+json`. A **DCA mandate** is a recurring buy the trading engine owns and runs by itself: *buy $10 of ETH with USDC on Base every day until $300 is spent*. The user approves the mandate once; every buy after that is an ordinary swap order through the existing pipeline (guardrails, approval threshold, daily cap, vault signing, ledger). No LLM turn is spent on a buy, no prompt is asked to count a budget: the cap, the schedule and the stop rules are rows in the ledger and are enforced there. The mandate is shown in the chat as a **card** (same mechanism as the LP cards in `docs/lp-cards.md`): the agent runs `agentos trade dca … --json`, the CLI publishes the payload as an inline artifact, the transcript renders it. On the desktop the card carries the controls (approve, pause, resume, buy now, stop); on the web console the card is read-only (the web UI is agent-bound and cannot approve anything). This file is the contract between the engine, the gateway, the CLI, the shared renderer and the desktop. Change it before changing any of them. Chains: Base (8453) and Robinhood Chain (4663). Not in scope: selling schedules, ladders/grids, cross-chain, more than one token per mandate. ## Why an engine object Before this, a "DCA" on the desk was a cron job whose prompt asked the agent to swap once per run and to sum the notes of previous orders to stay under a budget (`desk-logic.ts` `composeMissionPrompt`). That has three problems: the budget is a request, not a limit; the state (spent, runs, next buy) is not readable anywhere without re-deriving it from prose; and every buy costs an agent turn. A mandate fixes all three. Old cron-based DCA missions keep working unchanged; the desk's DCA presets now create mandates. ## Lifecycle ``` create ──(operator)──────────────► active ──► completed (cap reached / runs reached) └────(agent)──► awaiting_approval ─┤ ├─► stopped (user) │ │ └─► paused ⇄ active (user, or auto-pause after 3 bad runs) ├─► rejected │ └─► expired │ (24 h without a decision) ``` - **Who may create.** Any connection. An **agent-bound** connection (see `gateway/agent_surface.py`) always gets `awaiting_approval`; the operator (desktop, CLI without agent markers) gets `active` at once. The `initiator` param is never trusted, exactly as for orders. - **Approval** of a pending mandate is operator-only (`trading.dca.approve`, desktop card button, `agentos trade dca approve`). A pending mandate expires **24 h** after creation (`expires_at`), not after the order TTL: a proposal should survive the user being away. - **Runs.** A run is due when `now >= next_run_at`. The engine's housekeeping pass (`TradingService.housekeep()`, every `sync_interval_seconds`, 60 s, from the moment the gateway starts) calls `dca.run_due()`; the wallet sync runs beside it, never ahead of it. First run: at activation when `startNow` is true (default), otherwise one interval after activation. `next_run_at` is drift-free: `anchor_at + k * every_seconds` for the smallest `k` that is in the future. If the gateway was down and more than one interval passed, **one** run fires and the schedule skips forward; never a burst. - **A run** = one swap order with `initiator="agent"` (so the guardrails apply: a buy at or under `approval_threshold_usd` executes on its own, a larger one parks for approval; the daily cap counts it), `session_key` = the mandate's, `note` = `"<name> · buy <n>/<max|∞>"`, `mandate_id` set, `amount_usd = min(usd_per_run, remaining)`. Before placing the order the engine advances `next_run_at` (compare-and-set on the previous value) and inserts the run row, so a crash mid-run cannot buy twice. - **Run outcomes** (`mandate_runs.status`): `pending` (order placed, not yet settled — buys run with `wait=False`), `filled` (order confirmed), `parked` (awaiting approval; becomes `filled` / `expired` / `rejected` when the order settles), `skipped` (with `reasonCode`: `max_price`, `daily_cap`, `insufficient_balance`, `cap_reached`), `failed` (quote or execution failed, `reasonCode` = the error code), `expired`, `rejected`. Only `filled` runs count toward `runs.done`; skipped and failed runs are counted separately and do not shift the cap. A `pending` run whose order never appeared is written off as `failed trading.interrupted` after 1 h; each tick re-checks unsettled runs against their orders (restart safety). The balance is checked before an order is placed, so an `insufficient_balance` skip leaves no failed order in the Book. With a max price set and **no price known**, the run is skipped as `max_price` (never buy blind) and does not count toward auto-pause. - **Cap accounting.** `spentUsd` = Σ `value_usd` of **confirmed** orders with this `mandate_id`; `reservedUsd` = Σ of open ones (awaiting / approved / submitted). A run is sized from `capUsd − spent − reserved`. When that remainder is under **min($0.50, half a buy)** (rounded down to the cent, never under $0.01), or `runs.done == runs.max`, the mandate is `completed` (`statusReason` = `"cap reached"` / `"runs reached"`) and emits `trading.dca.changed`. `spent_usd` is also cached on the mandate row (updated at settle) so the list is one query, and it is a floor: confirmed spend never reads lower than it, so a cap does not reopen because order rows went missing. - **Max price guard.** With `max_price_usd` set, a run where the engine's spot price of `token` is above it is `skipped` (`max_price`, the price seen goes into `reason` detail). No buy, schedule advances normally. - **Auto-pause.** Three consecutive runs that are `skipped` (`insufficient_balance` / `daily_cap`) or `failed` pause the mandate with `statusReason` = e.g. `"paused after 3 runs: insufficient USDC"`. A `max_price` skip does **not** count (waiting for a price is the point). Resume is manual. - **Buy now** (`trading.dca.run`, operator-only) fires a run immediately on an `active` or `paused` mandate; it counts like any run and does **not** move the next scheduled buy. - **Stop** also rejects the mandate's buys still waiting for approval. **Resume** resets the bad-run streak. A user pause sets `statusReason` `"user"`; an expired proposal `"no decision within 24 h"`. A mandate is never completed while one of its buys is still open; it completes when that buy settles. The order note counts **buys**, not attempts (`buy 3/30` even after skipped runs). - **Update** (operator-only): `usdPerRun`, `capUsd`, `runsMax`, `everySeconds`, `maxPriceUsd`, `name` (`null` = not given; `runsMax: 0` removes the run limit, `maxPriceUsd: 0` removes the price guard; a cap below `usdPerRun` is allowed). Lowering the cap below what is already spent completes the mandate. Changing `everySeconds` re-anchors the schedule at now (next buy = now + every). - **Stop** is terminal; **pause/resume** flip `active`/`paused`. Resuming after a long pause does not run the missed buys: `next_run_at` is recomputed from the anchor, so at most one buy fires when it is due. - Nothing is ever deleted. `list` shows live mandates (`awaiting_approval`, `active`, `paused`) unless `--all`. - **Removing the wallet** (`wallet.remove`) stops every mandate bound to it (`statusReason` `"wallet removed"`) and rejects its buys waiting for approval. Importing the same key again revives none of them. - **Sealed terms.** Approving a mandate (or creating one as the operator) seals its terms (wallet, chain, tokens, `usdPerRun`, `capUsd`, `runsMax`, `everySeconds`, `maxPriceUsd`, slippage) with the vault key, so it needs an unlocked vault; `update` re-seals. Every run checks the seal first: a mandate whose row was changed outside the engine is `stopped` (`"integrity check failed (…)"`) without buying, and the gateway broadcasts `trading.integrity.alert`. While you have locked the vault (`agentos wallet lock`) due runs wait for the unlock instead of failing. ## Ledger (schema v7) ```sql CREATE TABLE IF NOT EXISTS mandates ( mandate_id TEXT PRIMARY KEY, -- "dca_" + 8 hex kind TEXT NOT NULL DEFAULT 'dca', name TEXT NOT NULL, status TEXT NOT NULL, -- awaiting_approval|active|paused|completed|stopped|rejected|expired status_reason TEXT, chain_id INTEGER NOT NULL, wallet TEXT NOT NULL, token_out TEXT NOT NULL, -- what is bought (address) token_in TEXT NOT NULL, -- what is spent (address), default the chain's USDC usd_per_run REAL NOT NULL, cap_usd REAL NOT NULL, runs_max INTEGER, every_seconds INTEGER NOT NULL, max_price_usd REAL, slippage_pct REAL, start_now INTEGER NOT NULL DEFAULT 1, anchor_at REAL, -- epoch s; set at activation next_run_at REAL, last_run_at REAL, spent_usd REAL NOT NULL DEFAULT 0, -- cache of Σ confirmed value_usd runs_done INTEGER NOT NULL DEFAULT 0, runs_skipped INTEGER NOT NULL DEFAULT 0, runs_failed INTEGER NOT NULL DEFAULT 0, bad_streak INTEGER NOT NULL DEFAULT 0, initiator TEXT NOT NULL, -- 'agent' | 'manual' (who created it) session_key TEXT, created_at REAL NOT NULL, updated_at REAL NOT NULL, approved_at REAL, expires_at REAL ); CREATE INDEX IF NOT EXISTS idx_mandates_status ON mandates(status, created_at DESC); CREATE TABLE IF NOT EXISTS mandate_runs ( run_id INTEGER PRIMARY KEY AUTOINCREMENT, mandate_id TEXT NOT NULL, n INTEGER NOT NULL, -- 1-based, counts every attempt at REAL NOT NULL, status TEXT NOT NULL, -- filled|parked|skipped|failed|expired|rejected reason TEXT, usd REAL, -- what the run tried to spend price_usd REAL, -- spot price of token_out seen at the run order_id TEXT, manual INTEGER NOT NULL DEFAULT 0 -- 1 = "buy now" ); CREATE INDEX IF NOT EXISTS idx_mandate_runs ON mandate_runs(mandate_id, n DESC); ALTER TABLE orders ADD COLUMN mandate_id TEXT; -- migration step, v6 → v7 CREATE INDEX IF NOT EXISTS idx_orders_mandate ON orders(mandate_id) WHERE mandate_id IS NOT NULL; ``` Times are epoch seconds as floats like `orders.created_at`; the JSON payload carries ISO-8601 UTC strings. `ORDER_KINDS` is unchanged: a mandate buy is `kind='swap'`. `_order_dict` gains `"mandateId": str | null` for every order. Engine module: `src/agentos/trading/dca.py` — pure-ish planning (`next_run_at`, sizing, guards, payload building) plus the runner entry points the service calls. The service exposes: ```python async def dca_create(self, *, chain, token, quote, usd_per_run, cap_usd, runs_max, every_seconds, max_price_usd, wallet, slippage_pct, name, start_now, initiator, session_key) -> dict # mandate payload (kind="mandate") async def dca_get(self, mandate_id) -> dict # payload async def dca_list(self, *, all=False, wallet=None) -> dict # payload (kind="mandates") async def dca_approve(self, mandate_id) -> dict async def dca_reject(self, mandate_id, reason=None) -> dict async def dca_pause(self, mandate_id) -> dict async def dca_resume(self, mandate_id) -> dict async def dca_stop(self, mandate_id, reason=None) -> dict async def dca_update(self, mandate_id, **fields) -> dict async def dca_run_now(self, mandate_id, *, wait=False) -> dict # payload + "run": Run async def dca_run_due(self) -> None # called from tick() ``` Errors are `TradingError` codes: `trading.dca.not_found`, `trading.dca.bad_state` (e.g. approve on an active one, resume on a stopped one), `trading.dca.invalid` (usd ≤ 0 or under $0.01, cap < usd, every < 60 s, unknown quote on Robinhood Chain without `--quote`), `trading.operator_required` (from the RPC layer), `trading.integrity` (the mandate failed its seal), plus the usual `trading.disabled`, `wallet.locked`, `trading.unsupported_chain`, `trading.token_not_found` (unknown symbol; an ambiguous one stays `trading.invalid`). At create, `slippagePct` may not exceed the agent slippage ceiling and the wallet may not be `all`. Events: every state change emits `trading.changed {reason: "dca", mandateId}` (so the desktop's `['trading']` query prefix refreshes) and `trading.dca.changed {mandate}` (full payload). Each run emits `trading.dca.run {mandateId, run}` twice — when placed (`pending`) and when settled; the order itself emits the normal `trading.approval.requested` / `trading.order.finished`. When an order with `mandate_id` settles (confirmed / failed / expired / rejected) the engine updates the run row and the mandate cache in the same place it settles the order. ## Payload ```jsonc Envelope = { "version": 1, "kind": "mandate" | "mandates", "fetchedAt": "2026-09-28T09:30:00Z", "warnings": ["string"], "request": { "kind": "get" | "list", "params": {…} } // what ↻ refresh re-runs: trading.dca.<kind> } // kind = "mandate" { ...Envelope, "mandate": Mandate, "run": Run | undefined } // "run" only in the response of trading.dca.run // kind = "mandates" { ...Envelope, "mandates": [ Mandate ], // live first, then by createdAt desc "totals": { "count": 3, "active": 2, "spentUsd": 240.5, "capUsd": 900, "acquiredUsd": 251.1 | null } } Mandate = { "id": "dca_1a2b3c4d", "name": "DCA ETH", "status": "awaiting_approval" | "active" | "paused" | "completed" | "stopped" | "rejected" | "expired", "statusReason": string | null, // "cap reached", "runs reached", "paused after 3 runs: insufficient USDC", "user: …" "chain": Chain, "wallet": Wallet, // as in lp-cards.md "token": Token, "quote": Token, // token = bought, quote = spent (priceUsd on both) "schedule": { "everySeconds": 86400, "label": "every day", // "every 6 hours", "every 30 minutes", "every week" "startNow": true, "anchorAt": iso | null, "nextRunAt": iso | null, "lastRunAt": iso | null }, "budget": { "usdPerRun": 10, "capUsd": 300, "spentUsd": 120.4, "reservedUsd": 10, "remainingUsd": 169.6, "progress": 0.40 }, // progress = spent / cap, 0–1 "runs": { "done": 12, "max": 30 | null, "skipped": 1, "failed": 0, "attempts": 13 }, "guards": { "maxPriceUsd": 3000 | null, "approvalThresholdUsd": 100, "dailyCapUsd": 1000, "slippagePct": 1.0, "buysNeedApproval": false }, // true when usdPerRun > threshold "acquired": { "amount": Amount, // Σ received_out of confirmed buys; usd = at current price "avgPriceUsd": number | null, // spentUsd / amount.human "currentPriceUsd": number | null, "vsAvgPct": number | null, // (current − avg) / avg × 100 "unrealizedUsd": number | null, // amount.usd − spentUsd "gasUsd": number }, // Σ gas of the mandate's orders "history": [ Run ], // newest first, ≤ 50 "initiator": "agent" | "manual", "sessionKey": string | null, "createdAt": iso, "updatedAt": iso, "approvedAt": iso | null, "expiresAt": iso | null } Run = { "n": 12, "at": iso, "manual": false, "status": "pending" | "filled" | "parked" | "skipped" | "failed" | "expired" | "rejected", "reasonCode": string | null, // machine: max_price | daily_cap | insufficient_balance | cap_reached | trading.<code> "reason": string | null, // skipped/failed detail, human-readable ("ETH at $3,120 above $3,000") "usd": number | null, // spent (filled) or attempted "amount": Amount | null, // received (filled only) "priceUsd": number | null, // effective buy price for filled, spot seen otherwise "orderId": string | null, "txHash": string | null, "explorerUrl": string | null, "gasUsd": number | null } ``` `Chain`, `Token`, `Amount`, `Wallet` are the LP card types. USD `null` means unknown, never `0`. `warnings` carry things like *"each buy of $150 is above the $100 approval threshold and will wait for you"*, *"USDC balance covers 4 more buys"* (when known), *"price unknown: max-price guard cannot be checked"*. ## RPC Agent-callable (create only proposes; reads are harmless): | method | params | returns | |---|---|---| | `trading.dca.create` | `chainId`/`chain`, `token`, `quote?`, `usdPerRun`, `capUsd?`, `runsMax?` (at least one of cap/runs; cap defaults to `usdPerRun × runsMax`), `everySeconds`, `maxPriceUsd?`, `wallet?`, `slippagePct?`, `name?`, `startNow?` (default true), `sessionKey?` (operator only; agents are bound) | `mandate` payload | | `trading.dca.get` | `mandateId` | `mandate` payload | | `trading.dca.list` | `all?`, `wallet?` | `mandates` payload | Operator-only (`@_operator_only`; an agent gets `trading.operator_required`): | method | params | returns | |---|---|---| | `trading.dca.approve` | `mandateId` | `mandate` payload (now `active`; the first buy fires on the next tick when `startNow`) | | `trading.dca.reject` | `mandateId`, `reason?` | payload | | `trading.dca.pause` / `resume` / `stop` | `mandateId`, `reason?` (stop) | payload | | `trading.dca.run` | `mandateId`, `wait?` | payload + `run` | | `trading.dca.update` | `mandateId` + any of `usdPerRun`, `capUsd`, `runsMax`, `everySeconds`, `maxPriceUsd`, `name` | payload | Every response is a full card payload with `request` echoed so the renderer can swap it in place. `note` sanitising, `_chain`, `_number`, `_str` helpers as for the other trading RPCs. Validation errors are `trading.dca.invalid` with a message naming the field. ## CLI ``` agentos trade dca create <token> --usd 10 --every 1d (--cap 300 | --runs 30 | both) [--max-price 3000] [--quote USDC] [--chain base|robinhood] [--wallet ADDR|label] [--slippage 1] [--name "DCA ETH"] [--start now|next] [--json] [--no-card] agentos trade dca list [--all] [--wallet …] [--json] [--no-card] agentos trade dca show <id> [--json] [--no-card] agentos trade dca approve <id> [--json] [--no-card] agentos trade dca reject <id> [--reason "…"] [--json] [--no-card] agentos trade dca pause | resume <id> [--json] [--no-card] agentos trade dca stop <id> [--reason "…"] [--json] [--no-card] agentos trade dca run <id> [--wait --wait-seconds N] [--json] [--no-card] agentos trade dca update <id> [--usd X] [--cap X] [--runs N] [--every 12h] [--max-price X] [--name …] [--json] [--no-card] ``` - `--every` accepts `30m`, `2h`, `1d`, `1w` or a plain number of seconds; minimum **60 s** (short intervals exist for testing; the desk offers hourly and up). - `<token>` is an address or a ticker the engine resolves on that chain. `--quote` defaults to the chain's USDC; on Robinhood Chain (no canonical USDC) it is required. - `--json` prints the payload and, unless `--no-card`, writes `dca-cards/<kind>-<slug>-<utc stamp>.json` (20 newest kept, same pruning as `lp-cards/`) and prints the last line `publish_artifact path=<file> mime=application/vnd.agentos.dca+json`. The gateway auto-publishes any `application/vnd.agentos.*` marker, no gateway change needed. - Human output (no `--json`): a Rich panel per mandate (name, status, schedule, progress bar `spent / cap`, next buy, avg vs current price) and a table for `list`. - Exit codes as `trade lp`: 2 for input / `trading.dca.invalid` / `trading.dca.bad_state` / `trading.dca.not_found` / `trading.invalid` / `trading.token_not_found`, 1 for gateway errors (including `trading.operator_required`). Errors are JSON on stderr under `--json`, never a card. - `run --wait` waits for the fired order like `swap --wait`. - From an agent shell, `create` always answers `status: "awaiting_approval"`; the agent tells the user the card has an **Approve & start** button and never approves itself (`trading.operator_required` otherwise). ## Rendering Shared renderer: `frontend/src/views/chat/transcript/dca.ts`. Same skeleton as `lp.ts`: `isDcaArtifact`, `normalizeDcaPayload`, `createDcaMounter({ fetchPayload, call, actions })`, registered in `artifacts.ts` (`artifactCategory → 'dca'`, placeholder `.msg-artifact-dca[data-dca-src]`) and mounted from `useTranscript.ts` next to `lpMounter` (option `dcaActions`, same shape as `lpActions`: `{ call, onOrder }`). `trading.order.finished` and `trading.dca.changed` refresh mounted cards of the affected mandate. ### `kind = "mandate"` — the card Root `article.dca-card[data-dca-kind=mandate][data-dca-status=…][data-dca-chain=…][data-dca-layout=wide|narrow]`. 1. **Header** `.dca-card__head`: `ETH ← USDC` (bought ← spent), chain pill, status pill `.dca-pill[data-status]` (`awaiting_approval` amber with a soft pulse, `active` green, `paused` grey, `completed` blue, `stopped` / `rejected` / `expired` muted). Name on the right, small. 2. **Hero** `.dca-card__hero`: `$10 every day` large; under it the live line `.dca-card__next[data-dca-next-at]`: `next buy in 3 h 12 m` (ticks every second while under an hour, every minute above; `first buy on approval` when pending; `buy now due` when overdue; `paused` etc.). 3. **Progress** `.dca-card__progress`: a bar `spent / cap` with the reserved slice hatched, labels `$120.40 of $300 · 40 %` and `12 of 30 buys` (or `12 buys`). 4. **Stats** `.dca-card__stats` (2×2, 4×1 when wide): *acquired* `0.0421 ETH · $131.20`; *avg buy* `$2,860` with `vs now ▲ 4.2 %` / `▼ 1.1 %` tinted; *unrealised* `+$10.80` signed and tinted; *gas* `$0.31`. `null` renders `—` with a "no price" hint. 5. **Buys chart** `.dca-chart` — plain SVG, no dependency: one column per attempt in time order (≤ 50): filled runs as bars whose height is the buy price, a dashed horizontal line at the average price, a dotted line at the current price with a right-edge label, skipped runs as hollow ticks at the price seen, failed as a small ×. Hover/focus shows a tooltip: date, `$10 → 0.0035 ETH @ $2,860`, status, tx link. Fewer than 2 filled runs → no chart, a one-line hint instead. 6. **Recent runs** `.dca-runs`: last 5 as rows `#12 · 2 h ago · filled · $10 → 0.0035 ETH @ $2,860 · ↗` (explorer link). A `parked` run says `awaiting approval · #ord_…`. 7. **Actions** `.dca-actions` (only when `ctx.canWrite`, i.e. desktop): - `awaiting_approval`: **Approve & start** (primary) · Reject - `active`: Pause · Buy now · Stop - `paused`: Resume · Buy now · Stop - terminal: none. Buttons carry `data-dca-action=approve|reject|pause|resume|run|stop` and `data-dca-id`. A click calls `trading.dca.<action>`, disables the row while in flight, swaps in the returned payload, and for `run` passes the run's `orderId` to `actions.onOrder` so the desk focuses the Book. Errors show inline in `.dca-actions__error`. Stop asks for a second click ("Stop — click again") rather than a dialog. 8. **Warnings** `.dca-card__warnings` above the footer, one line each. 9. **Footer** `.dca-card__foot`: `dca_1a2b3c4d · Key main (0x89e0…da97) · as of <relative time>` · ↻ refresh (when `request` present) · copy id. ### Live state, never a stale button An artifact file is a snapshot from the moment the command ran; a mandate moves on. The mounter therefore (a) renders the snapshot with every action disabled (`data-dca-stale="checking"`) and at once re-reads the live state through `trading.dca.<request.kind>`; a failed read keeps the snapshot, sets `data-dca-stale="failed"` and shows a "state may be stale · ↻" line; (b) keeps a per-mounter cache of the latest payload per mandate id (fed by reads, action responses and `trading.dca.changed`) so a re-mounted card draws the newest known state immediately; (c) after an action is refused with `trading.dca.bad_state` / `not_found`, re-reads the card. The chart pads its price range by at least ±0.5 % of the average and labels the top and bottom of the range; same-day runs are labelled with times. ### `kind = "mandates"` — the list `article.dca-card[data-dca-kind=mandates]`: header `DCA · 3 mandates`, totals line (`$240 of $900 · $251 acquired`), then one row per mandate: status dot, the mandate **name** first, `ETH ← USDC · every day · $10`, a mini progress bar, `next buy in …`, and the same action buttons in compact form. Empty → `No DCA mandates yet.` ### Web vs desktop The renderer lives in `frontend/`; the desktop restyles it in `desktop/src/renderer/src/views/chat/chat.css` via the `data-dca-*` hooks and must look like a desk instrument (rail, mono numerals, tinted status), not like the web card. `canWrite` is true only on the desktop desk (`ChatView` passes `dcaActions`), false on the web. ## Desktop desk - **Presets** `dca` and `dca-capped` create a mandate (`trading.dca.create`) instead of a cron job. `MissionContract` for `kind === 'dca'` shows the mandate form (token, USD per buy, every, cap, buys, max price, wallet, chain, name, start now) and states the limits are **enforced by the engine** (drop the "goals, not limits" note there). Edit → `trading.dca.update`. - **Missions list** shows mandates next to cron missions (the dot strip above it names cron missions only, so a mandate appears once): name, state word (`Awaiting approval`, `Active · next 3 h 12 m`, `Active · buy due`, `Paused`, `Done`, `Ended · no buys` when it finished with zero buys), `done/max buys` with a muted `· N skipped · N failed` suffix, a mini progress `$120 / $300`, `statusReason` as the row tooltip, and controls Pause / Resume, Buy now, Edit, Stop (two-click). Buy now toasts the run's outcome (bought / placed / awaiting approval / skipped: reason / failed: reason). Finished mandates (any terminal status) stay for 1 h after `updatedAt`, at most 2 rows newest first, then `+N more`. The list shows three rows, one to a line, and scrolls past that. One formatter drives every countdown (`buy due`, `N m`, `H h M m`, `D d H h`, rounding down) on a shared one-second clock. Mandates never replace the composer placeholder (cron missions still do). The **header status strip** summarises mandates as one chip — `DCA · next 59 m`, `DCA ×2 · next 12 m`, `DCA · awaiting` — with no names or progress. Query key `['trading', 'dca']`; the existing `trading.changed` invalidation covers it. - **Approvals region** (the asks area above the composer, where order approval cards live) lists pending mandates above pending orders as a compact `MandateCard` (what, how much, how often, cap, first buy, expiry, warnings; values wrap, never truncate) with **Approve & start** / Reject. - **Desk ledger** (`ledger.ts`) recognises `agentos trade dca <sub> …` and the `dca-cards/` marker, with titles `Start DCA · ETH · $10 / day`, `DCA status`, `Pause DCA`, `Buy now`, … - **Orders** show `DCA ETH · buy 3/30` from the note; an order's `mandateId` links to the mandate. - **Desk prompt v18** (`agent.ts`): a DCA is a mandate the engine runs; create it with `agentos trade dca create … --json` (never a cron job; the existing "never schedule a trade" rule now says "except a DCA mandate, which parks for the user's approval"); reading rules: "DCA $10 ETH every day, max $300" → `--usd 10 --every 1d --cap 300`; "30 buys" → `--runs 30`; "only under 3000" → `--max-price 3000`; "how is my DCA doing" → `dca list --json` / `dca show <id> --json` and answer in one line, the card shows the rest; "pause/stop my DCA" → tell the user to use the card or the Missions panel (operator-only), or run the command and report `trading.operator_required` plainly. Always report the mandate id. ## Tests - **Engine** (`tests/test_trading/test_dca.py`, offline, fake clock): create as agent parks / as operator activates; approve → first run fires on tick with `startNow`; drift-free schedule and single catch-up after a gap; sizing to the remainder and completion at the cap / at `runs_max`; `max_price` skip without bad-streak; auto-pause after 3 insufficient balance skips; parked run when `usd_per_run > threshold` and its settlement path (approve → filled, expire → expired); daily-cap skip; update re-anchoring; stop/pause/resume state machine and `bad_state` errors; migration v6 → v7 on an existing ledger (orders keep their rows, `mandate_id` added); payload shape (regenerates `tests/fixtures/dca_cards/{mandate-active,mandate-awaiting,mandate-completed,mandates,mandates-empty}.json`, which the frontend tests read like the LP fixtures). - **RPC** (`tests/test_gateway/test_rpc_trading_dca.py`): methods registered; agent may create/get/list and gets `awaiting_approval`; every write is `trading.operator_required` for an agent; validation codes. - **CLI** (`tests/test_cli/test_trade_dca_cmd.py`): `--every` parsing, cap / runs rule, marker last line, `--no-card`, pruning, JSON errors on stderr, exit codes. - **Frontend** (`dca.test.ts`): category, normalisation, each status layout, countdown text, progress math, chart with 0/1/N runs, actions hidden without `canWrite`, action → RPC → payload swap, refresh, CSS contract test entries. - **Desktop**: `MandateCard` approve/reject, MissionControls rows for mandates, `ledger.ts` parsing of `dca` commands and the marker, `ChatView` passes `dcaActions` at the desk only, CSS skin test. - **Live** (tester, dust wallet, Base): `agentos trade dca create ETH --usd 0.05 --every 2m --runs 2 --json` from the desk chat as the agent → card with Approve & start → approve on the desktop → first buy fires within a tick, second after 2 min → mandate `completed`; `Buy now` on a paused mandate; the card and the Missions panel agree with `agentos trade dca show`. Cost ≈ $0.10 + gas. --- # Price triggers > Source: https://useagentos.dev/docs/core/triggers Artifact type: `application/vnd.agentos.trigger+json`. A **trigger** is a conditional order the trading engine watches and fires by itself: *sell half my ETH if it drops under $3,800*, *buy $50 of ETH when it is back under $3,500*, *sell when ETH falls 10 % from its peak*, or just *tell me when ETH crosses $5,000*. The user approves the trigger once; the engine polls the price on every tick and, when the condition holds, places one ordinary swap order through the existing pipeline (guardrails, approval threshold, daily cap, vault signing, ledger) or sends one notification. No LLM turn is spent watching the market; the condition, the size and the stop rules are rows in the ledger and are enforced there. A trigger is the third way the engine acts: *now* (`trade swap`), *on a schedule* (DCA mandates, `docs/dca.md`) and now *when the market does X*. It reuses the mandate machinery wherever it can: the same lifecycle, the same "an agent only proposes" rule, the same cards-in-chat mechanism, the same desk controls. This file is the contract between the engine, the gateway, the CLI, the shared renderer and the desktop. Change it before changing any of them. Chains: Base (8453) and Robinhood Chain (4663). OCO pairs (a take-profit and a stop-loss on one position, one cancelling the other) are **brackets** and live in [Brackets](https://useagentos.dev/docs/core/brackets): two triggers of this file sharing a group. Not in scope here: ladders, time-of-day conditions, conditions on anything but one token's USD price, repeating alerts, LP-range alerts (follow-up). ## Vocabulary | word | meaning | |---|---| | **kind** | what fires: `sell` (token → quote), `buy` (quote → token) or `alert` (a notification, no order) | | **token** | the token whose USD price is watched **and** traded | | **quote** | the counter token: what a sell receives / a buy spends; defaults to the chain's USDC, or the native coin when USDC itself is the token | | **condition** | `below <price>`, `above <price>`, or `trail <pct>` (price falls `pct` % from the highest price seen since arming) | | **armed** | the trigger is live and being checked every tick | | **fire** | one attempt to act when the condition held (or a manual *Fire now*) | Common names, derived by the engine when no `--name` is given: | kind · condition | name | |---|---| | sell · below | `Stop-loss ETH` | | sell · above | `Take-profit ETH` | | sell · trail | `Trailing stop ETH` | | buy · below | `Buy ETH under $3,500` | | buy · above | `Buy ETH over $4,200` | | buy · trail | not allowed (`trading.trigger.invalid`) | | alert · any | `Alert ETH under $3,800` / `Alert ETH over $5,000` / `Alert ETH −10 % from peak` | ## Lifecycle ``` create ──(operator)────────────► armed ──► triggered ──► done └────(agent)──► awaiting_approval ┤ │ (filled / alerted) │ │ ├─► armed (fire failed, retry next tick; 3 in a row → paused) ├─► rejected │ ├─► paused (parked order expired, or nothing to sell) └─► expired │ └─► stopped (parked order rejected by the user) ├─► paused ⇄ armed (user) ├─► stopped (user) └─► expired (validUntil passed) ``` - **Who may create.** Any connection. An **agent-bound** connection (`gateway/agent_surface.py`) always gets `awaiting_approval`; the operator (desktop, CLI without agent markers) gets `armed` at once. `initiator` is never trusted from params, exactly as for orders and mandates. - **Approval** of a pending trigger is operator-only. A pending trigger expires **24 h** after creation (`expires_at`). - **Arming** records `armed_at` and `armed_price_usd` (the price seen then, or `null`). For a `trail` condition the peak starts at the armed price and is raised on every later check where the price is higher. - **Checking.** `TradingService.tick()` (every `sync_interval_seconds`, 60 s) calls `trigger_check()`. One pass: expire proposals and `validUntil`, reconcile open fires, then for every `armed` trigger read the token's spot price (`PriceService.price`, batched per chain), store `last_price_usd` / `last_checked_at`, raise the peak, and evaluate: - `below`: `price <= price_usd` - `above`: `price >= price_usd` - `trail`: `peak_price_usd` known and `price <= peak × (1 − trail_pct/100)` - An unknown price (`None`) is **not** a miss: `hits` is left alone and the trigger waits for the next tick. It never fires blind. - **Confirmation.** The condition must hold on **2 consecutive checks** (`CONFIRM_TICKS = 2`, about a minute) before the trigger fires; one check where it does not hold resets `hits` to 0. A single bad print from the price feed must not sell a position. The card shows `hits / 2`. - **A fire** (`trigger_fires` row, written **before** the order like a DCA run so a crash cannot act twice): - `alert`: emit `trading.trigger.fired` with the price; the fire is `alerted`, the trigger is `done` (`statusReason` = `"alerted at $3,790"`). - `sell`: one swap order `token → quote`, `initiator="agent"` (guardrails apply), sized from the trigger: `amount_pct` of the wallet's balance **at fire time**, or `amount` (token units), or `amount_usd`. `note` = `"<name> · fired at $3,790"`, `trigger_id` set, `wait=False`. The trigger is `triggered` while the order is open. - `buy`: one swap order `quote → token` for `amount_usd`. - Before placing: a sell with a zero token balance, or a buy whose quote balance cannot cover `amount_usd`, is a fire `skipped insufficient_balance` and the trigger is **paused** at once (`"paused: nothing to sell"` / `"paused: insufficient USDC"`). There is nothing to retry. - **Fire outcomes** (`trigger_fires.status`): `pending` (order placed, not settled), `filled`, `parked` (awaiting approval), `alerted`, `skipped` (`insufficient_balance`), `failed` (quote/execution error; `reasonCode` = the error code), `expired`, `rejected`. - `filled` → trigger `done`, `statusReason` e.g. `"sold 0.05 ETH for 189.4 USDC at $3,788"`. - `failed` → trigger back to `armed` with `bad_streak + 1` and `hits = 0` (it must re-confirm). Three consecutive failures → `paused` (`"paused after 3 failed fires: <code>"`). Resume resets the streak. - `parked` → trigger stays `triggered`; when the order settles: confirmed → `done`; **rejected** → `stopped` (`"sell rejected by you"`); **expired** → `paused` (`"the sell waited for approval and expired"`). It does not re-arm by itself: re-arming would park a new order every minute. - A `pending` fire whose order never appeared is written off as `failed trading.interrupted` after 1 h; each tick re-checks open fires against their orders (restart safety). - **Fire now** (`trading.trigger.fire`, operator-only) acts at once on an `armed` or `paused` trigger regardless of the condition; it is a fire with `manual = 1`. Exposed on the desk as *Fire now* (and *Sell now* / *Buy now* wording for the two kinds). - **Stop** is terminal and rejects a parked order of the trigger. **Pause** (`"user"`) / **Resume** flip `armed`/`paused`; resume resets `hits`, `bad_streak` and, for `trail`, the peak to the current price (a stop that was paused through a rally must not fire on the old peak). - **validUntil** (optional, GTC when absent): an `armed`/`paused` trigger past it becomes `expired` (`"not reached by <date>"`). - Nothing is ever deleted. `list` shows live triggers (`awaiting_approval`, `armed`, `triggered`, `paused`) unless `--all`. It never lists a bracket's legs (nor counts them in `totals`): a bracket is listed by `trading.bracket.list` (`brackets.md`). - **A bracket's legs refuse leg-level writes**: `approve`, `reject`, `pause`, `resume`, `stop` and `fire` on a leg answer `trading.trigger.bad_state` (*"trg_… is the take-profit leg of bracket brk_…: use trading.bracket.*"*); `get` works and shows the leg with its `bracket` field. - **Update** is not in v1 (stop and create again). ### Relative prices `--below`/`--above` accept an absolute USD price (`3800`) **or** a percent of the price at creation (`-10%` / `10%` on `--below` means 10 % under the current price; `+15%` / `15%` on `--above` means 15 % over it). The engine resolves the percent to an absolute `price_usd` **at creation** (what the user saw on the card) and records `from_price_usd`. With no price known the percent form is refused (`trading.trigger.invalid`: *"ETH has no price right now: give an absolute price"*). `--trail` is always a percent. ### Warnings at creation - `below` when the price is already at or under it (`above` likewise): *"ETH is already at $3,700, under $3,800: this fires after the next two checks"*. - A sell/buy whose estimated size is over the approval threshold: *"a sell of ≈$500 is above the $100 approval threshold and will wait for you when it fires"*. - A sell from a wallet that holds none of the token: *"Key main holds no ETH"*. - No price known: *"price unknown: the trigger waits until ETH has a price"* (the trigger still arms). The quote of a **sell** or **buy** defaults to the chain's USDC, or the native coin when USDC itself is the token: `trigger create USDC --sell --pct 100 --above 0.5` sells USDC for ETH (`sell 100 % of USDC → ETH`). Only a `--quote` the user gives that equals the token is refused (*"token and quote are the same token"*); a chain with no canonical USDC needs `--quote`. An **alert** never trades, so its quote is only the counter the card shows: the given `--quote`, else the chain's USDC, else (USDC itself being watched, or a chain with no canonical USDC) the native coin. An alert is never refused for its quote. ## Ledger (schema v8) ```sql CREATE TABLE IF NOT EXISTS triggers ( trigger_id TEXT PRIMARY KEY, -- "trg_" + 8 hex kind TEXT NOT NULL, -- sell | buy | alert name TEXT NOT NULL, status TEXT NOT NULL, -- awaiting_approval|armed|triggered|paused|done|stopped|rejected|expired status_reason TEXT, chain_id INTEGER NOT NULL, wallet TEXT NOT NULL, token TEXT NOT NULL, -- watched and traded (address) quote TEXT NOT NULL, -- counter token (address) direction TEXT NOT NULL, -- below | above | trail price_usd REAL, -- below/above threshold (absolute, resolved) trail_pct REAL, -- trail from_price_usd REAL, -- price at creation when a percent was given amount_usd REAL, -- buy: spend; sell: optional size amount_pct REAL, -- sell: % of the token balance at fire time amount_raw TEXT, -- sell: fixed token amount (raw string) slippage_pct REAL, confirm_ticks INTEGER NOT NULL DEFAULT 2, hits INTEGER NOT NULL DEFAULT 0, peak_price_usd REAL, -- trail state armed_at REAL, armed_price_usd REAL, last_price_usd REAL, last_checked_at REAL, triggered_at REAL, fires_failed INTEGER NOT NULL DEFAULT 0, bad_streak INTEGER NOT NULL DEFAULT 0, valid_until REAL, initiator TEXT NOT NULL, -- 'agent' | 'manual' session_key TEXT, created_at REAL NOT NULL, updated_at REAL NOT NULL, approved_at REAL, expires_at REAL ); CREATE INDEX IF NOT EXISTS idx_triggers_status ON triggers(status, created_at DESC); CREATE TABLE IF NOT EXISTS trigger_fires ( fire_id INTEGER PRIMARY KEY AUTOINCREMENT, trigger_id TEXT NOT NULL, n INTEGER NOT NULL, -- 1-based, every attempt at REAL NOT NULL, status TEXT NOT NULL, -- pending|filled|parked|alerted|skipped|failed|expired|rejected reason TEXT, -- "<code>: <detail>" like mandate_runs price_usd REAL, -- spot price seen at the fire order_id TEXT, manual INTEGER NOT NULL DEFAULT 0 ); CREATE INDEX IF NOT EXISTS idx_trigger_fires ON trigger_fires(trigger_id, n DESC); ALTER TABLE orders ADD COLUMN trigger_id TEXT; -- migration v7 → v8 CREATE INDEX IF NOT EXISTS idx_orders_trigger ON orders(trigger_id) WHERE trigger_id IS NOT NULL; ``` `_order_dict` gains `"triggerId": str | null`. `ORDER_KINDS` unchanged (a trigger's order is `kind='swap'`). When an order with `trigger_id` settles, the engine settles the fire and the trigger in the same place it settles the order (`_order_finished`), exactly like a DCA run. Engine module: `src/agentos/trading/triggers.py` — pure helpers (condition evaluation, relative-price resolution, default names, reasons, payload building) with no service imports; the runner lives on `TradingService`: ```python async def trigger_create(self, *, chain, kind, token, quote, direction, price, trail_pct, amount_usd, amount_pct, amount, wallet, slippage_pct, name, valid_for_seconds, initiator, session_key) -> dict # payload kind="trigger" async def trigger_get(self, trigger_id) -> dict async def trigger_list(self, *, all=False, wallet=None) -> dict # kind="triggers" async def trigger_approve(self, trigger_id) -> dict async def trigger_reject(self, trigger_id, reason=None) -> dict async def trigger_pause(self, trigger_id) -> dict async def trigger_resume(self, trigger_id) -> dict async def trigger_stop(self, trigger_id, reason=None) -> dict async def trigger_fire_now(self, trigger_id, *, wait=False) -> dict # payload + "fire": Fire async def trigger_check(self) -> None # from tick() ``` `price` for `trigger_create` is a `str | float`: `"3800"`, `"-10%"`, `"+15%"`, `"10%"`; the service resolves it (see *Relative prices*). `amount` is a token amount in human units (`"0.05"`). Errors are `TradingError` codes: `trading.trigger.not_found`, `trading.trigger.bad_state`, `trading.trigger.invalid` (unknown kind or direction; `buy` with `trail`; no size on sell/buy, more than one size, a size on `alert`; `amount_pct` outside 0 < pct ≤ 100; price ≤ 0; trail outside 0 < pct < 100; `valid_for` under 60 s; a percent price with no current price; quote missing on Robinhood Chain; a given quote == token; wallet `all`), `trading.operator_required` (RPC layer), `trading.integrity` (a fire-now on a trigger that failed its seal: it is stopped), plus `trading.disabled`, `wallet.locked`, `trading.unsupported_chain`, `trading.token_not_found`. At create, `slippagePct` may not exceed the agent slippage ceiling. Approving a trigger (or creating one as the operator) seals its terms with the vault key, so it needs an unlocked vault; a trigger whose row was changed outside the engine is stopped (`"integrity check failed (…)"`) instead of firing. While you have locked the vault, trading triggers wait (alerts still ring); removing the wallet stops its triggers (`"wallet removed"`). Events: every state change emits `trading.changed {reason: "trigger", triggerId}` and `trading.trigger.changed {trigger}` (full `Trigger` object). Each fire emits `trading.trigger.fired {triggerId, trigger, fire}` once when it happens (alert sent / order placed / skipped / failed) and `trading.trigger.changed` when it settles. The order itself emits the usual `trading.approval.requested` / `trading.order.finished`. ## Payload ```jsonc Envelope = { "version": 1, "kind": "trigger" | "triggers", "fetchedAt": iso, "warnings": [string], "request": { "kind": "get" | "list", "params": {…} } // ↻ re-runs trading.trigger.<kind> } { ...Envelope, "trigger": Trigger, "fire": Fire | undefined } // kind = "trigger" { ...Envelope, "triggers": [Trigger], // kind = "triggers": live first, then newest "totals": { "count": 3, "armed": 2, "awaiting": 1, "triggered": 0 } } Trigger = { "id": "trg_1a2b3c4d", "name": "Stop-loss ETH", "kind": "sell" | "buy" | "alert", "status": "awaiting_approval" | "armed" | "triggered" | "paused" | "done" | "stopped" | "rejected" | "expired", "statusReason": string | null, "chain": Chain, "wallet": Wallet, "token": Token, "quote": Token, // LP card types; priceUsd on both tokens "condition": { "direction": "below" | "above" | "trail", "priceUsd": number | null, // below/above threshold "trailPct": number | null, // trail "fromPriceUsd": number | null, // when a percent was given at creation "peakPriceUsd": number | null, // trail: highest price since arming "stopPriceUsd": number | null, // trail: peak × (1 − trailPct/100), what it would fire at now "confirmTicks": 2, "hits": 0, "label": "under $3,800" | "over $5,000" | "10 % below peak" }, "action": { "kind": "sell" | "buy" | "alert", "amountUsd": number | null, // buy: spend; sell: size when given in USD "amountPct": number | null, // sell: % of balance "amount": Amount | null, // sell: fixed token amount "estimatedUsd": number | null, // what the fire would move at the current price (sell pct/amount × price); once terminal with a result: result.amountIn.usd, what actually moved "slippagePct": number | null, "needsApproval": boolean, // estimatedUsd > approvalThresholdUsd "approvalThresholdUsd": number, "dailyCapUsd": number, "label": "sell 50 % of ETH → USDC" | "buy $50 of ETH with USDC" | "notify" }, "market": { "priceUsd": number | null, // last price seen "armedPriceUsd": number | null, "distancePct": number | null, // signed % move from priceUsd needed to fire: −2.1 (must fall), +4.0 (must rise); 0 when already met "checkedAt": iso | null, "balance": Amount | null // the wallet's token (sell) / quote (buy) balance now; null for alert and for a terminal trigger }, "fires": [Fire], // newest first, ≤ 20 "result": { // when done by an order "orderId": string, "txHash": string | null, "explorerUrl": string | null, "amountIn": Amount, "amountOut": Amount | null, "priceUsd": number | null, "gasUsd": number | null } | null, "validUntil": iso | null, "initiator": "agent" | "manual", "sessionKey": string | null, "createdAt": iso, "updatedAt": iso, "approvedAt": iso | null, "armedAt": iso | null, "triggeredAt": iso | null, "expiresAt": iso | null, "bracket": { "id": "brk_1a2b3c4d", "name": "Protect ETH", "leg": "tp" | "sl" } | null // set on a bracket's leg (brackets.md) } Fire = { "n": 1, "at": iso, "manual": false, "status": "pending" | "filled" | "parked" | "alerted" | "skipped" | "failed" | "expired" | "rejected", "reasonCode": string | null, "reason": string | null, "priceUsd": number | null, "orderId": string | null, "txHash": string | null, "explorerUrl": string | null } ``` USD `null` means unknown, never `0`. `Chain`, `Token`, `Amount`, `Wallet` are the LP card types (`dca.py` already has the builders; import them). ## RPC Agent-callable (create only proposes; reads are harmless): | method | params | returns | |---|---|---| | `trading.trigger.create` | `chainId`/`chain`, `kind`, `token`, `quote?`, `direction`, `price?` (string or number; required for below/above), `trailPct?` (required for trail), `amountUsd?`, `amountPct?`, `amount?`, `wallet?`, `slippagePct?`, `name?`, `validForSeconds?`, `sessionKey?` (operator only) | `trigger` payload | | `trading.trigger.get` | `triggerId` | `trigger` payload | | `trading.trigger.list` | `all?`, `wallet?` | `triggers` payload | Operator-only (`@_operator_only`): | method | params | returns | |---|---|---| | `trading.trigger.approve` | `triggerId` | payload (now `armed`) | | `trading.trigger.reject` | `triggerId`, `reason?` | payload | | `trading.trigger.pause` / `resume` / `stop` | `triggerId`, `reason?` (stop) | payload | | `trading.trigger.fire` | `triggerId`, `wait?` | payload + `fire` | Validation errors are `trading.trigger.invalid` naming the field; helpers mirror `_dca_*` in `rpc_trading.py`. ## CLI ``` agentos trade trigger create <token> (--below <price|pct%> | --above <price|pct%> | --trail <pct>) (--sell (--pct 50 | --amount 0.05 | --usd 100) | --buy --usd 50 | --alert) [--quote USDC] [--chain base|robinhood] [--wallet ADDR|label] [--slippage 1] [--name "…"] [--for 7d] [--json] [--no-card] agentos trade trigger list [--all] [--wallet …] [--json] [--no-card] agentos trade trigger show <id> [--json] [--no-card] agentos trade trigger approve <id> [--json] [--no-card] agentos trade trigger reject <id> [--reason "…"] [--json] [--no-card] agentos trade trigger pause | resume <id> [--json] [--no-card] agentos trade trigger stop <id> [--reason "…"] [--json] [--no-card] agentos trade trigger fire <id> [--wait --wait-seconds N] [--json] [--no-card] ``` - Exactly one of `--below` / `--above` / `--trail`; exactly one of `--sell` / `--buy` / `--alert`; `--sell` takes exactly one size, `--buy` takes `--usd`, `--alert` takes none. Checked in the CLI (exit 2) before the RPC. - `--for` accepts `30m`, `2h`, `1d`, `1w` or seconds (`parse_every`, ≥ 60 s). - `--json` prints the payload and, unless `--no-card`, writes `trigger-cards/<kind>-<slug>-<utc stamp>.json` (20 newest kept) and prints the marker `publish_artifact path=<file> mime=application/vnd.agentos.trigger+json` as the last line. The gateway auto-publishes `application/vnd.agentos.*`. - Human output: a Rich panel (name, kind, status, condition, price now and distance, size, hits, recent fires, result) or a table for `list`. - Exit codes as `trade dca`: 2 for input / `trading.trigger.invalid` / `bad_state` / `not_found` / `trading.invalid` / `trading.token_not_found`; 1 for gateway errors (including `trading.operator_required`). Errors are JSON on stderr under `--json`, never a card. - From an agent shell, `create` always answers `status: "awaiting_approval"`; the agent says the card has an **Approve & arm** button and never approves itself. ## Rendering Shared renderer: `frontend/src/views/chat/transcript/trigger.ts`. Same skeleton as `dca.ts`: `isTriggerArtifact`, `normalizeTriggerPayload`, `createTriggerMounter({ fetchPayload, call, actions })`, registered in `artifacts.ts` (category `'trigger'`, placeholder `.msg-artifact-trigger[data-trigger-src]`) and mounted from `useTranscript.ts` next to `dcaMounter` (option `triggerActions`, same shape as `dcaActions`). `trading.order.finished` and `trading.trigger.changed` refresh mounted cards of the affected trigger. ### `kind = "trigger"` — the card Root `article.trigger-card[data-trigger-kind=trigger][data-trigger-action=sell|buy|alert][data-trigger-status=…][data-trigger-chain=…][data-trigger-layout=wide|narrow]`. 1. **Header** `.trigger-card__head`: name, chain pill, status pill `.trigger-pill[data-status]` (`awaiting_approval` amber pulse, `armed` green, `triggered` blue pulse, `paused` grey, `done` blue, `stopped` / `rejected` / `expired` muted). Kind glyph: ▼ sell, ▲ buy, 🔔 alert (CSS via `data-trigger-action`, no emoji in the DOM). 2. **Hero** `.trigger-card__hero`: the sentence `sell 50 % of ETH when under $3,800` (large), under it the live line `.trigger-card__now`: `ETH $3,790 · 0.3 % above the line · checked 12 s ago` (or `armed, waiting for a price`, `fires after 1 more check` when `hits ≥ 1`, `done · sold 0.05 ETH at $3,788`, `awaiting approval`). 3. **Gauge** `.trigger-gauge`: a horizontal rail with the current price as a dot and the trigger price as a tick, labelled with both; for `trail`, the peak and the stop price. Pure SVG, no dependency; `data-trigger-dist` carries the signed distance for the skin to tint (near = amber). 4. **Facts** `.trigger-card__facts` (2×2): *size* (`50 % · ≈ $189` / `$50` / `—`), *wallet balance* (`0.1 ETH`), *valid until* (`GTC` / date), *on fire* (`trades at once` / `waits for you · over $100`; absent on an alert). 5. **Fires** `.trigger-fires`: last 5 as rows `#1 · 2 m ago · filled · $189 → 0.05 ETH @ $3,788 · ↗`, `parked · awaiting approval`, `failed · <reason>`. 6. **Actions** `.trigger-actions` (only when `ctx.canWrite`, desktop): `awaiting_approval`: **Approve & arm** · Reject; `armed`: Pause · Fire now · Stop; `paused`: Resume · Fire now · Stop; `triggered`: Stop; terminal: none. Buttons carry `data-trigger-op=approve|reject|pause|resume|fire|stop` and `data-trigger-id`; a click calls `trading.trigger.<op>`, disables the row in flight, swaps in the returned payload; `fire` passes the fire's `orderId` to `actions.onOrder`. Stop and Fire now take a confirming second click. Errors inline in `.trigger-actions__error`. 7. **Warnings** `.trigger-card__warnings`, **Footer** `.trigger-card__foot`: `trg_1a2b3c4d · Key main (0x89e0…da97) · as of <relative>` · ↻ · copy id. Live state as for DCA: render the snapshot with actions disabled (`data-trigger-stale="checking"`), re-read at once through `trading.trigger.get`, keep a per-id cache fed by reads, action responses and `trading.trigger.changed`; re-read after `bad_state` / `not_found`. ### `kind = "triggers"` — the list `article.trigger-card[data-trigger-kind=triggers]`: header `Triggers · 3`, totals (`2 armed · 1 awaiting`), one row per trigger: status dot, name, `sell 50 % ETH · under $3,800`, `ETH $3,790 · −0.3 %`, compact actions. Empty → `No triggers yet.` ### Web vs desktop The payload normalizers live in `frontend/src/views/chat/transcript/`. The web console draws its own read-only React card from them (`frontend/src/web/features/chat/cards/TradingCards.tsx`): it refreshes on `trading.*.changed` but offers no actions. The desktop renders the full card with its actions and styles it in `desktop/src/renderer/src/views/chat/chat.css` as a desk instrument (rail, mono numerals, tinted status). `canWrite` is true only on the desktop desk. ## Desktop desk - **Store** (`stores/trading.ts`): `useTriggers(all, enabled)` on `trading.trigger.list`, query key `['trading', 'trigger']`, refreshed by `trading.changed` (already) and `trading.trigger.changed` (add to `TRADING_EVENTS`); `useTriggerActions()` → approve / reject / pause / resume / stop / fire with toasts (`trading.trigger.toast.*`). - **Approvals region** lists pending triggers above pending mandates as a compact `TriggerCard` (what, when, size, wallet, expiry, warnings) with **Approve & arm** / Reject (Touch ID gate like `MandateCard`). - **Missions panel** shows triggers beside mandates: name, state word (`Awaiting approval`, `Armed · ETH $3,790 · −0.3 %`, `Armed · 1 of 2 checks`, `Triggered · order open`, `Paused`, `Done`), controls Pause / Resume, Fire now (two-click), Stop (two-click). Finished triggers stay 1 h. - **Status strip** adds one chip: `Triggers ×2`, `Trigger · near` when any armed trigger is within 1 % of its line, `Trigger · fired` while one is `triggered`. - **Notifications** (`use-notifications.ts`): on `trading.trigger.fired` post a native notification, kind `trade` (the main-process whitelist already carries it), target `{ type: 'trading', orderId? }`: - alert: title `ETH under $3,800`, subtitle `Alert · $3,790 now`; - sell/buy: title `Stop-loss ETH fired`, subtitle `selling 50 % of ETH at $3,790`; the order's own filled/approval notifications follow as usual; - skipped/failed: kind `tradeFailed`, body = the reason. - **Desk ledger** (`ledger.ts`) recognises `agentos trade trigger <sub> …` and the `trigger-cards/` marker: titles `Stop-loss · ETH · under $3,800`, `Take-profit · …`, `Buy the dip · …`, `Price alert · …`, `Trigger status`, `Pause trigger`, `Fire now`, … - **Orders** show `Stop-loss ETH · fired at $3,790` from the note; an order's `triggerId` links to the trigger. - **Desk prompt** (`agent.ts`, bump the version): a new **Triggers** section. A conditional request — "sell if it drops under", "cut my loss", "take profit at", "buy when it dips to", "stop loss 10 %", "trailing stop", "tell me when", "alert me when" — is a trigger the engine watches; never poll the price yourself, never schedule a cron for it. Reading rules: "sell all my ETH if it drops under 3800" → `trigger create ETH --sell --pct 100 --below 3800 --json`; "stop loss 10 %" → `--sell --pct 100 --below -10%`; "take profit at +20 %" → `--sell --pct 50 --above +20%` (ask the size only if truly absent, default 100 %); "buy $50 of ETH when it is back at 3500" → `--buy --usd 50 --below 3500`; "trailing stop 10 %" → `--sell --pct 100 --trail 10`; "tell me when ETH reaches 5000" → `--alert --above 5000`. From an agent the result is `awaiting_approval`: report the card has **Approve & arm**, give the id (`trg_…`), stop. "how are my triggers" → `trigger list --json`, one line. Pause/stop/fire are the user's controls (`trading.operator_required`). ## Tests - **Engine** (`tests/test_trading/test_triggers.py`, offline, fake clock, `FakePrices`): create as agent parks / as operator arms; relative price resolution and refusal without a price; default names; below/above/trail evaluation incl. peak tracking; two-tick confirmation and reset on a miss; unknown price neither fires nor resets; alert fires once and is done; sell by pct sizes from the balance at fire time; buy by usd; insufficient balance pauses at once; failed fire re-arms, three pause; parked order → confirmed done / rejected stopped / expired paused; stop rejects a parked order; validUntil expiry; resume resets hits/streak/peak; fire now; reconcile after restart; migration v7 → v8 keeps orders and mandates and adds `orders.trigger_id`; payload shape pins `tests/fixtures/trigger_cards/{trigger-armed,trigger-awaiting,trigger-done,trigger-alert,triggers,triggers-empty}.json` (regenerate with `AGENTOS_REGEN_TRIGGER_FIXTURES=1`). - **RPC** (`tests/test_gateway/test_rpc_trading_triggers.py`): methods registered; agent create/get/list, `awaiting_approval`, `initiator` and `sessionKey` not honoured; every write `trading.operator_required` for an agent; validation codes; approve → armed. - **CLI** (`tests/test_cli/test_trade_trigger_cmd.py`): flag exclusivity, size rules, `--for` parsing, marker last line, `--no-card`, pruning, JSON errors on stderr, exit codes, params sent. - **Frontend** (`trigger.test.ts`): category, normalisation, each status layout, hero/now text, gauge geometry, actions hidden without `canWrite`, action → RPC → payload swap, refresh, CSS contract entries. - **Desktop**: `TriggerCard` approve/reject, Missions rows for triggers, `ledger.ts` parsing, notification mapping for `trading.trigger.fired`, store hooks, CSS skin test. - **Live** (dust wallet, Base, ≈ $0.10 + gas): `trigger create USDC --alert --above 0.5 --json` fires within two ticks and posts a notification; `trigger create USDC --sell --usd 0.04 --above 0.5 --quote ETH` fires and fills; `trigger create USDC --buy --usd 0.04 --below 2 --quote ETH` fires and fills; `trigger create ETH --sell --pct 1 --below 100` stays armed with the right distance and is stopped; a trailing alert records the peak. --- # Brackets > Source: https://useagentos.dev/docs/core/brackets Artifact type: `application/vnd.agentos.trigger+json`, kind `bracket`. A **bracket** protects a position with two price triggers at once: *sell my ETH when it is up 20 %, or when it is down 10 %, whichever comes first*. The two **legs** are ordinary price triggers (`docs/triggers.md`) that know about each other: when one fires and fills, the other is stopped (one cancels the other, "OCO"). Without a bracket the user has to create a take-profit and a stop-loss separately and remember to cancel the survivor; if they forget, the survivor fires into an empty wallet and pauses with *nothing to sell*. A bracket is **not** a new kind of engine object. It is a group of two trigger rows that share a `group_id`; everything a trigger already does (confirmation on two ticks, the fire rows, the guardrails, the approval of large orders, the ledger, the cards) applies to each leg unchanged. What is new is the group: it is created, approved, paused, resumed, stopped and shown **as one thing**, and the engine keeps its two legs consistent. This file is the contract between the engine, the gateway, the CLI, the shared renderer and the desktop. Change it before changing any of them. It extends `docs/triggers.md`; whatever it does not say, that file says. Chains: Base (8453) and Robinhood Chain (4663). Kinds: `sell` (the bracket sells the position) and `alert` (a range alert: *tell me when ETH leaves $3,420–$4,560*). Not in scope: buy brackets (OCO entries), more than two legs, ladders, editing a live bracket (stop and create again), moving the stop to break-even by itself. ## Vocabulary | word | meaning | |---|---| | **bracket** | the group: one name, one status, one card, two legs | | **leg** | one of the two triggers: the **take-profit** leg (`tp`, fires `above`) and the **stop-loss** leg (`sl`, fires `below` or `trail`). A range alert's legs are its **ceiling** (`tp`) and **floor** (`sl`): every leg word below reads so for `kind = alert` (`triggers.leg_word(leg, kind)`) | | **sibling** | the other leg | | **on hold** | a leg paused by the engine because its sibling is firing; it is released or stopped when the sibling's fire settles | | **line** | a leg's price: the take-profit line and the stop line (a trail's moves with the peak) | Default names (`--name` renames the bracket only; the legs keep theirs): | kind | bracket | take-profit leg | stop-loss leg | |---|---|---|---| | sell | `Protect ETH` | `Take-profit ETH` | `Stop-loss ETH` (`Trailing stop ETH` with `--trail`) | | alert | `Watch ETH` | `Alert ETH over $4,560` | `Alert ETH under $3,420` (`Alert ETH −10 % from peak`) | ## Lifecycle A bracket has no row of its own; its **status is derived from its legs**, by precedence: ``` triggered > awaiting_approval > armed > paused > done > stopped > rejected > expired ``` The first status in that order that any leg has is the bracket's. `statusReason` is the deciding leg's `statusReason`, prefixed with the leg word when the two legs are in different states (`"take-profit: sold 0.05 ETH for 230 USDC at $4,560"`, `"stop-loss paused: nothing to sell"`, `"take-profit filled · stop-loss guards the rest"`). The engine helper is `triggers.bracket_status(legs)`; it is pure and tested. ``` create ──(operator)────────────► armed ──(a leg fires)──► triggered ──► done (leg filled / alerted; sibling stopped) └────(agent)──► awaiting_approval ┤ │ │ │ ├─► armed (fire failed / order rejected or expired: sibling released) ├─► rejected │ └─► paused (nothing to sell: both legs paused) └─► expired ├─► paused ⇄ armed (user: both legs) ├─► stopped (user: both legs; a parked order is rejected) └─► expired (validUntil: both legs) ``` - **Creation** writes both legs in **one ledger transaction** (`insert_triggers`), both with the same `group_id` (`"brk_" + 8 hex`), `group_name`, `wallet`, `token`, `quote`, `slippage_pct`, `valid_until`, `initiator`, `session_key`; `leg` is `"tp"` / `"sl"`. An agent-bound connection gets both legs `awaiting_approval` (one proposal, one card, one **Approve & arm**); the operator gets both `armed`. `initiator` is never trusted from params. - **Approve / reject** act on both legs (`approve` arms both at the price then; the pending TTL is the trigger's 24 h). **Pause** pauses every `armed` leg (`"user"`); it is `bad_state` while a leg is `triggered`. **Resume** re-arms every `paused` leg (hits, streak and a trail's peak reset as for a trigger). **Stop** stops every live leg and rejects a parked order of either, as `trigger_stop` does. - **Leg-level writes are refused.** `trading.trigger.approve|reject|pause| resume|stop|fire` on a leg answer `trading.trigger.bad_state` (*"trg_… is the take-profit leg of bracket brk_…: use trading.bracket.*"*). Reads (`trading.trigger.get`) work and show the leg with its `bracket` field. - **`trading.trigger.list` does not list legs** (nor count them in `totals`); a bracket is listed by `trading.bracket.list`. The desk's Missions therefore see one row per bracket, never three. - **Checking** is the trigger's: each armed leg is evaluated every tick with the same two-tick confirmation. Nothing is added to `trigger_check()`. ### One cancels the other All of this happens inside the trigger runner (`_trigger_fire`, `_trigger_after_fire`), under the trigger lock, for a leg that has a `group_id`: 1. **When a leg is claimed** (`armed` → `triggered`, manual or not), its sibling, if `armed`, is put **on hold**: `paused` with `status_reason = "on hold: take-profit fired"` (`triggers.OCO_HOLD` prefix, naming the fired leg). A sibling that is already `paused` (by the user or by a failure) is left alone. The sibling never fires while its twin's order is open: there is one position and one order on it at a time. 2. **When the fire settles:** - `filled` / `alerted` → the leg is `done`; the sibling is **stopped** from any live status (`"take-profit filled"` / `"stop-loss filled"` / `"range left over the top"` / `"range left under the floor"`, `triggers.oco_stopped_reason`). The bracket is `done`. - **Partial take-profit** (`tp_pct` under the position's `amount_pct`, see *Sizing*): a `filled` take-profit leg is `done`, but the stop-loss leg is **released** instead of stopped (it guards the rest: `amount_pct` of what is left). The bracket stays `armed` with reason `"take-profit filled · stop-loss guards the rest"`. A filled stop-loss still stops the take-profit (the stop sells the whole size). - `failed`, or a parked order `rejected` by the user or `expired` waiting: the leg goes where a trigger goes (`armed` / `paused` / `stopped`); a sibling **on hold is released**: `armed` again, `hits = 0`, `bad_streak = 0`, a trail's peak reset to the price now (`triggers.release`). A sibling the user had paused stays paused. - `skipped` (insufficient balance): the leg pauses as a trigger does; a sibling on hold is **paused the same way** (`"paused: nothing to sell"`): it would find the same empty wallet. The bracket is `paused`; resume re-arms both. 3. **Fire now** on a bracket (`trading.bracket.fire`) fires one leg by hand: the `leg` given, else the **nearest** leg (the smaller `|distancePct|` at the last price; `sl` when no price is known). The sibling goes on hold as in 1. The desk words it *Sell now* (`sell`) / *Notify now* (`alert`). 4. A release or a stop of the sibling is a trigger state change: it emits `trading.trigger.changed` for the sibling and `trading.bracket.changed` once for the group. Restart safety is the trigger's: the hold is a row (`paused` + reason), the fire row is written before the order, and `_trigger_reconcile` settles the stray fire, which runs step 2. ### Sizing Both legs sell the same position: exactly one of `amountPct` (default `100` when no size is given), `amount` (token units) or `amountUsd`, copied to both legs. `tpPct` (sell, with `amountPct` only) makes the take-profit leg sell a smaller share: `tpPct` ≤ `amountPct`, `0 < tpPct`; equal to `amountPct` it is dropped. An alert bracket has no size. ### Lines `takeProfit` is a price or a percent **over** the price now (`4560`, `"+20%"`, `"20%"`), resolved at creation like a trigger's `--above`. `stopLoss` is a price or a percent **under** it (`3420`, `"-10%"`), like `--below`; or `trailPct` makes the stop leg a trailing stop (exactly one of `stopLoss` / `trailPct`). After resolution the take-profit line must be **above** the stop line (`trading.bracket.invalid`: *"take-profit $3,000 must be above stop-loss $3,400"*); a trail's initial stop (`price × (1 − trailPct/100)`) is compared when the price is known. A percent with no price known is refused as for a trigger. The price now **between** the lines is the normal case; outside, the creation warnings of the leg that is already met say so (*"ETH is already at $4,700, over $4,560: the take-profit fires after the next two checks"*). Both legs' warnings are the bracket's, prefixed with the leg word. Quote and wallet rules are the trigger's: `quote` defaults to the chain's USDC (the native coin when the token is USDC itself), is required on a chain without a canonical USDC for a `sell` bracket, never refused for an `alert`; `wallet` defaults to the primary wallet and may not be `all`. ## Ledger (schema v9) ```sql ALTER TABLE triggers ADD COLUMN group_id TEXT; -- "brk_" + 8 hex; NULL for a plain trigger ALTER TABLE triggers ADD COLUMN group_name TEXT; -- the bracket's name, on both legs ALTER TABLE triggers ADD COLUMN leg TEXT; -- 'tp' | 'sl' | NULL CREATE INDEX IF NOT EXISTS idx_triggers_group ON triggers(group_id) WHERE group_id IS NOT NULL; ``` Migration v8 → v9 adds the three columns (`_add_trigger_group_columns`); existing triggers are untouched (`group_id IS NULL`). Ledger API: ```python def insert_triggers(self, rows: list[dict]) -> None # one transaction def list_triggers(self, *, statuses=None, wallet=None, legs="exclude") # "exclude" | "only" | "all" def group_triggers(self, group_id: str) -> list[dict] # the legs, tp first def list_groups(self, *, statuses=None, wallet=None) -> list[str] # group ids, newest first; statuses: any leg in ``` `list_triggers(legs="exclude")` is the default so every existing caller (the checker, `trigger_list`, the reconciler) keeps working; the checker and the expirers call it with `legs="all"` so legs are evaluated and expired like any trigger. `triggers.py` gains the pure helpers: `BRACKET_ID_PREFIX = "brk_"`, `new_bracket_id()`, `LEGS = ("tp", "sl")`, `OCO_HOLD = "on hold: "`, `hold_reason(leg_name)`, `oco_stopped_reason(kind, fired_leg)`, `bracket_default_name(kind, symbol)`, `leg_word(leg)` (`"take-profit"` / `"stop-loss"`), `bracket_status(legs) -> (status, status_reason)`, `validate_bracket_terms(...)`, `bracket_json(...)`, `bracket_payload(...)`, `brackets_payload(...)`, `nearest_leg(legs)`. The runner on `TradingService`: ```python async def bracket_create(self, *, chain, kind, token, quote, take_profit, stop_loss, trail_pct, amount_usd, amount_pct, amount, tp_pct, wallet, slippage_pct, name, valid_for_seconds, initiator, session_key) -> dict # payload kind="bracket" async def bracket_get(self, bracket_id) -> dict async def bracket_list(self, *, all=False, wallet=None) -> dict # kind="brackets" async def bracket_approve(self, bracket_id) -> dict async def bracket_reject(self, bracket_id, reason=None) -> dict async def bracket_pause(self, bracket_id) -> dict async def bracket_resume(self, bracket_id) -> dict async def bracket_stop(self, bracket_id, reason=None) -> dict async def bracket_fire_now(self, bracket_id, *, leg=None, wait=False) -> dict # payload + "fire": Fire ``` Errors: `trading.bracket.not_found`, `trading.bracket.bad_state`, `trading.bracket.invalid` (unknown kind; `takeProfit` missing; neither or both of `stopLoss` / `trailPct`; a size on `alert`; more than one size; `tpPct` without `amountPct`, over it, or ≤ 0; take-profit not above the stop; the trigger's price/percent/trail/validFor/quote/wallet refusals, same wording), `trading.operator_required` (RPC), `trading.integrity` (a leg failed its seal: both legs are stopped), plus `trading.disabled`, `wallet.locked`, `trading.unsupported_chain`, `trading.token_not_found`. Approving or creating a bracket as the operator seals both legs and needs an unlocked vault. Events: every leg change emits the trigger's events **and** `trading.changed {reason: "bracket", bracketId}` + `trading.bracket.changed {bracket}` (the full `Bracket`). A fire emits `trading.trigger.fired {triggerId, trigger, fire}` as before; the `trigger` carries its `bracket` field so a notification can say *Protect ETH · take-profit fired*. ## Payload The trigger mime carries two more kinds: ```jsonc Envelope = { "version": 1, "kind": "trigger" | "triggers" | "bracket" | "brackets", "fetchedAt": iso, "warnings": [string], "request": { "kind": "get" | "list", "params": {…} } } // ↻ re-runs trading.bracket.<kind> { ...Envelope, "bracket": Bracket, "fire": Fire | undefined } // kind = "bracket" { ...Envelope, "brackets": [Bracket], // kind = "brackets": live first, then newest "totals": { "count": 2, "armed": 1, "awaiting": 1, "triggered": 0 } } Bracket = { "id": "brk_1a2b3c4d", "name": "Protect ETH", "kind": "sell" | "alert", "status": "awaiting_approval" | "armed" | "triggered" | "paused" | "done" | "stopped" | "rejected" | "expired", "statusReason": string | null, "chain": Chain, "wallet": Wallet, "token": Token, "quote": Token, "takeProfit": Trigger, // the tp leg, full trigger object (docs/triggers.md), with "bracket" set "stopLoss": Trigger, // the sl leg "lines": { "takeProfitUsd": number | null, // the tp line "stopLossUsd": number | null, // the sl line now: the threshold, or a trail's peak × (1 − trailPct/100) "trailPct": number | null, "fromPriceUsd": number | null, // the price at creation when a percent was given on either leg "takeProfitLabel": "over $4,560", "stopLossLabel": "under $3,420" | "10 % below peak" }, "action": { "kind": "sell" | "alert", "amountPct": number | null, "amount": Amount | null, "amountUsd": number | null, "tpPct": number | null, // partial take-profit share, when under amountPct "estimatedUsd": number | null, // what the stop-loss leg would move now (the whole size); terminal: what the filled leg moved "slippagePct": number | null, "needsApproval": boolean, "approvalThresholdUsd": number, "dailyCapUsd": number, "label": "sell 100 % of ETH → USDC" | "sell 50 % of ETH at take-profit, 100 % at stop → USDC" | "notify" }, "market": { "priceUsd": number | null, "armedPriceUsd": number | null, "checkedAt": iso | null, "balance": Amount | null, // the wallet's token balance now (sell); null for alert / terminal "upsidePct": number | null, // +20.3: % rise to the tp line; 0 when met "downsidePct": number | null, // −9.8: % fall to the sl line; 0 when met "positionPct": number | null, // where the price sits between the lines: 0 = at the stop, 100 = at the take-profit, clamped "rewardRisk": number | null, // upsidePct / |downsidePct|, one decimal; null when either is 0 or unknown "nearest": "tp" | "sl" | null // the leg closer to firing }, "fired": "tp" | "sl" | null, // the leg whose fire ended (or, partial tp, advanced) the bracket "result": Result | null, // the filled leg's result (docs/triggers.md), else null "validUntil": iso | null, "initiator": "agent" | "manual", "sessionKey": string | null, "createdAt": iso, "updatedAt": iso, "approvedAt": iso | null, "armedAt": iso | null, "expiresAt": iso | null } ``` `Trigger` (every trigger payload, legs or not) gains one field: ```jsonc "bracket": { "id": "brk_1a2b3c4d", "name": "Protect ETH", "leg": "tp" | "sl" } | null ``` USD `null` means unknown, never `0`. The `fires` of a bracket are read from its legs (`takeProfit.fires`, `stopLoss.fires`); the card merges them, newest first, tagged with the leg. ## RPC Agent-callable (create only proposes; reads are harmless): | method | params | returns | |---|---|---| | `trading.bracket.create` | `chainId`/`chain`, `token`, `takeProfit` (string or number), `stopLoss?` (string or number), `trailPct?`, `kind?` (`sell` default, `alert`), `quote?`, `amountPct?`, `amount?`, `amountUsd?`, `tpPct?`, `wallet?`, `slippagePct?`, `name?`, `validForSeconds?`, `sessionKey?` (operator only) | `bracket` payload | | `trading.bracket.get` | `bracketId` | `bracket` payload | | `trading.bracket.list` | `all?`, `wallet?` | `brackets` payload | Operator-only (`@_operator_only`): | method | params | returns | |---|---|---| | `trading.bracket.approve` | `bracketId` | payload (now `armed`) | | `trading.bracket.reject` | `bracketId`, `reason?` | payload | | `trading.bracket.pause` / `resume` / `stop` | `bracketId`, `reason?` (stop) | payload | | `trading.bracket.fire` | `bracketId`, `leg?` (`tp` / `sl`), `wait?` | payload + `fire` | Validation errors are `trading.bracket.invalid` naming the field; the helpers mirror `_trigger_*` in `rpc_trading.py`. The structural rules (`takeProfit` required; exactly one of `stopLoss` / `trailPct`; one size at most; `tpPct` only with `amountPct`; no size on `alert`) are checked in the RPC layer, the values against the market in the engine. ## CLI ``` agentos trade protect <token> --tp <price|pct%> (--sl <price|pct%> | --trail <pct>) [--pct 100 | --amount 0.05 | --usd 100] [--tp-pct 50] [--alert] [--quote USDC] [--chain base|robinhood] [--wallet ADDR|label] [--slippage 1] [--name "…"] [--for 7d] [--json] [--no-card] agentos trade bracket list [--all] [--wallet …] [--json] [--no-card] agentos trade bracket show <id> [--json] [--no-card] agentos trade bracket approve <id> [--json] [--no-card] agentos trade bracket reject <id> [--reason "…"] [--json] [--no-card] agentos trade bracket pause | resume <id> [--json] [--no-card] agentos trade bracket stop <id> [--reason "…"] [--json] [--no-card] agentos trade bracket fire <id> [--leg tp|sl] [--wait --wait-seconds N] [--json] [--no-card] ``` - `trade protect` is the creating verb (it reads as the user speaks: *protect my ETH*); `trade bracket …` manages one. `--tp` is required; exactly one of `--sl` / `--trail`; at most one of `--pct` / `--amount` / `--usd` (none → `--pct 100`); `--tp-pct` needs `--pct` (or the default) and must not exceed it; `--alert` takes no size. Checked in the CLI (exit 2) before the RPC. `--tp` accepts `4560`, `+20%`, `20%`; `--sl` accepts `3420`, `-10%`, `10%` (`parse_trigger_price` with `--above` / `--below` rules). - `--for` as for a trigger (`parse_every`, ≥ 60 s). - `--json` prints the payload and, unless `--no-card`, writes `trigger-cards/<bracket|brackets>-<slug>-<utc stamp>.json` (same folder, same 20-newest pruning, `_TRIGGER_CARD_FILE` accepts the two new prefixes) and prints `publish_artifact path=<file> mime=application/vnd.agentos.trigger+json` as the last line. - Human output: a Rich panel (name, kind, status, the two lines with the price now between them, upside / downside / reward:risk, size, balance, each leg's checks, recent fires of both legs, result) or a table for `list` (name, status, token, price now, `+20 % / −10 %`, size). - Exit codes as `trade trigger`: 2 for input / `trading.bracket.invalid` / `bad_state` / `not_found` / `trading.invalid` / `trading.token_not_found`; 1 for gateway errors. JSON errors on stderr under `--json`, never a card. - From an agent shell `protect` always answers `status: "awaiting_approval"`; the agent says the card has one **Approve & arm** button for both legs and never approves itself. ## Rendering Shared renderer: `frontend/src/views/chat/transcript/trigger.ts`. `trigger.ts` handles the two new kinds in the same module (one mime, one mounter, one registration): `TriggerKind` becomes `'trigger' | 'triggers' | 'bracket' | 'brackets'`, `normalizeTriggerPayload` returns a `BracketOnePayload` / `BracketListPayload`, `triggerReadMethod` maps a bracket request to `trading.bracket.<kind>`, and `trading.bracket.changed` refreshes mounted cards of the affected bracket (the mounter gains `bracketChanged(payload)`, wired in `useTranscript.ts` next to `triggerChanged`). Controls reuse `TriggerActions.call` with the `trading.bracket.<op>` methods; no new option on the transcript hook. ### `kind = "bracket"` — the card Root `article.trigger-card[data-trigger-kind=bracket][data-trigger-action=sell|alert][data-trigger-status=…][data-trigger-chain=…][data-trigger-layout=wide|narrow][data-trigger-nearest=tp|sl]`. Every hook below is **exact**: the desktop skins these selectors blind. 1. **Header** `.trigger-card__head`: name, chain pill, status pill `.trigger-pill[data-status]` as a trigger's. Kind glyph via `data-trigger-action` (▼▲ pair for sell, 🔔 for alert, CSS only). 2. **Hero** `.trigger-card__hero`: `sell 100 % of ETH · take profit over $4,560 · stop under $3,420` (alert: `notify when ETH is over $4,560 or under $3,420`); under it `.trigger-card__now`: `ETH $3,790 · +20.3 % to take-profit · −9.8 % to stop · checked 12 s ago`, or `armed, waiting for a price`, `take-profit fires after 1 more check`, `awaiting approval`, `done · take-profit: sold 0.05 ETH at $4,560`, `on hold · stop-loss order open`. 3. **Range gauge** `.trigger-gauge[data-trigger-gauge=range]`: one rail `.trigger-gauge__line`, the stop line as a tick at the left `.trigger-gauge__tick[data-leg=sl]`, the take-profit line as a tick at the right `.trigger-gauge__tick[data-leg=tp]`, the price as the dot `.trigger-gauge__dot`, the span between the ticks as `.trigger-gauge__zone[data-zone=bracket]`; labels `.trigger-gauge__label[data-leg=sl|tp]` and `.trigger-gauge__label[data-leg=now]`. Pure SVG, `data-trigger-dist` on the root carries the nearest leg's signed distance for the skin to tint (near = amber). 4. **Legs** `.bracket-legs`: two rows `.bracket-leg[data-leg=tp|sl][data-status=…]`: leg word `.bracket-leg__word` (*Take-profit* / *Stop-loss* / *Trailing stop*; an alert's *Ceiling* / *Floor*), line `.bracket-leg__line` (`over $4,560`), state `.bracket-leg__state` (`armed · 1 of 2 checks`, `on hold`, `stopped · take-profit filled`, `done · sold …`). A leg that is over (`done` / `stopped` / `rejected` / `expired`) has no distance: the now-line says what happened (`take-profit filled · −9.8 % to stop`), the list row prints `—` for it, it is never `data-trigger-nearest`, and reward : risk is `—`. 5. **Facts** `.trigger-card__facts` (2×2): *size* (`100 % · ≈ $189` / `50 % at take-profit, 100 % at stop`; the `≈ $…` part sits on its own line in `.trigger-fact__sub`, and a fact whose value is over 18 characters carries `data-trigger-fact-span="2"` so the skin gives it two columns and nothing ever overflows a column), *balance*, *reward : risk* (`2.1 : 1` with `.trigger-fact__rr`), *on fire* (`trades at once` / `waits for you · over $100`; absent on an alert, whose size already says `notify only`); *valid until* joins when set. 6. **Fires** `.trigger-fires`: both legs' fires merged, newest first, ≤ 5, each row prefixed with the leg word (`take-profit #1 · 2 m ago · filled …`). Row actions on the `brackets` (and `triggers`) list card recount the totals line from the rows after every swap. 7. **Actions** `.trigger-actions` (only with `canWrite`): `awaiting_approval`: **Approve & arm** · Reject; `armed`: Pause · Sell now (alert: Notify now) · Stop; `paused`: Resume · Sell now · Stop; `triggered`: Stop; terminal: none. Buttons carry `data-trigger-op=approve|reject|pause|resume|fire|stop` and `data-bracket-id`; a click calls `trading.bracket.<op>`, disables the row in flight, swaps in the returned payload; `fire` passes the fire's `orderId` to `actions.onOrder`. Sell now and Stop take a confirming second click (`data-trigger-confirm`). Errors in `.trigger-actions__error`. 8. **Warnings** `.trigger-card__warnings`, **Footer** `.trigger-card__foot`: `brk_1a2b3c4d · Key main (0x89e0…da97) · as of <relative>` · ↻ · copy id. Live state as for a trigger (`data-trigger-stale="checking"`, re-read through `trading.bracket.get`, per-id cache fed by reads, action responses and `trading.bracket.changed`). ### `kind = "brackets"` — the list `article.trigger-card[data-trigger-kind=brackets]`: header `Brackets · 2`, totals, one row per bracket `.trigger-row[data-bracket-id]`: status dot, name, `sell 100 % ETH · $3,420 – $4,560`, `ETH $3,790 · +20 % / −10 %`, compact actions. Empty → `No brackets yet.` ### A leg's own card A trigger card whose `trigger.bracket` is set shows a line in the header, `.trigger-card__group` (`take-profit leg of Protect ETH · brk_1a2b3c4d`), and **no** `.trigger-actions` (leg writes are refused). ### Web vs desktop As for triggers: the web console shows a read-only card (`frontend/src/web/features/chat/cards/TradingCards.tsx`); the desktop renders the full card and styles it in `desktop/src/renderer/src/views/chat/chat.css` (range gauge: stop tick red-tinted, take-profit tick green-tinted, zone faint; legs strip as two mono rows). `canWrite` is true only on the desk. ## Desktop desk - **Types** (`views/trading/types.ts`): `Bracket`, `BracketPayload`, `BracketListPayload`, `BracketLeg = 'tp' | 'sl'`; `Trigger.bracket`. - **Store** (`stores/trading.ts`): `useBrackets(all, enabled)` on `trading.bracket.list`, key `['trading', 'bracket', all ? 'all' : 'live']`, refreshed by `trading.changed` and `trading.bracket.changed` (add to `TRADING_EVENTS`); `useBracketActions()` → approve / reject / pause / resume / stop / fire(bracket, leg?) with toasts (`trading.bracket.toast.*`), Touch ID through the store's `gatedCall` (`TRADING_WRITE_GATES`: approve, fire and resume ask; the ask comes from `bracketTouchId(bracket, op)` in `touch-id.ts` and names both lines and the size). - **Approvals region**: pending brackets above pending triggers as a `BracketCard` (name, the two lines, size, wallet, expiry, both legs' warnings) with **Approve & arm** / Reject (one decision for both legs). - **Missions panel** (`missions.ts`, `MissionControls.tsx`): a bracket is one row: name, state word (`Awaiting approval`, `Armed · ETH $3,790 · +20 % / −10 %`, `Take-profit · 1 of 2 checks`, `Triggered · stop-loss order open`, `Paused`, `Done · take-profit`), controls Pause / Resume, Sell now (two-click; alert: Notify now), Stop (two-click). Finished brackets stay 1 h. Legs never appear as rows of their own. - **Status strip**: brackets count into the trigger chip (`Triggers ×3` counts a bracket once); `Trigger · near` when either line is within 1 %; `Trigger · fired` while a leg is `triggered`. - **Notifications** (`notifications/logic.ts`): a `trading.trigger.fired` whose `trigger.bracket` is set is titled `Protect ETH · take-profit fired` (`notify.bracket.fired.title`), subtitle as a trigger's; an alert leg: `Watch ETH · over $4,560`. - **Desk ledger** (`ledger.ts`): `agentos trade protect …` → row kind `bracket_create`, title `Protect · ETH · +20 % / −10 %` (or the prices); `trade bracket <sub>` → `bracket_list|bracket_approve|…`; the `trigger-cards/bracket-…` marker is a bracket card. - **Chat wiring** (`ChatView.tsx`): every card write goes through the store's `gatedCall`, so a bracket card's `approve` / `fire` / `resume` ask exactly as the desk's do (the bracket is read first via `bracketAskById` to name it). - **Desk prompt** (`agent.ts`, bump `TRADING_AGENT_VERSION`): a **Brackets** section. A request for both an exit above and an exit below on a position — "protect my ETH", "protect the position", "take profit 20 %, stop loss 10 %", "take profit at 4,500 and stop at 3,400", "sell half at +20 %, stop at −10 %", "tell me if ETH leaves 3,400–4,500" — is **one bracket**, never two triggers: `agentos trade protect ETH --tp +20% --sl -10% --json` (default `--pct 100`); "take profit on half" → `--tp-pct 50`; "trailing" on the stop → `--trail 10`; a range alert → `--alert`. From an agent the result is `awaiting_approval`: report the card has one **Approve & arm** for both legs, give the id (`brk_…`), stop. A single-sided request stays a trigger. "how are my brackets" → `bracket list --json`, one line. ## Docs and skills `docs/cli.md` (`trade protect` / `trade bracket` beside `trade trigger`), the bundled `agentos` skill `SKILL.md` (CLI surface lines), the `wallet-trading` skill `SKILL.md` (the reading rules above, the command lines), and `docs/triggers.md` (scope line: OCO pairs now live in `brackets.md`; `Trigger.bracket`; `list` excludes legs; leg writes refused). ## Tests - **Engine** (`tests/test_trading/test_brackets.py`, offline, the `World` of `test_triggers.py`): create as operator arms both / as agent parks both in one card; default and given names; percent lines resolve; tp not above sl refused; `tpPct` rules; alert bracket; `trigger.list` hides legs; leg writes refused; status precedence (`bracket_status`); tp claim holds sl; tp filled → sl stopped, bracket done, result from the tp leg; sl filled → tp stopped; partial tp → sl released, bracket armed with the reason; failed fire releases the hold; parked order rejected → leg stopped, sibling released; expired waiting → leg paused, sibling released; skipped → both paused; a user-paused sibling is not released; fire now nearest / given leg; pause / resume / stop / approve / reject act on both; validUntil expires both; reconcile after restart; migration v8 → v9 keeps triggers; fixtures `tests/fixtures/trigger_cards/{bracket-armed, bracket-awaiting,bracket-done,bracket-alert,brackets,brackets-empty}.json` (regenerate with `AGENTOS_REGEN_TRIGGER_FIXTURES=1`). - **RPC** (`tests/test_gateway/test_rpc_trading_brackets.py`): registered; agent create/get/list, `awaiting_approval`; every write `trading.operator_required` for an agent; validation codes; approve → armed. - **CLI** (`tests/test_cli/test_trade_protect_cmd.py`): flag rules, default size, `--tp-pct`, `--for`, marker last line, pruning accepts the new prefixes, JSON errors on stderr, exit codes, params sent. - **Frontend** (`trigger.test.ts` or `bracket.test.ts`): category and normalisation of the two kinds, each status layout, hero/now text, range gauge geometry (dot between the ticks, clamped outside), legs strip, merged fires, actions hidden without `canWrite`, action → RPC → payload swap, `bracketChanged` refresh, a leg's card shows the group line and no actions, CSS contract entries. - **Desktop**: `BracketCard` approve/reject, Missions rows, `ledger.ts` parsing, notification title, store hooks, status chip, CSS skin test. - **Live** (dust wallet, Base, ≈ $0.10 + gas): `trade protect USDC --tp 0.5 --sl 0.1 --usd 0.04 --quote ETH --json` → the take-profit leg fires within two ticks and fills, the stop-loss leg is `stopped · take-profit filled`, the bracket `done`; `trade protect ETH --tp +20% --sl -10% --pct 1` stays armed with `upsidePct ≈ 20`, `downsidePct ≈ −10`, `positionPct ≈ 33`, survives pause / resume, and is stopped; `trade protect USDC --tp 0.5 --sl 0.1 --alert` fires the alert leg and is `done`; `trade protect USDC --tp 0.5 --sl 0.1 --pct 1 --tp-pct 0.5 --quote ETH` fills the take-profit and leaves the stop-loss armed for the rest. --- # Stock Token markets > Source: https://useagentos.dev/docs/core/markets Artifact type: `application/vnd.agentos.markets+json`. *Which tokens trade against NVDA?* On Robinhood Chain a Stock Token is not only something you buy: it is the **quote asset** for hundreds of other tokens. Launchpads (Bankr, long.xyz, Pons V2) let a memecoin launch *priced in NVDA*, and those pools are the bulk of the stock's on-chain market — measured 2026-10-06, 172 of the 200 NVDA pools GeckoTerminal lists have NVDA on the quote side, and the deepest NVDA pool of all is AI/NVDA (Artificial Inu, $4.7 M), bigger than NVDA/USDG on Uniswap v3. The **markets** read answers that question for one token: every pool it is in, on every DEX the chain has, split into *priced in NVDA* (NVDA is the quote) and *NVDA priced in* (NVDA is the base: NVDA/USDG, NVDA/WETH), with TVL, 24 h volume, price, age and a Swap button on each row. This file is the contract between the engine, the gateway, the CLI, the shared chat renderer and the desktop. Change it before changing any of them. Whatever it does not say, `docs/lp-cards.md` says (the card plumbing is the same). Chains: Robinhood Chain (4663) first; Base (8453) works the same way (the sources index both). Not in scope: swapping *through a named pool* (a swap from a row is a best-route swap, see "Swap"), LP writes, on-chain pool enumeration from logs (the public Robinhood node caps `eth_getLogs` at 10 M blocks per call and a full scan took longer than 15 minutes). ## Vocabulary | word | meaning | |---|---| | **token** | the token the user asked about (`NVDA`); the card is about it | | **pool** | one liquidity pool on one DEX holding the token and one other token | | **counterparty** | the other token in the pool (`AI` in `AI/NVDA`) | | **side** | `quote` when the token is the pool's quote asset (the counterparty is priced in it: `AI/NVDA`); `base` when the token is the base (`NVDA/USDG`) | | **priced in** | the `quote` section: *tokens priced in NVDA* | | **lookalike** | a counterparty that borrows a listed company's symbol or name but is not a Robinhood Stock Token (`memestock TSLA`, ` NVIDIA Robinhood Token ` without the bullet) | | **via Uniswap** | the pool is on Uniswap v2/v3/v4, so the Trading API's best route can use it | ## Prerequisites this feature ships with Today the desk cannot swap a Stock Token on Robinhood Chain at all, so a Swap button would be decoration. Two engine changes land with the feature: 1. **Universal Router pins** (`trading/uniswap.py`, `UNIVERSAL_ROUTERS`). The Trading API now sends swaps to Universal Router **v2.1.2**; the table pinned only Base's v2.0 and nothing for 4663, so the engine refused every Uniswap swap on Robinhood Chain and, since the API moved, on Base too. The table becomes a per-chain **set** of verified routers: | chain | routers (lowercase) | source | |---|---|---| | 8453 | `0x6ff5693b99212da76ad316178a184ab56d299b43` (v2.0), `0xd6145b2d3f379919e8cdeda7b97e37c4b2ca9c40` (v2.1.2) | `Uniswap/universal-router` `deploy-addresses/base.json` | | 4663 | `0x8876789976decbfcbbbe364623c63652db8c0904` (v2.1.1), `0x204faca1764b154221e35c0d20abb3c525710498` (v2.1.2) | `deploy-addresses/robinhood.json`; `/v1/swap` answered `to = 0x204F…` on 2026-10-06 | `trusted_targets` returns the chain's set plus the proxy; a chain with no entry still gets the empty set (refuse, never guess). Verified 2026-10-06: both 4663 addresses hold code (24 380 and 24 546 bytes). 2. **Stock Token routing** (`trading/service.py`, `trading/aggregator.py`). 0x refuses the Stock Tokens for legal reasons (`trading.token_not_tradeable`); Uniswap trades them (checked: ETH→AAPL via a v4 0.08 % pool, NVDA→AI, NVDA→ORBIO). The AgentOS DEX carries Uniswap as a second liquidity source, asked for with `source=uniswap` on `/v1/quote` and executed through the same Router. So: - `quote`, `swap`, and every path that quotes for an order (DCA runs, trigger fires, bracket legs, the re-quote at execution) name that source when the configured provider is the aggregator and either token is a tokenized stock (`stock_token`). No Uniswap API key is needed, and the quote dict and the order row keep `provider: "aggregator"`. - Every other pair is asked the way it always was, with no `source`, and answered by 0x. - If 0x still answers `token_not_tradeable` for a pair the flag missed, the engine asks the Uniswap source once for that quote. - If the Uniswap source cannot take the pair (the gateway's `SOURCE_UNAVAILABLE`, or a gateway that predates the source) and a Uniswap key is configured, the quote is retried through the Uniswap provider and the row records `provider: "uniswap"`. Without a key the error is raised with its message extended: *"The AgentOS DEX's Uniswap source could not take this pair. Retry later, or add a Uniswap API key (`agentos config set trading.uniswap_api_key <key>`) to route through Uniswap directly"* — the exact wording lives in the engine, the desktop shows it verbatim. - A configured `trading.provider = "uniswap"` is left alone. 3. **Stock Token detection** (`trading/prices.py`, `trading/token_lists.py`). A row of a chain's stock list (`robinhood_stock_tokens.json`, `base_stock_tokens.json` in the AgentOS [token lists](https://github.com/use-agent-os/agent-os-token-list), tagged `stock`) is a Stock Token. The ledger's own token rows keep no tag, so a Robinhood Stock Token is also known by its name: one helper, `is_stock_token_name(name)`, matches `… • Robinhood Token` and the truncated forms an older registry stored (`… • Robinhood Toke`, `… • Robinhood T`: a bullet followed by any prefix of `Robinhood Token`, the regexes of `robinhood-chain-stocks/scripts/chain_stocks.py`). A name without the bullet is **not** a Stock Token however it is spelt (` NVIDIA Robinhood Token ` is a lookalike with a $649 k pool). ## Sources, and why in this order | source | what it gives | limits | |---|---|---| | **GeckoTerminal** `GET /api/v2/networks/{robinhood\|base}/tokens/{address}/pools?page=N&include=base_token,quote_token,dex&sort=h24_volume_usd_desc` | the only listing that returns pools on **both** sides of the token; 20 per page, up to page 10; per pool: `address`, `name` (`NVDA / USDG 0.01%` — the fee is only in the name), `reserve_in_usd`, `volume_usd.h24`, `price_change_percentage.h24`, `transactions.h24.{buys,sells}`, `pool_created_at`, `base_token_price_usd`, `quote_token_price_usd`, `base_token_price_quote_token`, `quote_token_price_base_token`, relationships `base_token`, `quote_token` (`robinhood_0x…`), `dex` (`uniswap-v4-robinhood`, `bankr-robinhood`, `pons-v2-dex`, `ramses-v3-robinhood` …); `included[]` carries each token's `name`, `symbol`, `decimals`, `image_url` | **30 requests / minute per IP**; 429 seen during research. Header `accept: application/json;version=20230302` | | **DexScreener** `GET /token-pairs/v1/{robinhood\|base}/{address}` | enrichment for pools GeckoTerminal also has: `labels` (`v2`/`v3`/`v4`), `liquidity.usd`, `volume.h24`, `url`; matched on `pairAddress` (lowercase; a v4 pair address is the poolId) | 30 pairs, **base side only** — it never lists `AI/NVDA` for NVDA; 300 / min | | **chain** | for a Stock Token: the Chainlink feed price (`oracle`), `oraclePaused()`; ported from `chain_stocks.py` (feed directory `https://reference-data-directory.vercel.app/feeds-robinhood-mainnet.json`, `latestRoundData`, 8 decimals; `uiMultiplier()` `0xa60bf13d`; `oraclePaused()` `0x7706ba52`) | `null` on any failure, never an error | DexScreener alone was the old plan; it is wrong for this feature because the pools the user asks about (`AI/NVDA`, `ORBIO/NVDA`) have the token on the quote side. The engine's own V4 discovery (`lp.discover_pools`) finds 8 NVDA pools, all against USDG/ETH, for the same reason. ### Engine behaviour `trading/markets.py`: ```python async def markets(service, *, chain, target, side="all", min_tvl_usd=10_000.0, limit=50, lookalikes=False, deep=False) -> dict ``` - `target` resolves through `service.resolve_token` (an address, `ETH`, or a symbol; a symbol that matches one Stock Token picks it over the community tokens of the same symbol — the existing rule). - Pages GeckoTerminal until `limit` rows survive the filters, a page comes back short, or the page cap: **5 pages** (100 pools) by default, **10** with `deep`. Pages are read in **bursts of up to 5 concurrent requests** (a page GeckoTerminal's edge has not cached takes 11–13 s, a cached one 0.2 s, measured 2026-10-06; one page at a time cost 40 s per token) with a **120 s cache per `(chain, token)`** of the raw pages, so a refresh or a second section costs nothing. Pages are kept as a contiguous prefix: a 429 drops that page and every later one; what was read is returned with `partial: true` and the warning *"GeckoTerminal rate limit: showing the first N pools"*. No pages at all (network, 5xx) → `trading.markets.unavailable`. `partial` is also set when the page cap stopped a read that had more pools (warning points at `deep`). GeckoTerminal's limit bites earlier than its stated 30/min (a 429 after ~11 requests in 90 s was seen): the first 429 inside a burst is retried once after 15 s; a second 429 ends the read (`rateLimited: true`). An uncached page was measured at up to 18.5 s (`cf-cache-status: MISS`), so the per-page timeout is **60 s**, and a page that timed out inside a burst is retried **once** after the burst before the read gives up on it. Clients show *"A first read of a token can take up to a minute"* while loading. - One DexScreener call enriches matches; its failure is a warning. - Rows below `min_tvl_usd` are dropped and counted (`counts.belowMinTvl`). Lookalike counterparties are dropped and counted unless `lookalikes` (`counts.hiddenLookalikes`). A **lookalike** is a counterparty whose symbol (case-insensitive) or name (minus the suffix) matches a Stock Token in the chain's token list but whose address is not that token's. - `side` filters to one section; `all` returns both. Rows are sorted by `tvlUsd` descending within each section. - Counterparty metadata comes from `included[]` first, then `prices.known_token` for `verified`/`stockToken`. - `launcher` labels a pool by its DEX id: `bankr-*` → `Bankr`, `pons-*` → `Pons`, `clanker-*` → `Clanker`, `long-*`/`virtuals-*` as named; the table lives in `markets.py` and is best-effort (`null` otherwise). - `viaUniswap` is `dex.id` starting with `uniswap-`. - `feePct` is parsed from the trailing `N%` of GeckoTerminal's pool name (`"0.01%"` → `0.01`); `null` when absent. - Prices: for `side = quote`, `priceUsd` is the **counterparty's** USD price and `priceInToken` the counterparty priced in the token. For `side = base`, `priceUsd` is the **token's** USD price in that pool and `priceInToken` is the token priced in the counterparty. `priceInToken` is computed as the **ratio of the two USD prices** GeckoTerminal gives for the pool (`base_token_price_usd`, `quote_token_price_usd`) — its `base_token_price_quote_token` field was measured 45–77 % off real quotes on launchpad pools (2026-10-06) and is used only when one USD price is missing. Strings from the source become JSON numbers; unknown → `null`, never `0`. - A counterparty at the zero address is the chain's native coin: `{address: "0x000…0", symbol: "ETH", name: "Ether", native: true}`, never "WETH". `dex.version` falls back to `"v4"` when the pool address is 32 bytes (a v4 poolId) and to the version in the DEX id (`uniswap-v3-…`). - `token.oracle` is read only on 4663 and only when `token.stockToken`; `premiumPct` on a `base` row is `(priceUsd / oracle.usd - 1) * 100` when both exist, else `null` (never on `quote` rows: a memecoin has no oracle). ## Payload ```jsonc { "version": 1, "kind": "markets", "chain": { "id": 4663, "key": "robinhood", "name": "Robinhood Chain", "explorer": "https://robin.etherscan.io" }, "fetchedAt": "2026-10-06T04:12:00Z", "partial": false, // paging stopped early (rate limit / cap): the card shows a badge "warnings": ["string"], "token": { "address": "0xd0601ce157db5bdc3162bbac2a2c8af5320d9eec", "symbol": "NVDA", "name": "NVIDIA • Robinhood Token", "decimals": 18, "logoUrl": "https://…" | null, "verified": true, "stockToken": true, "priceUsd": 240.30 | null, // from the engine's price feed (DexScreener best pair) "oracle": { "usd": 239.74, "updatedAt": "2026-10-05T20:38:49Z", "ageSeconds": 47269, "stale": false, "paused": false } | null }, "counts": { "scanned": 100, "shown": 34, "belowMinTvl": 61, "hiddenLookalikes": 5, "limited": 0, // rows above the floor that `limit` cut (the counts line says "· 12 more over the limit") "pages": 5, "pageCap": 5, "pageCapHit": false, // the page cap, not `limit`, ended a read that had more pools: *Deeper* is offered when true (and not yet `deep`) "rateLimited": false // a 429 cut the read short: *Deeper* (or *Read again*) is offered again even when `deep`, so the user can retry after a minute }, "sections": { "quote": [ Pool, … ], // "Priced in NVDA" — empty array when side=base "base": [ Pool, … ] // "NVDA priced in" — empty array when side=quote }, "request": { "kind": "markets", "params": { "target": "0xd060…", "chainId": 4663, "side": "all", "minTvlUsd": 10000, "limit": 50, "lookalikes": false, "deep": false } } } ``` `Pool`: ```jsonc { "poolAddress": "0xcbdfea90…ce27", // GeckoTerminal address; for v4 the poolId "pair": "AI/NVDA", // counterparty first on quote rows, token first on base rows "side": "quote" | "base", "dex": { "id": "bankr-robinhood", "label": "Bankr", "version": "v4" | "v3" | "v2" | null }, "launcher": "Bankr" | null, "viaUniswap": false, "feePct": 1.0 | null, "counterparty": { "address": "0x2e8c…1e18", "symbol": "AI", "name": "Artificial Inu", "decimals": 18, "logoUrl": null, "verified": false, "stockToken": false, "lookalike": false }, "tvlUsd": 4732293.0 | null, "volume24hUsd": 806473.0 | null, "txns24h": { "buys": 812, "sells": 790 } | null, "priceUsd": 0.1131 | null, // see "Prices" above "priceInToken": 0.000471 | null, "change24hPct": -3.2 | null, "premiumPct": null, // base rows of a Stock Token only; rounded to 2 decimals, never negative zero (|x| < 0.005 → 0.0) "createdAt": "2026-07-25T00:52:36Z" | null, "url": "https://www.geckoterminal.com/robinhood/pools/0xcbdf…" , "swap": { "chainId": 4663, "tokenIn": "0xd060…", "tokenOut": "0x2e8c…" } // what the Swap button prefills: sell the token, buy the counterparty } ``` Every row has `swap`; the renderer decides whether to show the button (see "Swap"). `swap.tokenIn` is the token on `quote` rows (spend NVDA, get AI) and on `base` rows too (sell NVDA for USDG); the desktop's swap panel has a flip control for the other direction. ## Gateway `trading.markets` — read-only, allowed from an agent. | param | type | default | |---|---|---| | `target` | string, required | symbol, address or `ETH` (also accepts `token`) | | `chainId` | 8453 \| 4663 | 4663 | | `side` | `all` \| `quote` \| `base` | `all` | | `minTvlUsd` | number ≥ 0 | 10000 | | `limit` | 1–200 | 50 | | `lookalikes` | bool | false | | `deep` | bool | false | Errors: `trading.invalid` (bad params, ambiguous symbol — with `details.candidates` as `tokens.resolve` does), `trading.not_found` (unknown token), `trading.markets.unavailable` (no page could be read). Registered in `gateway/rpc_trading.py` next to `trading.lp.*`, with the same `_with_request` echo. ## CLI ``` agentos trade markets <token> [--chain base|robinhood] [--side all|quote|base] [--min-tvl 10000] [--limit 50] [--lookalikes] [--deep] [--json] [--no-card] ``` Default chain **robinhood** (the only `trade` command with that default — say so in `--help`). Human output: the token line (symbol, price, oracle and premium when known), then one table per section with columns `PAIR DEX TVL VOL 24H PRICE IN NVDA AGE FLAGS` (flags: `uni`, `lookalike`, `stock`), then one line of counts (*34 of 100 pools shown · 61 under $10k · 5 lookalikes hidden · 12 more over the limit · partial*). Prices are printed with at most 6 significant digits and the table folds rather than truncates in an 80-column terminal. An ambiguous symbol lists its candidates (symbol, name, address) in human mode too. With `--json`: JSON on stdout, the card written to `markets-cards/markets-<symbol>-<utc stamp>.json` (20 newest kept) and the `publish_artifact path=… mime=application/vnd.agentos.markets+json` line, exactly as `docs/lp-cards.md` describes for LP cards. Errors are the `{"error": {...}}` envelope on stderr, exit 1, no card. ## Chat card Shared renderer: `frontend/src/views/chat/transcript/markets.ts`. Mounted by `createMarketsMounter` from `useTranscript.ts` beside `createLpMounter`. One card per payload: - Head: token logo, symbol, name, chain pill, `priceUsd`, and for a Stock Token the oracle price with a `stale`/`paused` badge when set. - Two sections in this order, each with a title and a count: **Priced in NVDA** (`sections.quote`) and **NVDA priced in** (`sections.base`). An empty section shows one line (*No pools against NVDA above $10k*). - A row: pair, DEX label + version pill, launcher pill when set, TVL, 24 h volume, price (USD) and price in token, 24 h change coloured, age (`3d`, `2mo`), flags. Lookalike rows (only when requested) wear a warning pill. `premiumPct` shows on base rows as `+0.4 % vs oracle`. - Footer: counts line (including `limited` when > 0), `partial` badge, ↻ refresh (re-runs `trading.markets` with `request.params`, like LP cards), *Show lookalikes* (only when `hiddenLookalikes` > 0 and the read did not include them) and *Deeper* (only when `counts.pageCapHit` and not `deep`) links that re-run with `lookalikes: true` / `deep: true`. - The launcher pill is hidden when it would repeat the DEX label (Bankr on Bankr). A lookalike row (and any row whose counterparty symbol equals the token's) shows the counterparty's **name** after the pair so two "GME/GME" rows can be told apart. - **Swap** button per row, rendered only when the mounter is given an `onSwap(swap: { chainId, tokenIn, tokenOut })` dep; the web console passes none (no button), the desktop passes one. Rows are capped at 40 per section with *+N more* that expands in place. Narrow cards (under ~480 px): the **pair column is never starved** — it keeps at least 9 characters before any other column shrinks; the Price column gives way first, then Vol and Age disappear (≤ 420 px), the venue pills wrap as a group under the pair, and "Uniswap" never breaks mid-word. A premium of ±0.0 % is shown as `0.0%` with the flat tone. ### CSS hooks Verbatim; the desktop skins these, the web styles them. ``` .mk-card the card root; data-chain="4663"; data-partial="true" when partial .mk-head .mk-logo .mk-symbol .mk-name .mk-chain .mk-price .mk-oracle .mk-oracle-badge[data-tone=warn|danger] .mk-section[data-side=quote|base] .mk-section-title .mk-section-count .mk-empty .mk-rows the row list .mk-row[data-lookalike=true] one pool .mk-pair .mk-cp-name (the counterparty's name on lookalike / same-symbol rows) .mk-dex .mk-version .mk-launcher .mk-tvl .mk-vol .mk-px .mk-px-in .mk-change[data-tone=up|down|flat] .mk-age .mk-flags .mk-flag[data-kind=uni|stock|lookalike] .mk-premium[data-tone=up|down|flat] .mk-swap the Swap button (absent when no onSwap) .mk-more the "+N more" control .mk-foot .mk-counts .mk-partial .mk-refresh .mk-link[data-action=lookalikes|deep|again] ``` The exact nesting is documented verbatim in `MARKETS_DOM` (exported from `markets.ts`); the desktop skin is tested against the real DOM. Text and numbers use the renderer's existing money/percent formatters (`formatMoney`, compact for ≥ $100k: `$4.7M`). ## Desktop - **BOOK tab `markets`** (`stores/trading-ui.ts` `BookTab` gains `'markets'`; icon `Layers`), placed after `swap`. **Full desk** (`TradingView.tsx`) gains the same tab after `holdings`. - `views/trading/Markets.tsx`: a search field (symbol or address; the current chain from the desk's chain control, defaulting to Robinhood Chain when the user types a known Stock Token symbol on Base — i.e. the component looks the symbol up with `useTokenSearch` on both chains and prefers the verified Stock Token; among several verified exact matches on the chain it prefers a Stock Token, then the highest liquidity, and shows which token it picked — it must never silently take the first match; the *N matches* menu is wide enough to show each token's full name, liquidity and short address), filters (*Min TVL* segmented `$1k / $10k / $100k`, *Lookalikes* toggle), the two sections as lists, the counts footer, *Deeper* control. Rows match the card's content but are built in the desktop's own markup and `.mac-*` / `trd-*` vocabulary (`desktop-shares-logic-not-ui`): share the **logic** (`useMarkets` hook, formatters, lookalike/launcher helpers exported from the renderer module) and nothing presentational. Loading, empty, rate-limited (`partial`) and error states are drawn. At the BOOK's minimum width (300 px) the tab icons keep their size (the bar scrolls or wraps, icons never shrink), the price-in-token cell wraps rather than truncating to "0.0…", and the premium never overlaps the Age column; pair text that must truncate does so with an ellipsis, never mid-glyph; the tab strip shows it scrolls (an edge fade) when tabs are hidden. - `useMarkets(params, enabled)` in `stores/trading.ts` → `rpc.call('trading.markets', …)`, `staleTime` 60 s, keyed by every param. - **Swap from anywhere**: `stores/trading-ui.ts` gains `swapRequest: { chainId, tokenIn: Token, tokenOut: Token, seq } | null` and `requestSwap(req)`. `Book` and `TradingView` subscribe and turn it into their `SwapPrefill` (+ `setTab('swap')` / `setBookTab('swap')`). The Markets row's Swap button, the chat card's `onSwap` (wired in the desktop's transcript deps), and the existing Holdings Swap button all go through `requestSwap`; the Holdings path keeps its behaviour. - A Holdings row of a Stock Token gets a **Markets** action next to Swap that opens the tab with that token. - i18n: `trading.markets.*` keys in `i18n/en/trading.ts` (and the other locales the file set has, English fallback is fine). - Desk agent (`desk/agent.ts`): the allowlist admits `agentos trade markets`; TOOLS.md teaches: *"pairs of X", "what trades against X", "markets for X", "tokens priced in X", "pools of X on every DEX"* → `agentos trade markets X --chain robinhood --json`; the card is the answer; a liquidity question about **one** pool stays `lp pool` — but a launchpad pool (Bankr, Pons: `lp pool` answers `trading.lp.pool_key_unknown`) is answered with the markets card of its quote token, never with a different pool's card. `TRADING_AGENT_VERSION` bumps. - Desktop skin for `.mk-*` in `views/chat/chat.css` next to `.lp-card`, distinct from the web look. ## Docs to update in the same change `docs/cli.md` (the `trade markets` command, and the Stock Token paragraph: they now route through Uniswap), `src/agentos/skills/bundled/agentos/SKILL.md` (the `trade` command list **and** its `trade` row that said the 29 stocks "cannot be routed at all"), `src/agentos/skills/bundled/wallet-trading/SKILL.md` and `src/agentos/skills/bundled/robinhood-agentic-trading/SKILL.md` (same sentence: Stock Tokens route through Uniswap when a key is configured; the aggregator alone refuses them), `docs/features/trading.md` (the aggregator paragraph quoted above), `CHANGELOG.md` under *Unreleased / Added*. ## Verified facts the tests pin - Router sets above; `trusted_targets` on 4663 contains `0x204f…`. - `is_stock_token_name`: `"NVIDIA • Robinhood Token"` → true, `"International Business Machines • Robinhood Toke"` → true, `" NVIDIA Robinhood Token "` → false, `"memestock TSLA"` → false. - Provider routing: aggregator configured + Stock Token on either side + Uniswap key → the quote carries `provider: "uniswap"`; no key → the `token_not_tradeable` error carries the Uniswap hint. - Markets: a recorded GeckoTerminal page set for NVDA (fixture) yields `AI/NVDA` in `sections.quote` with `dex.label = "Bankr"`, `NVDA/USDG` in `sections.base` with `feePct = 0.01`, `viaUniswap = true`; a 429 on page 3 gives `partial: true` and the warning; lookalike filtering hides a counterparty named `NVDA` whose address differs from the Stock Token. --- # Pilot Router > Source: https://useagentos.dev/docs/core/features/pilot-router Pilot Router is AgentOS's local model-routing layer. It helps the agent choose an appropriate model tier for each turn so routine work does not always run on the most expensive model. Use this page when you want to enable routing, understand what it changes, or decide whether a fixed provider/model is better for a specific run. **Naming.** "Pilot Router" names the whole routing layer — every strategy below runs inside it. `pilot-v1` is one specific strategy: the default local ML model that ships with Pilot Router. Wire identifiers keep their original names (the `[agentos_router]` config section and the `AGENTOS_ROUTER_` env prefix). ## Why Use It Pilot Router is useful when you want: - lower cost for simple chat, edits, summaries, and routine tool work; - stronger models reserved for hard reasoning, recovery, and long tasks; - one AgentOS workflow that can route across provider profiles; - local routing decisions without sending prompts to a separate external classifier just to choose the model (the default `pilot-v1` strategy; the opt-in `jev` strategy is the one exception — it sends the current turn text to typesafe.ai, see [The Jev strategy](#the-jev-strategy)). It is not required. AgentOS can also run in direct single-model mode. ## Model Tiers Pilot Router sorts every turn into one of four text tiers, ordered from cheapest and fastest to strongest, plus a separate vision route. `c1` is the default tier: it handles ordinary work, and it is where the router falls back whenever it is unsure or its model bundle is unavailable. | Tier | Handles | | --- | --- | | `c0` | Trivial chat, short rewrites, extraction, and low-risk simple Q&A. | | `c1` | Normal agent work: coding assistance, debugging, and moderate analysis. **Default tier.** | | `c2` | Multi-step coding, structured reasoning, larger-context synthesis, and harder analysis. | | `c3` | Difficult planning, deep review, complex debugging, and high-stakes synthesis. | | `image_model` | Vision route for user-supplied image attachments, screenshots, and diagrams. | **`image_model` is not a difficulty level.** It is chosen when the turn carries image attachments, independently of the `c0`–`c3` classification. **Each provider profile maps its own models.** The tier is the routing decision; which model serves that tier comes from `[agentos_router.tiers]`, and the defaults differ per provider profile. See the annotated tier block in `agentos.toml.example`, or the Providers and Models page for the profiles themselves. **Classes and tiers are the same four levels.** The classifier reports `R0`–`R3`; these map one-to-one onto `c0`–`c3`. Diagnostics output and the LLM judge use the `R` names, while config, the CLI, and this page use the `c` names. **Reasoning effort follows the tier** when `auto_thinking` is enabled: `c3` raises thinking to T3, `c2` to T2, `c1` to T1, and `c0` runs with no thinking budget. ### How a Turn Lands on a Tier The tier for a turn is not only the classifier's opinion. These steps apply in order, and a later one can override an earlier one: 1. **Image attachments** route the turn to `image_model` outright, skipping text classification; 2. **a manual pin** (`/c0` … `/c3`) overrides classification, and stays in effect until you run `/auto`, leave the session, or the hold idles out after ten minutes; 3. **the strategy classifies** the current message into `R0`–`R3` and maps it to the matching tier — only the current message is classified, not the history; 4. **a low-confidence decision snaps back to the default tier** — when the strategy's confidence falls below `confidence_threshold` (default `0.5`), a non-default tier is replaced by `c1`; 5. **a short complaint upgrades one tier** — a brief frustrated follow-up (at most `complaint_upgrade_max_chars`, default 160) raises the turn by `complaint_upgrade_steps` (default 1); 6. **cache continuity holds a higher tier** — when a recent turn (within `kv_cache_anti_downgrade_window_seconds`, default 600) ran higher, the turn is not downgraded below it; 7. **a translation request drops to a ceiling** — see [Translation requests](#translation-requests) below; 8. **a large context raises a floor** — roughly 25,000 material tokens floors the turn at `c2`, and roughly 80,000 tokens, or 40% of the model's context window, floors it at `c3`. To see which of these applied to a given turn, turn on diagnostics as described in [What the Router Can Affect](#what-the-router-can-affect). ### Translation Requests The strategies score *reasoning difficulty*, not task type, so an ordinary "translate this paragraph" is scored as ordinary work and lands on `c1` — and because the Pilot corpus is English-only, the same request written in another language drifts a tier in either direction for no reason but its script. Whether translation deserves more than the cheapest model is a policy question rather than something a classifier can be trained into, so it is answered deterministically. A translate verb in the first or last paragraph of a turn — recognised in English, Vietnamese, Chinese, Japanese, Korean, Thai, Indonesian, French, Spanish, German, Portuguese, Russian, Arabic, and Hindi — caps the turn at `translate_ceiling_tier` (default `c0`). | Key | Default | Meaning | | --- | --- | --- | | `translate_ceiling_enabled` | `true` | Turn the cap off entirely. | | `translate_ceiling_tier` | `c0` | Tier a translation turn is capped at. | Every detected translation is capped, extras and all: asking for commentary alongside the translation, or for a poem's rhyme to survive it, does not lift the turn. Three things still do: - **a complaint upgrade**, so a follow-up saying the last answer was wrong is never capped in the same turn; - **the large-context floor**, which runs after the cap and lifts a document too big for the cheap tier back to one that can hold it; - **a programming language as the target** — "translate this Python module to Rust" is a request to write code, not to translate prose, and is the one phrasing that shares the verb without sharing the task. Detection reads only the leading and trailing paragraph of a turn, so a pasted document that merely mentions translation is not treated as a translation request. When a turn is capped, `routing_extra` carries `task_type`, `task_type_ceiling_from_tier`, and the matched language; when the verb matched but the cap did not apply, `task_type_blocked_by` records why. ## Strategies Pilot Router has three selectable strategies, set via `agentos_router.strategy` in `agentos.toml` (or the onboarding wizard): | Strategy | Mode label | How it decides | | --- | --- | --- | | `pilot-v1` (default) | Local ML — English-optimized (Pilot) | An AgentOS-native, English-optimized local router (MiniLM embeddings + a self-trained AgentOS model, ONNX). Decides on-device with no LLM call, nothing leaving your machine. The bundle ships in the wheel under `src/agentos/agentos_router/models/pilot_v1/`; a missing bundle degrades to the default tier (c1). See [The Pilot strategy](#the-pilot-strategy) below for status, config, and upgrade-from-v4 behavior. | | `llm_judge` | Smart routing (LLM-based) | A small "judge" model classifies each turn (R0–R3) via a forced tool call. The judge can be a cloud model (default: the cheapest tier of your active provider) or a local OpenAI-compatible endpoint (Ollama, LM Studio, llama.cpp, vLLM) configured with `judge_model` / `judge_base_url`. | | `jev` (experimental, opt-in) | Jev cloud classifier (typesafe.ai, experimental) | One call to typesafe.ai's Jev "System One" classifier per turn. Sends the **current turn text** to typesafe.ai (nothing else: no system prompt, history, or tool list). Returns a calibrated probability over R0–R3 that feeds the engine's confidence gate, plus a `high_risk` score that floors destructive / production-affecting requests at c3. Configured under `[agentos_router.jev]`; the key comes from `TYPESAFE_API_KEY`. See [The Jev strategy](#the-jev-strategy). | Both the Web UI setup wizard and the CLI (`agentos onboard`, `agentos configure router`) offer a Mode dropdown with four options: **Local ML — English-optimized (Pilot)**, **Smart routing (LLM-based)**, **Jev cloud classifier (typesafe.ai, experimental)**, and **Off** — the legacy **Smart routing (on-device)** (`v4_phase3`) option is no longer offered. The "Judge model" field only appears when the LLM-based strategy is selected; the "Pilot safety net" field only appears when the Pilot strategy is selected; the "TypeSafe API key" field only appears when the Jev strategy is selected — each is irrelevant to the other strategies. ### The Pilot strategy `pilot-v1` is an AgentOS-native, English-optimized local router. It replaces the borrowed `v4_phase3` embedding+ensemble with a self-trained AgentOS model (MiniLM embeddings + ONNX inference) that runs entirely offline — no LLM call, nothing leaves your machine. **Status: default strategy.** `pilot-v1` is the default router strategy — a fresh install routes through it with no config change. It was promoted from opt-in after passing the owner's relative-to-incumbent ship gate (it beats the `v4_phase3` incumbent on 11/12 evaluation axes; see `scripts/pilot_router/DATA.md` / `scripts/pilot_router/eval_report.md`). The legacy `v4_phase3` engine and its ~52MB model bundle have been removed from the tree entirely (Phase C); a config that still pins it is auto-migrated to `pilot-v1` on the next load (see **Upgrading from v4_phase3**). Those reports measure routing *quality* and feature-extraction *latency*. For what the router has saved you in dollars on your own traffic, see [`agentos cost savings`](https://useagentos.dev/docs/core/cli#agentos-cost-savings) — it rolls the per-turn savings telemetry in `~/.agentos/logs/decisions-*.jsonl` up into a summary, JSON/CSV, or a shareable PDF. The default needs no config, but the Pilot safety-net floor is tunable: ```toml [agentos_router] # strategy = "pilot-v1" # default — this line is optional [agentos_router.pilot] # Under-routing safety-net floor. The effective cutoff is # max(safety_net_threshold, router.confidence_threshold), so a value below the # confidence threshold has no effect. Default 0.5. safety_net_threshold = 0.5 ``` The Web UI setup wizard / CLI preselect the **Local ML — English-optimized (Pilot)** router mode by default. **Degrade behavior.** Like `v4_phase3`, Pilot never fails the turn if its artifacts are missing. When the Pilot model bundle is not present (e.g. a source checkout without `git lfs pull`), the strategy tags the decision `pilot_unavailable` and routes the turn to the default tier (the same graceful degrade `v4_phase3` used when its bundle was missing). **Upgrading from v4_phase3.** Historical installs persisted `strategy = "v4_phase3"` explicitly in `~/.agentos/config.toml`. On the next config load AgentOS **automatically migrates** any such config to `pilot-v1`: the old file is backed up verbatim next to it (`config.toml.backup.<timestamp>`) and rewritten with `strategy = "pilot-v1"`, and the flip is logged. The migration is idempotent — once rewritten there is nothing left to migrate. There is no way to keep `v4_phase3` in config: the legacy engine and its model bundle were removed from the tree (Phase C), and a value that bypasses the file migration (e.g. an env override) normalizes to `pilot-v1` at config load. ### The Jev strategy `jev` is an **experimental, opt-in** strategy backed by typesafe.ai's Jev "System One" classifier. Jev is not a text generator: one `POST /v1/systemone` call answers two typed questions in parallel — a `route` choice over R0–R3 (criteria derived from your tier descriptions) and a `high_risk` score ("is this a destructive / production-affecting request?") — and returns a **calibrated** probability distribution. Unlike the LLM judge, whose self-reported confidence is uncalibrated and therefore pinned to 1.0, Jev's confidence flows through the engine's confidence gate unchanged. A `high_risk` score at or above `high_risk_threshold` floors the turn at c3 (the decision carries `high_risk_floor_applied = true`), and a floor is never undone by the confidence gate. **Privacy.** Selecting this strategy sends the current turn text (truncated to `input_max_chars`) to typesafe.ai on every routed turn. Nothing else leaves the machine — no system prompt, no history, no tool list. It is never the default. Select it from the wizard — run `agentos configure router` with **no** `--router` flag (the flag is the non-interactive form and saves without asking), then pick **Jev cloud classifier (typesafe.ai, experimental)**; it asks for the API key (blank = use `TYPESAFE_API_KEY`, set beforehand with `agentos env set TYPESAFE_API_KEY`, which prompts for the value) and verifies it with one test call. Or set it by hand (`agentos config set agentos_router.strategy jev`, or edit the file): ```toml [agentos_router] strategy = "jev" [agentos_router.jev] # api_key = "..." # or leave unset and export TYPESAFE_API_KEY api_key_env = "TYPESAFE_API_KEY" base_url = "https://api.typesafe.ai" model = "jev-latest" input_max_chars = 4000 # min 1000; head/tail truncation high_risk_threshold = 0.7 # high_risk >= this floors the turn at c3 # timeout_seconds = 8.0 # unset: derived from routing_timeout_seconds short_circuit_enabled = true # greetings/acks skip the call agentic_floor_enabled = false # true: tool-bearing turns never go below c1 ``` `api_key` is redacted on every public surface and is never written to `config.toml` when it equals `$TYPESAFE_API_KEY`. **Degrade behavior.** Every failure routes the turn to the default tier with `routing_source = "jev_unavailable"` and a `reason` in `routing_extra`; there is no in-band retry. `agentos doctor` reports a missing key as `router.credentials.missing`, and boot logs `build_services.agentos_router_credentials_missing`. | Condition | `reason` | Result | | --- | --- | --- | | No key in `api_key` or `$TYPESAFE_API_KEY` | `api key missing (TYPESAFE_API_KEY)` | default tier, no network call | | HTTP 401 / 422 / 429 / 529 (or any 4xx/5xx) | `http <status>` | default tier | | Network error | exception class name | default tier | | Inner timeout (strictly below `routing_timeout_seconds`) | `jev timeout` | default tier | | Unparsable body / no usable `route` answer | `malformed jev response` | default tier | With `agentos_router.require_router_runtime = true` every degrade becomes a `RuntimeError` instead, and a missing key is fatal at boot (Pilot parity). For a classifier-only eval on the labeled dataset (accuracy, under-routing, ECE/NLL, cost) see `scripts/pilot_router/evaluate_jev.py`; for the engine-level view, `scripts/router_eval.py --strategy jev`. ## One Router, One Provider Routing is **single-provider**: the gateway builds one provider client from `[llm].provider` at boot, and tiers only choose which **model** each turn uses. The `provider` field on a tier is descriptive metadata — it never makes a request reach a different provider. Configure every tier with a model that `[llm].provider` itself serves. Local providers (Ollama, LM Studio, OVMS, vLLM) have no built-in tier profile. Onboarding writes self-consistent single-model tiers for them; to get real multi-model routing, edit the tiers to point at other models your local server has pulled (see the local example in `agentos.toml.example`). If a tier still points at a different provider than `[llm].provider` — for example leftover cloud defaults on an Ollama install — the router degrades that route to `[llm].model` instead of sending the local server a model name it does not have; the turn metadata carries `routing_degraded: true`, `agentos doctor` reports the mismatch, and the gateway logs a one-time warning at boot. ## Enable Routing Recommended first-run setup: ```sh agentos onboard --router recommended ``` Reconfigure an existing install: ```sh agentos configure router --router recommended ``` Use the OpenRouter mixed defaults: ```sh agentos configure router --router openrouter-mix ``` Disable routing and use the configured provider/model directly: ```sh agentos configure router --router disabled ``` ## Inspect Provider Support Check the provider catalog available in your install: ```sh agentos providers list ``` If the gateway is running, inspect runtime provider health: ```sh agentos providers status ``` Router-supported profiles depend on the installed AgentOS version, optional dependencies, and configured provider credentials. Common profiles include OpenRouter (the default), Bankr, OpenCAP, Surplus Intelligence, OpenAI, DeepSeek, Gemini, DashScope, Moonshot, Volcengine, Zhipu, and compatible provider tiers exposed by the local catalog. ## What the Router Can Affect Depending on configuration, Pilot Router may influence: - selected model tier; - direct model fallback; - reasoning level; - response policy; - image-capable model selection; - cache-continuity safeguards for recent higher-tier turns. The exact decision is available through runtime metadata and diagnostics surfaces. Turn on diagnostics when you need to understand why a turn was routed to a particular model: ```sh agentos diagnostics on ``` ## Recommended Operating Modes | Goal | Suggested mode | | --- | --- | | General personal-agent use | `recommended` | | Multi-provider cost optimization through OpenRouter | `openrouter-mix` | | Provider evaluation, billing audit, or reproducible benchmark run | `disabled` | | Debugging one provider-specific behavior | `disabled` | For routine use, start with `recommended`. Disable routing only when the model choice itself is the thing you are testing. This table covers the install/provider profile (`--router`). It is independent of the `strategy` choice above — both `pilot-v1` and `llm_judge` work under any profile. ## Example Requests Good router-friendly requests describe the outcome, not the tier: ```text Summarize this long issue thread and list the decision points. ``` ```text Review my current diff and point out the highest-risk changes. ``` Avoid asking the router to behave like a manual model picker unless you are debugging: ```text Use exactly this one model for every turn. ``` For exact-model work, configure direct routing instead. ## Troubleshooting If routing does not appear to work: 1. Confirm the router is enabled: ```sh agentos config get router.enabled agentos config get llm.provider ``` 2. Check provider readiness: ```sh agentos providers status agentos doctor ``` 3. If Pilot Router optional ML dependencies (`numpy`, `onnxruntime`, `tokenizers` — install via `uv sync --extra recommended` or the `ml-router` extra) or the local model bundle are missing, the default `pilot-v1` strategy degrades to the default tier rather than failing the turn (it tags the decision `pilot_unavailable` — the same graceful degrade the legacy `v4_phase3` used); AgentOS can also still run with direct single-model routing, or switch `strategy` to `llm_judge` to route without any local ML bundle at all. On Windows, ONNX Runtime may require the Visual C++ Redistributable. 4. If `strategy = "jev"` and decisions show `routing_source = "jev_unavailable"`, read `routing_extra.reason`: `api key missing (TYPESAFE_API_KEY)` means no key resolved (`agentos env set TYPESAFE_API_KEY`, which prompts for the value, or `agentos_router.jev.api_key`); `http 401` is a rejected key, `http 429` / `http 529` is rate limiting or vendor overload, `jev timeout` means the call exceeded `jev.timeout_seconds`, and `malformed jev response` means the body had no usable `route` answer. `agentos doctor` surfaces the missing-key case as the finding `router.credentials.missing` (`runtimeInvalidReason = "credentials_missing"`). Every case routes the turn to the default tier; the turn itself never fails unless `require_router_runtime = true`. 5. If routing takes longer than `agentos_router.routing_timeout_seconds` (default `10`), the turn runs unrouted instead of failing. Each routing step runs on its own thread, so a router that blocks holds up neither the gateway nor another turn's routing. If router steps keep hanging past the timeout, at most 4 stuck router threads are kept; further turns skip routing (logged as `pipeline.step_failed` with `Pilot Router skipped: N earlier router steps are still stuck`) until a stuck step returns. 6. If you need deterministic model behavior for a run, disable routing: ```sh agentos configure router --router disabled ``` --- # Tool Compression > Source: https://useagentos.dev/docs/core/features/tool-compression AgentOS agents use tools. Tool calls can produce large outputs: command logs, JSON, web pages, search results, diffs, file contents, tables, and artifacts. Tool compression keeps those outputs useful without letting them consume the whole model context. This is a user-facing context-management feature. It does not change what the tool returned; it changes how much of that result is shown to the model for the next step. ## Why It Matters Tool compression helps when: - a command prints a large log; - a web page or search result is too long for a useful prompt; - a file read returns more text than the next step needs; - a long session is close to the context budget; - you want raw results preserved while the model sees a compact preview. Without compression, one large tool result can crowd out the user's goal, recent conversation, and next action. ## What Users May See In long or tool-heavy turns, the model-visible result may include: - a compact preview; - a note that a result was shortened; - a `tool_result_handle` for an out-of-band stored result; - estimated token-saving diagnostics when diagnostics are enabled. This is expected. It means AgentOS is protecting the active context window. ## Product-Level Model AgentOS separates two views: | View | Purpose | | --- | --- | | Runtime view | The durable result AgentOS can preserve, inspect, or export. | | Provider view | The bounded text sent back to the model for the next reasoning step. | The agent can continue from the important facts while large raw material stays available through files, session export, diagnostics, or tool-result handles when configured. ## Compression Modes AgentOS supports several compression styles depending on configuration and tool output shape. | Mode | Best for | Tradeoff | | --- | --- | --- | | `truncate` | Fast deterministic previews. | May omit useful middle sections. | | `summarize` | Slower/background workflows that benefit from semantic summaries. | Adds another model call and should be opt-in. | | Structured projection | Logs, diffs, JSON, tables, and known tool shapes. | Depends on reducer coverage for that output type. | Most users should keep the default behavior and use diagnostics only when a workflow is still too large. ## How to Work With Large Outputs Ask for focused follow-up reads: ```text Look at the failing test names and the last 80 lines of the log. ``` Prefer handles, paths, and summaries: ```text Use the compacted result to identify likely causes, then read the exact file sections you need. ``` Avoid asking the agent to paste every line of a huge result unless exact text is the deliverable: ```text Paste the entire 50,000-line log into chat. ``` ## Inspect and Debug Turn on diagnostics when you need to understand context growth: ```sh agentos diagnostics on ``` Export the session when you need to inspect durable history outside the chat surface: ```sh agentos sessions export <session-key> ``` Review cost and usage after a large tool-heavy run: ```sh agentos cost ``` ## Best Practices - Keep tool requests specific. - Ask for the smallest file ranges, log tail, or JSON fields that answer the question. - Use artifacts for large deliverables instead of forcing everything into chat. - Use session export for audit and debugging. - Treat tool compression as a continuity feature, not as a substitute for storing important files. --- # Memory > Source: https://useagentos.dev/docs/core/features/memory AgentOS memory helps the agent recall durable context without replaying every old conversation. Use it for stable preferences, reusable project facts, previous decisions, and notes that should survive across sessions. Memory is separate from skills. Skills teach the agent how to do a task; memory stores useful facts and context the agent may need later. ## How it fits together ```mermaid graph TB subgraph Sources["📁 Memory sources — files are the source of truth"] CUR["🧠 MEMORY.md<br/>curated agent notes, char-budgeted"] USR["👤 USER.md<br/>user profile, char-budgeted"] NOTES["📝 memory/**/*.md<br/>daily and named notes"] end subgraph Engine["⚙️ Built-in memory engine — always on"] IDX[("🔎 Hybrid index<br/>SQLite FTS + sqlite-vec")] EMB["🧮 Embedding provider<br/>auto: Gemma → BGE → remote → FTS-only"] end subgraph Ext["🔌 External provider — optional, off by default"] MEM0["mem0, fully local<br/>Ollama LLM + embeddinggemma + on-disk vectors"] end CHAT["💬 Private conversation"] REVIEW["📝 Memory review<br/>every N turns · before a compaction"] PROMPT["💬 System prompt<br/>frozen snapshots + fenced recall"] RECALL["🔁 Proactive recall<br/>trigger search · deep recall"] TOOLS["🛠️ Tools<br/>memory · memory_save · memory_search"] LIN[("🧾 Lineage<br/>origins · forgotten sessions")] CHAT --> TOOLS CHAT --> REVIEW REVIEW -->|memory · memory_save| TOOLS CUR -->|frozen snapshot| PROMPT USR -->|frozen snapshot| PROMPT CUR --> IDX NOTES --> IDX EMB --> IDX IDX -->|memory_search| TOOLS IDX --> RECALL RECALL -->|fenced recall block| PROMPT TOOLS -->|memory tool writes| CUR TOOLS -->|memory_save| NOTES TOOLS -.->|origins| LIN MEM0 -->|fenced recall block| PROMPT TOOLS -.->|write mirror| MEM0 classDef store fill:#E6E6FA,stroke:#333,stroke-width:2px,color:#1a1a5e classDef engine fill:#90EE90,stroke:#333,stroke-width:2px,color:#0a3d0a classDef ext fill:#FFE4B5,stroke:#333,stroke-width:2px,color:#5e3a00 classDef out fill:#87CEEB,stroke:#333,stroke-width:2px,color:#003554 class CUR,USR,NOTES,LIN store class IDX,EMB,RECALL,REVIEW engine class MEM0 ext class PROMPT,TOOLS,CHAT out ``` How a conversation becomes long-term memory: the model saves facts on its own, or the [memory review](#how-conversations-become-memory) does it every few turns and once more before a compaction summarises the conversation. Those writes land in `MEMORY.md` (through the `memory` tool) or in dated notes (`memory_save`), and notes are found again by search and proactive recall. Every write records which session caused it, so [forget](#lineage-and-forget) can remove what a session taught the agent. ## What to Store Good memory entries are stable and reusable: - user preferences; - project conventions; - recurring output formats; - names of important repositories, directories, or services; - decisions the user wants reused; - brief notes from completed tasks. Avoid memory for: - API keys or secrets; - raw private data that does not need long-term recall; - one-off instructions for the current turn; - noisy dumps that would pollute future retrieval; - exact transcripts that should instead be exported as session records. ## Common Commands Inspect memory health: ```sh agentos memory status agentos memory status --deep ``` Index and list memory sources: ```sh agentos memory index agentos memory list --source all ``` Ingest documents or folders into knowledge base: ```sh agentos memory ingest /path/to/notes agentos memory ingest /path/to/architecture.pdf ``` Curate agent notes and user preferences: ```sh agentos memory curated get --target memory agentos memory curated add "Always run unit tests before submitting PRs" agentos memory curated remove "Always run unit tests before submitting PRs" ``` Search and inspect memory: ```sh agentos memory search "release note format" agentos memory show <path> ``` Search knowledge base, sessions, or all sources: ```sh agentos memory search "deployment decision" --source knowledge_base agentos memory search "deployment decision" --source all ``` ## Natural Chat Usage Ask naturally when something should be remembered: ```text Remember that I prefer concise release notes with a risk section. ``` Later, refer to the preference: ```text Use my usual release-note format for this changelog. ``` You do not have to ask the agent to search: proactive recall (below) looks up memory for each message, and the agent is told to call `memory_search` itself whenever an answer depends on past work it does not have in context. When memory still seems stale, ask explicitly: ```text Search memory for my release-note preferences before drafting this. ``` ## Proactive recall `MEMORY.md` and `USER.md` are always in the prompt, but notes under `memory/**/*.md`, indexed sessions and the knowledge base are only reached by search. Proactive recall runs that search for the agent before each interactive turn, in two lanes: 1. **Trigger search** — every eligible turn. A lexical (keyword) search of the curated notes with the user's message. A note is injected only when it is a strong match: enough of the message's key terms appear in it (or its heading's terms appear in the message), scored deterministically against `trigger_min_score`. No embedding or model call, and bounded by `[memory] recall_timeout_seconds`. 2. **Deep recall** — only when the message asks about the past ("what did we decide last time", "do you remember", "hôm trước mình chốt gì", "còn nhớ … không") *and* the trigger search found nothing strong. A wider search (all sources, hybrid), the matching lines read from each note, and one small-model call that returns a short summary or `NONE`. Bounded by `deep_timeout_seconds`. Recall intent is detected by phrase patterns for English, Vietnamese (with or without diacritics), Spanish, Portuguese, French, German, Chinese, Japanese, Korean and Russian. What is found goes into the turn's dynamic context (not the cached system prompt) as a `## Recalled Memory` block, fenced in `<memory-context>` with a note that it is background data, not user input, and capped at `max_injected_chars`. If deep recall times out or fails, a one-line note says so, so the agent does not take silence as "no memory". Nothing in either lane can fail or block the turn beyond its deadline. `mode` controls the deep lane: `escalate` (default) as above, `always` on every eligible turn, `off` never (the trigger search still runs). Set `enabled = false` to turn proactive recall off entirely. **Which turns run it.** Only turns a person typed into a private, interactive conversation: the web chat, the CLI, and direct messages on channels. Heartbeat, cron and other background runs, sub-agent and ACP children, inter-session messages and child-completion deliveries, group and channel conversations, and stateless prompts are skipped. **Model.** Deep recall is the auxiliary task `memory_recall`. By default it uses the model the session is chatting with. The model is chosen in this order, highest first: 1. `AGENTOS_MEMORY_RECALL_PROVIDER` / `AGENTOS_MEMORY_RECALL_MODEL`, then `[auxiliary.tasks.memory_recall]`: the operator's override. 2. `[memory.recall] provider` / `model`, when set. 3. The session's chat model for this turn. That is the model pinned on the session (`sessions.patch` / the session's model setting), else the agent's model, else a router hold already in place (`/use <model>` or `router_control`, while `[agentos_router]` is on), else the primary `[llm]` model. The call goes through the same provider, API key and base URL as the turn. 4. The auxiliary chain (`[auxiliary]`, then `[llm]`, then the built-in default). This applies only when there is no chat provider at all. The router's per-turn tier choice is made after recall runs, so recall does not wait for it. Without a pinned model, an agent model or a hold, recall uses the primary `[llm]` model even when the router later sends the turn to another tier. Thinking is always off for the recall call, whatever the session's thinking level. Providers whose models reason by default are sent their explicit "no reasoning" setting (or the lowest effort the model accepts), so a reasoning model does not run past `deep_timeout_seconds`. Recall still pays the chat model's latency. If you chat with a large or slow model, set `[memory.recall] model` to a fast one (or raise `deep_timeout_seconds`). Tokens are recorded as `aux:memory_recall`. The model gets no tools: AgentOS runs the memory search and line reads itself and hands it only those excerpts. ```toml [memory.recall] enabled = true mode = "escalate" # escalate | always | off trigger_min_score = 0.65 trigger_max_hits = 3 max_injected_chars = 1800 deep_timeout_seconds = 8.0 deep_max_summary_chars = 400 deep_max_results = 6 provider = "" # empty: inherit the session's chat model model = "" ``` The same keys are in the web console in the **Proactive recall** card of **Settings › Memory**, on the **Embeddings** tab. **Per-session control and inspection.** ```sh agentos memory recall status --session <session-key> --show-block agentos memory recall pause --session <session-key> agentos memory recall resume --session <session-key> ``` `status` shows the last outcome per session — `injected`, `none`, `unavailable` or `error`, the lane decision, hit counts, elapsed time, the deep-recall model with the rule that chose it — and with `--show-block` the exact block that was injected. A pause applies to one session until it is resumed or the gateway restarts. Each turn also logs a `memory.active_recall` event with the same fields. Over RPC these are `memory.recall.status` and `memory.recall.set`. ## How conversations become memory Durable facts from a conversation reach memory in three ways: the model saves them on its own, you ask it to, or the **memory review** does it. The review is a short background turn that re-reads the conversation and saves anything durable it finds, with a memory-only tool set (`memory`, `memory_save`, `memory_get`, `memory_search`, and for the periodic review `memory_delete`). It never blocks a reply and never appears in the transcript. It runs at two moments: - **Every few turns** (`[memory.nudge] interval`, default 10 user turns), after the reply has been delivered. It is skipped for a turn in which the agent already wrote to memory on its own. This review goes through every message the user sent in the conversation, lists the durable facts in them (including ones mentioned in passing while asking for something else), checks each against what `USER.md` and `MEMORY.md` already hold, then adds what is missing and replaces values that changed (keeping the rest of the entry), one topic per entry. It leaves out small talk, passing moods and events, one-off questions and the task itself. Each run is logged as a `memory_nudge.review_done` event: what it wrote (target and action, never the text), and the review turn's own `input_tokens`, `output_tokens` and `iterations`. The review has no transcript entry, so that line is where its cost shows up. - **Once before a compaction** (`[memory.nudge] before_compaction`, default `true`). A compaction replaces older messages with a summary, so this is the last chance to save what only those messages hold. The review runs right before a proactive or manual compaction (the web console's or `agentos chat`'s `/compact`) of a private chat, with a prompt saying that earlier messages are about to be summarised and only durable facts not yet saved should be written. It can only add: new `memory` entries and notes appended with `memory_save`. Replacing, removing or overwriting anything already saved is refused inside it, whatever the conversation asks for (the periodic review keeps those operations). It is bounded by `[memory.nudge] timeout_seconds`: compaction never waits longer, and comes out the same whether the review saved something, saved nothing, failed or timed out. A manual compaction can therefore take up to `timeout_seconds` longer than before. Afterwards the periodic count restarts. It is skipped, with a logged reason, when the compaction would summarise nothing anyway, which is known without a model call (the conversation still fits, or folding it would not save enough: `nothing_to_compact`), for a compaction forced by a full context (in-turn, or the gateway's overflow recovery: `no_headroom`), for cron, sub-agent, group and channel sessions, when a review ran in the last two user turns of the session (`recent_review`), and while one is already running for it (`in_progress`; a review still winding down after its deadline or after its compaction was cancelled counts, and can no longer start a memory write). `[memory.nudge] enabled = false` or `interval = 0` turns it off too. With `[compaction] proactive = false` only manual compactions get a review. A new message cancels a proactive compaction, and its review with it. Each decision is logged as a `pre_compaction_review` event with `outcome` `ran`, `timeout`, `error`, `cancelled` or `skipped` (plus `reason`), and `compaction`, `duration_ms` and `timeout_seconds`. ```toml [memory.nudge] enabled = true interval = 10 # user turns between reviews; 0 disables timeout_seconds = 90.0 before_compaction = true # one review before a proactive or manual compaction ``` Use session export when exact old wording matters: ```sh agentos sessions export <session-key> ``` Memory is for useful recall. Session export is for exact records. ## Lineage and forget Every write records its **origin**: which session caused it and how. - The `memory` tool records each entry it adds or replaces, with the session and writer `tool` (or `review` for the memory review). A replacement keeps the replaced entry's origins and adds the current session; a removal drops the entry's origins. An add of an entry that already exists adds the session to it. - `memory_save` records the block it wrote to its note. - Curated edits through the CLI or RPC (`agentos memory curated ...`) record writer `operator` and no session. Entries and note text written before this existed, or edited by hand since, have no origin: they are **untracked** and never attributed to a session. `agentos memory status --json` shows tracked and untracked counts for `MEMORY.md` and `USER.md`. ```sh agentos memory forget --session <id-or-key> [--session ...] [--agent <id>] [--dry-run] [--json] ``` A selector is a full session id (that transcript only) or a full session key (every transcript under the key, including ones a later reset creates). A prefix never matches: any selector that resolves to nothing stops the whole command, changes nothing, and exits 2. Forget removes: 1. every curated entry with any origin from the selected sessions, whole; an entry that also came from other sessions is removed too and listed as `mixed`; 2. note blocks those sessions saved, under the rule below; 3. the sessions' derived index documents (with session indexing on), found by their path, so one indexed while the forget was running goes too; 4. best effort, the external provider's copies of the removed curated entries. A note block goes only when it is provably theirs. Its text must still be a complete block in the note (starting the note or after a blank line, ending it or before one): a block the user edited or extended with another line is listed as `unmatched` with reason `changed`. And every complete copy of that text in the note must be attributable to the selected sessions: if another session also saved it, if the note holds more copies than they saved, or if a copy lies inside a block another session wrote, nothing is guessed and the block is listed as `unmatched` with reason `ambiguous` and a `detail` (`other_sessions`, `untracked_copies` or `overlaps_other_block`). Forgetting all the sessions involved together removes such a shared block. Only the removed text and one blank-line separator next to it are cut; every other byte of the note, its line endings included, stays as it was. The sessions are then recorded as forgotten: they are never indexed again. Forgets of one agent run one at a time. `--dry-run` prints the same report and changes nothing. The report (`--json`) has `sessions`, `curated`, `mixed`, `notes`, `unmatched` (reason `changed`, `ambiguous`, `file_missing`, `unreadable` or `invalid_path`), `sessionDocuments`, `staleOrigins`, `untracked`, `providerMirrored`, `errors` (each with a stable `code`) and `notCovered`. The command exits 1 when `errors` is not empty. Forget deletes an origin only together with the text it points to: what it could not remove (an unreadable or missing note or `MEMORY.md`, an edited or shared block) keeps its lineage, so running the same forget again retries it. Removed text appears only in the report's `curated` list; logs carry hashes, paths, counts and codes. Forget is not erasure. It removes only what lineage attributes to the sessions: it does not delete transcripts (use `agentos sessions delete`), turn-capture files, compaction checkpoints, or untracked and hand-edited text, and the report says so. A `MEMORY.md` the curated store refuses to rewrite (drift) is reported, not rewritten. Over RPC this is `memory.forget` (`agentId`, `sessions`, `dryRun`), Control-only. Deleting a session (`agentos sessions delete`) removes its derived index document, so search no longer returns it. What the session taught the agent stays, with its origins: deleting a conversation is not a request to unlearn it. **`memory.db` holds more than the index.** The per-agent `memory.db` also holds the origins and the list of forgotten sessions. `agentos memory index --force` rebuilds only the index and keeps both; deleting `memory.db` to force a reindex loses them, and a forgotten session would be indexed again. ## Embeddings and semantic search Hybrid retrieval (the default) blends keyword (FTS) search with vector search. Vectors come from an embedding provider selected by `[memory.embedding]`. In the default `provider = "auto"` mode AgentOS picks the first available option in this order: 1. A downloaded **EmbeddingGemma** model (higher quality, 768-dim). 2. The **bundled BGE-small** ONNX export (offline, ships with the recommended install). 3. A memory-specific **remote** embedding key, if one is configured. 4. **FTS-only** (keyword search) when nothing else is available. ```mermaid flowchart TD START(["🚀 Gateway boot · provider = auto"]) --> GEMMA{"EmbeddingGemma<br/>downloaded?"} GEMMA -->|yes| USEG["✅ local · google/embeddinggemma-300m<br/>mean pooling + prompt prefixes"] GEMMA -->|no| BGE{"Bundled BGE<br/>available?"} BGE -->|yes| USEB["✅ local · BAAI/bge-small-zh-v1.5"] BGE -->|no| KEY{"Remote API key<br/>configured?"} KEY -->|yes| REM["☁️ remote · text-embedding-3-small"] KEY -->|no| FTS["🔤 FTS-only keyword search"] USEG --> FP["🔑 Provider fingerprint"] USEB --> FP REM --> FP FP --> SAME{"Fingerprint changed<br/>since last run?"} SAME -->|no| READY(["🟢 Search ready"]) SAME -->|yes| DROP["🧹 Drop stale index"] DROP --> REEMB["♻️ Re-embed on next sync — automatic"] REEMB --> READY classDef decision fill:#FFD700,stroke:#333,stroke-width:2px,color:#000 classDef local fill:#90EE90,stroke:#333,stroke-width:2px,color:#0a3d0a classDef remote fill:#87CEEB,stroke:#333,stroke-width:2px,color:#003554 classDef fallback fill:#FFB6C1,stroke:#333,stroke-width:2px,color:#5e0a1e class GEMMA,BGE,KEY,SAME decision class USEG,USEB local class REM remote class FTS fallback ``` ### Upgrading the local model The bundled BGE model works offline with no setup. To upgrade to EmbeddingGemma, download its ONNX export once: ```sh agentos memory embedding-download ``` The files land under `~/.agentos/models/embeddings/`. Use `--model <id>` to select a different model; the default is `google/embeddinggemma-300m`. Auto mode then prefers the downloaded model automatically — no config change required, but the gateway must be restarted to pick it up (see below). To pin a specific local model instead of relying on auto, set `[memory.embedding.local]`: ```toml [memory.embedding.local] model = "google/embeddinggemma-300m" # or "BAAI/bge-small-zh-v1.5" ``` ### Reindex on model switch The active provider, model id, and ONNX directory are hashed into an embedding **fingerprint**. Switching the local model (for example, after downloading EmbeddingGemma or changing `[memory.embedding.local].model`) changes that fingerprint, so existing vectors are never mixed across incompatible models. Applying a new local model requires restarting the gateway (or a full stop/start) — the provider is resolved once at boot, so `agentos memory index --force` against an already-running gateway just reindexes with whichever provider it already loaded, not the new one. Once the gateway has restarted with the new model, the fingerprint change is detected automatically and a full reindex happens on the next sync; no manual `--force` step is needed. ## Curated memory (MEMORY.md / USER.md) Two small, bounded files are injected into every system prompt so the agent always has the highest-signal facts on hand without a retrieval round-trip: - `USER.md` — a short profile of the user: name, how to address them, pronouns, language, role, and how they like answers. - `MEMORY.md` — every other durable fact: the user's work, the people in their life, their home, routines, schedules and plans, plus the agent's own notes (environment facts, conventions, tool quirks, lessons learned). It is the larger store, so most facts go here. The agent saves what it judges durable during a turn, and the memory review catches what the turns missed, including facts mentioned in passing while asking for something else. When a fact changes, it is told to replace the entry holding it and keep every other detail of that entry. When a store is nearly full, it is told to keep saving anyway (merge related entries, shorten wordy ones, or use the other store if it has room) and not to drop a fact that is still true just to make room. These are instructions to the model, not checks: once `MEMORY.md` is at its limit a model can still overwrite an entry it should have kept, so a store that stays full is worth reviewing. Both stores live at the workspace root and are §-delimited lists of small entries, not free-form prose. A new workspace (the main one and each `workspace/agents/<id>/`) gets both files empty: everything in them is injected as something the agent remembers, so they hold only what the agent or you put there. What belongs in each is part of the system prompt's memory guidance. Each store is char-budgeted rather than line- or entry-limited: - `memory.curated_memory_char_limit` (default `4000`) bounds `MEMORY.md`. - `memory.curated_user_char_limit` (default `2000`) bounds `USER.md`. - `memory.inject_limit` (default `6400`) bounds the combined text actually injected into the system prompt. It is kept comfortably above the sum of the two budgets plus header overhead so a full `MEMORY.md` and a full `USER.md` both fit without either block being dropped. If a block would push the joined result over `inject_limit`, that block (and any lower-priority block after it) is dropped whole rather than sliced mid-block — memory is checked first, then user. All three limits can also be adjusted from the gateway web UI, in **Settings › Memory** (the retrieval fields at the end of the section). Changes save through `config.patch` and apply immediately — no gateway restart needed. ### The `memory` tool Writes go through a single `memory` tool, not free-form file edits: ```json {"action": "add", "target": "memory", "content": "Deploys with make deploy"} {"action": "replace", "target": "user", "old_text": "prefers dark mode", "content": "Prefers dark mode and 2-space indent"} {"action": "remove", "target": "memory", "old_text": "stale fact"} ``` `target` is `"memory"` (default) or `"user"`. Multiple changes in one turn should use the batch shape instead, which applies atomically against the *final* budget: ```json { "target": "memory", "operations": [ {"action": "remove", "old_text": "old deploy note"}, {"action": "add", "content": "Deploys with make deploy"} ] } ``` ### Consolidation when full An `add` (or a batch whose final result) that would exceed the store's char limit is rejected with the current entries returned in the response, so the agent can consolidate: `replace` overlapping entries or `remove` stale ones, then retry — ideally in the same batch call so a single round-trip both frees room and adds the new fact. Repeated consolidation failures within a turn cap out after a few attempts so a fragile add/replace can't loop the turn to budget exhaustion. The cap is counted per session, so two sessions consolidating the same workspace's memory at once do not use up each other's attempts. ```mermaid flowchart TD W(["🛠️ memory tool call"]) --> SCAN{"🛡️ Threat scan<br/>clean?"} SCAN -->|no| BLOCK["❌ Rejected — content never written"] SCAN -->|yes| DRIFT{"External file drift<br/>detected?"} DRIFT -->|yes| BAK["🗄️ Refused — .bak snapshot saved"] DRIFT -->|no| BUDGET{"Fits the char<br/>budget?"} BUDGET -->|yes| SAVE["💾 Atomic write under file lock"] SAVE --> OK(["✅ Saved"]) BUDGET -->|no| CONS["♻️ Consolidate in ONE batch call:<br/>remove/replace stale entries + add new,<br/>budget checked on the final result"] CONS --> BUDGET classDef decision fill:#FFD700,stroke:#333,stroke-width:2px,color:#000 classDef good fill:#90EE90,stroke:#333,stroke-width:2px,color:#0a3d0a classDef bad fill:#FFB6C1,stroke:#333,stroke-width:2px,color:#5e0a1e class SCAN,DRIFT,BUDGET decision class SAVE,OK good class BLOCK,BAK bad ``` ### Drift guard (`.bak` files) Each store expects its file to be a clean §-delimited list it wrote itself. If an external writer (a patch tool, shell append, manual edit, or a concurrent session) leaves content on disk that would not round-trip through that format, the next `add`/`replace`/`remove`/batch call is refused rather than silently rewriting the file over the foreign content. A timestamped snapshot is written next to the file (e.g. `MEMORY.md.bak.<unix_ts>`) and the tool response points at it; a refused retry against unchanged contents reuses that snapshot instead of writing another. Every write stays refused until the file is rewritten by hand as a clean §-delimited list (entries separated by a line holding only `§`, no blank lines around it) — even a whitespace-only edit such as a blank line before a `§` counts as drift. Lowering `curated_memory_char_limit` / `curated_user_char_limit` below an entry that is already in the file is not drift: that entry can still be removed or replaced to get back under the new limit. The limit still applies to what an add, replace or batch would leave behind. ### Migration note Agents that had a free-form `MEMORY.md` (headings, bullet lists, paragraphs) from before curated memory existed are migrated automatically, once, the first time memory is loaded for a turn: the text is split into entries and kept up to 80% of the char budget, with any remainder archived to `memory/archive/memory-overflow.md` (still indexed and searchable — nothing is lost). `MEMORY.md` is rewritten in place as a clean §-delimited list. Workspaces created by earlier releases were seeded with instructions in both files ("Use this file for…", an empty `- Name:` / `- Pronouns:` form, "Do not store secrets…"), which the migration above split into eight `MEMORY.md` entries. That text took about 16% of each budget and was injected as if it were remembered. That text is now always left out: it is never listed, counted, matched or injected. Reading never writes, so `agentos memory status`, `agentos memory curated get` and `agentos memory forget --dry-run` show a workspace that still holds it exactly as if it were gone, and leave every file byte for byte as it was. The next turn removes it from the files once (as does the first write to a file, whatever makes it), with the same lock and atomic write as any other write and without a `.bak` file: - An entry that is exactly the old template, or exactly one of the entries the migration made from it, is removed. - A template you only added to (every template line still there, unchanged and in order, with values typed after `- Name:` and the like, or lines added) keeps what you added: the filled-in lines and the added lines stay, as one entry; the untouched template lines go. - Anything else stays as it is, including an entry that quotes or rewords the template text, and a template with any line edited or deleted. Remove that by hand with `agentos memory curated remove` if you want it gone. A file that would trip the drift guard is left for it. The removed text was never written by the `memory` tool, so it had no lineage origin (the `untracked` count in `agentos memory status --json` drops by the entries removed) and nothing is sent to an external memory provider. ### `memory_save` scope `memory_save` now targets only `memory/**/*.md` notes — it no longer accepts `MEMORY.md` directly. Durable facts about the agent or the user go through the `memory` tool described above instead. ## External memory providers Built-in memory (the index and curated files above) is always on. On top of it you can enable an **external memory provider** — an extra recall/write layer that runs alongside built-in memory rather than replacing it. It is **disabled by default**: with no provider selected the layer is never imported and adds zero overhead. When a provider is active it hooks four points: - **Prompt block** — a recall block is assembled into the system prompt each turn, so relevant prior facts are available to the model up front. - **Fenced recall** — recalled provider memories are wrapped in a clear fence in the prompt so they are attributable and cannot be confused with the live conversation. - **Per-turn sync** — after each turn the user/assistant exchange is handed to the provider (serialized through one background queue per manager) so it can extract and store durable memories. - **Write mirror** — every committed curated `memory` tool write (add, replace, remove, and each change in a batch) is mirrored to the provider on the same background queue, so it picks up new facts and drops edited or deleted ones. Replace and remove hand the provider the full text of the old entry. A duplicate add that changed nothing is not mirrored, and a failed mirror is logged without affecting the tool call. ```mermaid sequenceDiagram autonumber actor U as 👤 User participant RT as ⚙️ Engine turn participant CM as 🧠 Curated stores participant IX as 🔎 Hybrid index participant XP as 🔌 Provider U->>RT: message RT->>XP: prefetch(query) — 3s budget XP-->>RT: fenced recall (or empty) RT->>CM: frozen snapshots (loaded once per session) RT-->>U: reply par background — never blocks the turn RT->>IX: turn capture → index sync RT->>XP: sync_turn(user, assistant) end opt memory tool write during the turn RT->>CM: add / replace / remove (budget-checked) RT-->>XP: mirror add / replace / remove end ``` ### mem0 (fully local by default) The bundled provider is [mem0](https://github.com/mem0ai/mem0). Its defaults target a **fully local stack** so it works offline with no API keys and no data leaving the machine: - **LLM**: Ollama running `qwen3:4b` at `http://localhost:11434` (used to extract and summarize memories). - **Embedder**: Ollama running `embeddinggemma` at the same endpoint. - **Vector store**: an on-disk store under the agent state directory (`<agent state dir>/mem0`) when `vector_store_path` is left empty. Install the optional extra (it is **not** a required dependency — `mem0ai` is never imported unless the provider is selected): ```sh pip install 'use-agent-os[mem0]' ``` The extra accepts `mem0ai` 0.1.70 up to (not including) 3.0. mem0 changed its search API in 2.0 — the user scope moved from a `user_id=` keyword into `filters={"user_id": ...}` and `limit` became `top_k` — and the provider detects which one the installed client takes when it starts, so either works. If a search is still rejected for its scope, the gateway log has a `mem0_provider.prefetch_failed` warning with the call shape and the installed `mem0ai` version; recall is empty until it is fixed. Make sure Ollama is running and the two models are pulled: ```sh ollama pull qwen3:4b ollama pull embeddinggemma ``` ### Configuration Select and tune the provider under `[memory.provider]`: ```toml [memory.provider] name = "mem0" # "" (disabled, default) | "mem0" [memory.provider.mem0] llm_provider = "ollama" llm_model = "qwen3:4b" llm_base_url = "http://localhost:11434" embedder_provider = "ollama" embedder_model = "embeddinggemma" embedder_base_url = "http://localhost:11434" vector_store_path = "" # empty -> <agent state dir>/mem0 ``` The same keys are editable in the web console under **Settings › Advanced** (filter for `memory.provider`). **Restart required.** The provider manager is built once at gateway boot, so changing `memory.provider.name` — or any `memory.provider.mem0.*` setting — only takes effect after a gateway restart. Settings shows a restart notice naming the change when you save these keys. **How curated writes reach mem0.** A curated entry is stored in mem0 verbatim (no LLM extraction) as one record, tagged with its target and a hash of the entry text. A `remove` searches mem0 for that text and deletes only the records carrying both tags; a `replace` does the same and then adds the new entry. Limits: - Only mirrors written by a version with this tagging can be deleted. Curated adds mirrored by earlier versions went through mem0's fact extraction, carry no tags, and stay in mem0 until you delete them there. - Facts mem0 extracted from the conversation itself (per-turn sync) are never deleted by a curated replace or remove, even when they say the same thing. - The lookup inspects the top 20 search hits for the entry's text. A record that does not rank there (for example, after the embedder model changed) is missed and stays in mem0. - An entry edited outside the `memory` tool (by hand, or through `agentos memory curated`) is not mirrored at all. **Privacy.** With the default stack, everything (LLM, embeddings, vector store) stays on the local machine. mem0 telemetry is disabled, so no usage data is sent externally. ## Maintenance and Repair Refresh the index after editing memory files or changing memory configuration: ```sh agentos memory index --force ``` Inspect archived transcripts from sessions whose memory never landed: ```sh agentos memory raw-fallbacks list agentos memory raw-fallbacks show <path> ``` ## Best Practices - Keep entries short and sourceable. - Prefer "Remember X for project Y" over vague "remember this." - Search memory before assuming the agent forgot. - Remove or revise stale preferences instead of adding contradictory ones. - Keep secrets out of memory. - Use artifacts or files for large reference material. --- # Skills > Source: https://useagentos.dev/docs/core/features/skills Skills are task-specific instruction packages and scripts. They let AgentOS load relevant guidance only when a task needs it, instead of putting every possible instruction into every prompt. Skills are separate from memory. Memory stores facts; skills describe repeatable ways to work. ## What Skills Are For Use skills for repeatable work patterns such as: - deep research; - summarization; - GitHub and PR workflows; - document generation; - spreadsheet, slide, PDF, and DOCX work; - web search; - weather lookup; - terminal or tmux monitoring; - subagent delegation; - skill creation and review. ## Discover Installed Skills List skills available in the current install: ```sh agentos skills list ``` View one skill: ```sh agentos skills view <skill-name> ``` Search community sources: ```sh agentos skills search pdf ``` Some skills may be ineligible when optional dependencies are missing or when the skill is intentionally demo-only. `skills list` is the source of truth for your current install. ### Where Search Results Come From `skills search` fans out to every configured source and merges the results. The Bankr source covers both places Bankr publishes: skills in the [BankrBot/skills](https://github.com/BankrBot/skills) repository, and skills published from bankr.bot, which live under their author's wallet address (`https://bankr.bot/skills/<wallet>/<slug>`) and are served with their body inline rather than as a repository directory. Both install the same way: ```sh agentos skills install https://bankr.bot/skills/<wallet>/<slug> --source bankr ``` Each half carries a fixed allowlist, because neither has an index that can be crawled without tripping a rate limit — and because the source a skill arrives through is recorded as its provenance, so it must not be able to pull an arbitrary repository or another author's skill under Bankr's name. A skill published from a wallet is credited to its author, not to Bankr: it lists the author's handle and resolves to no recognized publisher, so it renders unbranded rather than sitting in the Partners group. The Aeon source reads [aeonfun/aeon](https://github.com/aeonfun/aeon), which unlike the others publishes a real machine-readable index — one `catalog/skills.json` describing all 75 of its skills, so browsing costs a single request rather than one per skill. Its allowlist therefore exists for a different reason: not because the catalog cannot be crawled, but because most of what Aeon publishes does not belong in an interactive runtime. Aeon skills are prompts written for scheduled GitHub Actions runs, and dozens of them either operate an Aeon instance (`aeon-doctor`, `memory-flush`, `aeon-update`) or read Aeon's durable `memory/` directory as their actual input. The allowlisted ones are adapted on install. Their frontmatter declares `requires` as a plain list, which AgentOS reads only as a mapping and would otherwise discard — so it is rewritten into the `requires.env` form, and the Aeon category is remapped onto a real browse bucket. A short note is inserted ahead of the skill's own text saying that `memory/`, `./secretcurl`, and `./notify` are absent here and what to do instead. The prose itself is left alone, so the installed file still reads as Aeon wrote it. Some Aeon skills want an API key you supply yourself, and a few want a paid plan; each catalog card lists what it needs under its setup steps. ## How a Skill Is Described Four separate facts describe an installed skill. They are easy to confuse, and using one to answer another is the usual cause of a confusing Skills screen. | Fact | Question it answers | Values | | --- | --- | --- | | Acquisition | How did it get here? | `shipped`, `hub`, `local` | | Publisher | Whose name is on it? | An allowlisted partner, or nothing | | Layer | Where are the files? | `extra`, `bundled`, `managed`, `personal`, `project`, `workspace` | | Availability | Is the agent being offered it right now? | offered, or a reason | **Acquisition** is what the Web UI groups by, and what `agentos skills list --json` reports under `acquisition`. A `shipped` skill came with AgentOS. A `hub` skill was fetched by `agentos skills install` and has a lockfile entry recording its source, identifier, version, and install time. A `local` skill is a directory you put in a skills folder yourself. The same block carries `removable` and `updatable`. These are answers, not guesses from the layer: if a hub-installed skill's recorded path no longer matches the configured `skills.managed_dir`, `removable` is `false` — AgentOS will not delete files it cannot prove it owns — while `updatable` stays `true`, because an update re-fetches by identifier into the current managed directory. **Publisher** is allowlisted inside AgentOS. A skill manifest can only *select* a recognized publisher by id; it can never *describe* one. A third-party skill that writes a partner's name, URL, and logo into its own frontmatter renders as an ordinary unbranded skill, because none of those fields are read. Selecting an id is also restricted by where the skill lives. Only a `bundled` manifest — one that ships inside the release — may name its own publisher; a directory you (or anything else) drop into a writable skills path gets no brand from its own frontmatter, so a look-alike cannot sit in the Partners group. An installed partner skill is branded by the hub catalog row that installed it, recorded in the lockfile, not by its own text. This is why a partner's skills sit under one heading whether they shipped with AgentOS or you installed them from that partner's hub. **Layer** is only about file location and name-collision precedence (later overrides earlier): `extra` (config dirs) → `bundled` (shipped) → `managed` (`~/.agentos/skills`, where installs land) → `personal` (`~/.agents/skills`) → `project` (`<workspace>/.agents/skills`) → `workspace` (`<workspace>/skills`). It is shown as a detail on each card and it decides which skills are sacrificed first if the prompt budget is exceeded, but it does not tell you where a skill came from. The two `.agents/skills` layers are shared with other agents on the machine — Codex, Cursor, and anything else following that convention install there too. AgentOS treats them as ordinary layers: a skill another tool writes appears on the next turn, and one it removes stops being offered, without a restart and without going through `agentos skills`. The directories are also honoured when they do not exist yet, so the first cross-agent install on a fresh machine does not need one either. Note the precedence that follows from the order above: a skill in `.agents/skills` overrides a bundled or hub-installed skill of the same name. Provenance (`origin`, `license`, `upstream_url`) is separate from all four: it records where the *text* came from and under what licence. A skill can be AgentOS-original text published by a partner, or upstream text with no publisher at all. **Category** (`metadata.agentos.category`) is subject matter, not trust — what a skill is about, where `capabilities` says what it can reach. The Web UI reads one value from it: a shipped skill declaring `category: crypto` is split out of "AgentOS Normal Skills" into its own **AgentOS Crypto Skills** heading. The split is gated on acquisition exactly the way publishers are, so a directory dropped into a writable skills path cannot claim a heading carrying the AgentOS name just by writing a category into its own frontmatter. Cards in that group carry a mark instead of the generic glyph. The nine bundled GMGN skills (`gmgn-token`, `gmgn-market`, `gmgn-portfolio`, `gmgn-track`, `gmgn-holder-analysis`, `gmgn-wallet-analysis`, `gmgn-wallet-score`, `gmgn-swap`, `gmgn-cooking`) wear the GMGN mark — chosen on `provenance.origin: gmgn-mit`, badged with each skill's own `metadata.agentos.emoji` so nine siblings stay tellable apart — and the rest of the group wears the AgentOS mark. Every mark ships with the client; no manifest field points the UI at an image, remote or local. ## Declaring the Variables a Skill Reads `metadata.agentos.requires.env` (or `metadata.platform.requires.env`) lists the environment variables a skill's scripts read. Each entry carries a `description` and a `url` so the Environment page and `agentos env list` can say what the variable is for and where to obtain it, and `secret` when the name-based heuristic would guess wrong. `required` defaults to `true`; set it to `false` for a variable that unlocks part of the skill rather than gating all of it -- the `multi-search-engine` skill declares every engine key that way, so it stays offered on DuckDuckGo alone and grows engines as keys appear. A required variable that is missing hides the skill and is reported by `agentos skills doctor`; an optional one only shows as unset on the Environment page. Declared variables are also the ones forwarded into the `execute_code` sandbox when the skill is viewed, which is how a script running there can read its own key. AgentOS's own provider credentials are refused to hub and local skills; a bundled skill may declare them. ## How a Skill Reaches Its Own Scripts A `SKILL.md` is written before anyone knows where it will be installed or which Python will be running, so it names both through placeholders that the tool layer fills in when the body is handed to the agent (`skill_view`): | Placeholder | Becomes | Why | | --- | --- | --- | | `{baseDir}` | The skill's own install directory | Bundled skills live under site-packages on one machine and under a workspace on the next; an absolute path is wrong everywhere but where it was typed. | | `{python}` | The interpreter AgentOS itself runs on (`sys.executable` of the gateway) | A bare `python` in a shell command is whatever the user's PATH says — a Homebrew 3.9 with a stray `httpx`, or nothing at all on Windows. Only AgentOS's own interpreter is guaranteed to carry the skill's dependencies and to be new enough for its syntax. | So a script invocation in a skill body is written as: ```bash {python} {baseDir}/scripts/run.py --flag value ``` and an `entrypoint.command` in frontmatter as `"{python} {baseDir}/scripts/run.py"` (quoted — YAML would otherwise read the leading `{` as a mapping). `agentos skills init --with-script` scaffolds it that way. The expanded text also leads with `[Skill directory: …]` and `[Skill interpreter: …]` lines, so a third-party skill that still says `python3 script.py` can be steered onto the right interpreter too. Expansion happens only on the copy the agent reads. The file on disk keeps the placeholders, which is what lets `skill_edit` write it back without baking a machine-specific path into it, and what lets the same skill directory move between machines. ## Whether the Agent Is Offered a Skill Installed, eligible, and offered are three different states. A skill can be installed and fully eligible and still not reach the agent on a given turn. The gateway reports this as `availability` on every skill row, and the agent's own skill listing prints a `[not offered]` line with the same explanation: | Reason | Meaning | What to do | | --- | --- | --- | | offered | the agent has it | — | | `model_invocation_disabled` | the manifest opts out of model invocation | nothing; run it yourself | | `ineligible` | a required binary, environment variable, or OS is missing | the detail names what is missing | | `tool_gate` | its required tools are not enabled in this session | enable the tools | | `fallback_superseded` | it is a fallback for a tool the session already has natively | nothing; the native tool is better | | `not_retrieved` | relevance filtering is on and this message did not match | raise `skills.filter_top_k`, or reword | | `prompt_budget` | ready, but the skills block is full | raise `skills.max_skills_prompt_chars` | Every reason above appears in a `skills.list` row except `not_retrieved`. Retrieval ranks skills against the wording of one message, so there is no query to answer it with outside a turn — it reaches the decision log, never the Skills page. The other six, `prompt_budget` included, are answerable from the installed set plus the configured budget, so the page can show them before you send anything. `agentos skills list --json` does not carry `availability`. A CLI process has no chat session and no tool surface, so it cannot answer honestly; an absent key means "not computed", never "not offered". ## Install, Update, and Remove Skills Install a managed skill: ```sh agentos skills install <skill-name> ``` Update one skill or all managed skills: ```sh agentos skills update <skill-name> agentos skills update --all ``` Remove a managed skill: ```sh agentos skills uninstall <skill-name> ``` ### Opt-in skills in this repository `src/agentos/skills/exp/` is left out of the wheel, so nothing in it is in a fresh install's skill list or prompt. A skill there that a user wants is installed from GitHub like any other repository directory, through the same scan and install policy: | Skill | What it does | Install | |---|---|---| | `musedin` | Profile, feed, roles and jobs on MusedIn (musedin.com), signed with the identity the bundled `musebook` skill stores. Paid x402 actions only when the user asks; the script itself never pays. | `agentos skills install https://github.com/use-agent-os/agent-os/tree/main/src/agentos/skills/exp/musedin --source github` | ## Install Security A hub skill is someone else's instructions and scripts, so an install passes three checks before anything reaches the managed layer. The bundle is staged in `~/.agentos/quarantine` while they run and deleted if any of them refuses. | Check | Refuses when | `--force` | | --- | --- | --- | | Registry verdict | ClawHub's own review marks the skill `suspicious` | overrides | | Registry verdict | ClawHub marks it `malicious` | never overrides | | Built-in scan | the pattern scan finds prompt injection, exfiltration or hidden Unicode (`dangerous`) | overrides | | Install policy | your policy command answers `warn` | overrides | | Install policy | your policy command answers `block`, or fails to answer | never overrides | **Registry verdict.** ClawHub scans what it hosts with ClawScan and publishes the result. AgentOS reads it on install, refuses on `suspicious` or `malicious`, and records it in the lockfile as `registry_verdict`. Search results carry it too, along with `upstream_scanners` — third-party scanner statuses the registry relays (Snyk, Socket and others). Those are shown but never refused on: they are another party's opinion of another party's copy. Other sources publish no verdict, so the field is empty for them. **Install policy.** For a real review, point AgentOS at a scanner of your own. It is off by default: ```toml [skills.install_policy] enabled = true command = "/absolute/path/to/clawscan" args = ["openclaw-install-policy"] pass_env = ["PATH", "DOCKER_HOST"] timeout_seconds = 300 ``` The command is run once per install and per update, after the built-in scan and before the move. It reads one JSON request on stdin — the quarantined directory as `sourcePath`, the skill name, the source and the requested identifier — and writes one JSON response on stdout: ```json {"protocolVersion": 1, "decision": "block", "reason": "reads ~/.ssh/id_rsa"} ``` `decision` is `allow`, `warn` or `block`; `reason` and a `findings` list are optional. This is the OpenClaw `security.installPolicy` protocol, version 1, so `clawscan openclaw-install-policy` works unchanged and can front SkillSpector, Tencent AIG, Cisco's scanner or Snyk. Any executable that speaks the protocol will do. The policy fails closed. A command that is missing, is not an absolute path, exits nonzero, times out, or prints anything other than a valid response blocks the install, and so does `enabled = true` with no `command`. The command inherits only the variables named in `pass_env`, not the gateway's environment, and it runs outside the tool sandbox as a trusted local process — point it at a binary you control. The policy covers `agentos skills install` and `agentos skills update`, Settings › Skills in the web console, and the agent's `skill_install_community` tool. It does not cover skills you write yourself or copy into a skill directory by hand. ## Manage Skill Sources Custom source repositories are called taps: ```sh agentos skills tap list agentos skills tap add <owner/repo> agentos skills tap remove <owner/repo> ``` Use taps when your team maintains its own skill catalog. ## What a Skill Can Put in the Chat Besides text, a skill hands files to the surface with `publish_artifact`. Most arrive in Web UI chat as a download chip, but some mimes render inline instead: | Mime | Rendered as | | --- | --- | | `image/*` | Inline preview | | `audio/*` | Inline player | | `application/vnd.agentos.chart+json` | Interactive candlestick chart | Nothing has to be registered for this: the mime a skill publishes decides how its output is drawn, so any skill can render a chart without a frontend change. [Artifacts and Media](https://useagentos.dev/docs/core/artifacts-and-media#inline-charts) carries the payload shape, the workspace rule `publish_artifact` enforces, and the two mistakes that produce no error and no chart — omitting the mime, and writing the file outside the workspace. ## Publish and Inspect Publish a skill directory: ```sh agentos skills publish <path-to-skill> ``` For ordinary skill content, use: ```sh agentos skills view <skill-name> ``` ## How to Ask for a Skill Ask for the outcome: ```text Create a PowerPoint deck summarizing this report. ``` Better than: ```text Load the pptx skill and run its script. ``` AgentOS can choose eligible skills from the current catalog when the task matches their description and triggers. ## Bundled Skill Families | Family | Examples | | --- | --- | | Research | deep research, multi-source search, summarization | | Documents | DOCX, PPTX, XLSX, PDF, HTML-to-PDF | | Operations | cron, GitHub, terminal monitoring, subagents | | Memory | memory-oriented helpers and history exploration | | Creation | skill review | ## Troubleshooting If a skill is not used, start by finding out whether the agent was ever offered it. Guessing from the layer or from "it says ready" is what makes this hard. 1. Confirm it appears in the installed catalog: ```sh agentos skills list ``` 2. Open the skill on the Skills screen, or ask the agent to list its skills. Either surface names the reason it is being withheld. Match it below. 3. **"Needs setup" / `ineligible`.** The reason names the missing binary or environment variable. Install the binary, or set the variable: ```sh agentos env set <NAME> --stdin ``` The value applies to the running gateway — no restart — and the skill becomes eligible on the next turn. 4. **"Skills section is full" / `prompt_budget`.** The skill is ready and was dropped only because the injected skills block hit its character budget. Raise it: ```sh agentos config get skills.max_skills_prompt_chars # default 24000 agentos config set skills.max_skills_prompt_chars 32000 agentos gateway restart ``` The gateway also logs `skills_filter.budget_truncated` with the names it dropped and the budget it hit. Truncation goes lowest-precedence layer first — `extra` directories, then `bundled` — so the symptom is usually shipped skills quietly disappearing while what you installed into `managed`, `personal`, `project`, or `workspace` survives. 5. **The agent ignores skills, but nothing reports `prompt_budget`.** The block fits, so no skill was dropped — but the budget was tight enough that the descriptions were shortened, or replaced by names alone. A name is rarely enough for the model to tell that a skill applies, so the symptom is an agent that answers from general knowledge with every skill still listed as offered. Check the render mode: ```sh grep skills_render_mode ~/.agentos/logs/decisions-*.jsonl | tail -1 ``` Anything other than `full` means the budget cost the model description text, and the gateway logged `skills_filter.budget_degraded` when it happened. Raise `skills.max_skills_prompt_chars`, or turn on `skills.filter_enabled` so only the skills relevant to each message are injected. 6. **`not_retrieved`.** Only reachable when `skills.filter_enabled = true`, which is off by default. Raise `skills.filter_top_k` or reword the request; the answer depends on the wording of that one message. 7. **`tool_gate` or `fallback_superseded`.** These are about the session's tools, not the skill. The first means a tool the skill needs is not enabled; the second means AgentOS already has a native tool that does the job better. 8. **`model_invocation_disabled`.** Working as declared. The skill opted out of model invocation and is for you to run, not the agent. 9. If none of the above applies, ask for the outcome in normal language. Skill names can help, but user intent should still be clear. --- # Browser automation > Source: https://useagentos.dev/docs/core/features/browser The `browser` tool lets the agent drive a real Chromium — navigate, read a page as an accessibility snapshot with element refs, click, type, fill forms, wait, run JavaScript, answer native dialogs, and take screenshots. It is built on the [`agent-browser`](https://github.com/vercel-labs/agent-browser) CLI engine (Vercel Labs, Apache-2.0), a Rust client–daemon that speaks the Chrome DevTools Protocol directly. The tool stays **hidden** from the model until the `agent-browser` binary is installed, the same way `x_search` hides without an xAI key. ## Install ``` npm install -g agent-browser agent-browser install # downloads Chromium # on Debian/Ubuntu/Docker, also install system libs: agent-browser install --with-deps ``` `agentos doctor` reports whether the binary and Chromium are present and prints this hint when they are missing. The binary is looked up on `PATH` first. A gateway launched by the desktop app, launchd or systemd gets a bare `PATH`, so AgentOS then checks the usual npm global directories (nvm, fnm, Volta, pnpm, Bun, Homebrew, `~/.npm-global/bin`). Set `binary_path` if yours lives anywhere else. ## Modes **Managed (default).** The engine launches its own headless Chromium. Nothing to configure beyond installing the binary. Set `headless = false` to watch it work in a visible window. **Attach (opt-in, local only).** Point the tool at your own already-running Chrome so the agent can act inside your logged-in sessions. Start Chrome with a debug port bound to loopback: ``` # macOS example /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome \ --remote-debugging-port=9222 ``` then set: ```toml [browser] cdp_port = 9222 attach_confirmed = true # required — see below ``` Only an integer **port** is accepted (localhost only); there is no way to point the tool at a remote or cloud CDP URL. This is deliberate — it structurally rules out the agent (or a page it visits) redirecting the browser backend somewhere else. ### Attach consent Attach mode can drive whatever your Chrome is signed into — email, bank, dashboards. Because that is a real risk, attach mode refuses to run until you explicitly consent by setting `attach_confirmed = true`. Setting the port alone is not enough. Managed headless mode needs no confirmation. ## Actions `browser(action, …)` dispatches on `action`: | action | args | what it does | | --- | --- | --- | | `navigate` | `url` | open a URL; returns final URL, title, and a page snapshot | | `snapshot` | — | accessibility tree with `@e` refs (the default "read the page") | | `click` | `ref` | click an element by ref | | `type` | `ref`, `text` | type into a field (secret-guarded) | | `fill` | `ref`, `text` | clear then set a field's value (secret-guarded) | | `select` | `ref`, `value` | choose a `<select>` option | | `wait` | `condition` | wait for a selector / text / URL / load state | | `press` | `key` | keyboard key (Enter, Tab, …) | | `scroll` | `direction` | scroll the viewport | | `back` | — | history back | | `screenshot` | — | capture the page | | `tabs` | — | list tabs in this session | | `eval` | `expression` | run JavaScript in the page | | `dialog` | `dialog_action` | accept/dismiss a native alert/confirm/prompt | | `close` | — | end this session's browser (managed) / disconnect (attach) | `navigate`, `snapshot`, `click`, `type`, `fill`, and `wait` are the everyday loop. `eval` and `dialog` are covered below. ## How the agent decides to use it You should not have to say "use the browser tool". The tool's description tells the model to reach for it whenever you ask to open, browse, or look at a page, name a site or a search engine ("search Google for…", "check it on x.com"), want to watch the browser work, or need clicking, a form, or a signed-in session. An explicit request for a browser or a named site wins over `web_search` — that substitution is the main way this tool ends up looking absent. The description also carries a runtime line naming which browser the session drives, because that changes when the tool is the right choice: - **Attached** (visible, your own browser): search engines that refuse headless automation answer normally, so the model is told to prefer this tool over `web_search` for search and browsing. - **Headless**: Google and DuckDuckGo answer with a CAPTCHA, so the model is told to use `web_search` for general search and keep this tool for pages that need interaction or that allow automated access. ## Sessions and persistence Each AgentOS session gets one browser session, started lazily on the first `browser` call and reused across turns. Idle sessions are reaped after `session_ttl_minutes`; at most `max_sessions` run at once (oldest-idle evicted). By default a session's profile is **ephemeral** — cookies and logins do not survive it. Set `persist_profile = true` to keep them between sessions; note that this writes cookies and storage to disk under the AgentOS state directory. ## Security posture The engine runs **outside** the sandbox — Chromium cannot run inside bubblewrap/seatbelt — so these controls are enforced in AgentOS instead: - **Environment scrub.** The engine subprocess starts from a minimal environment (PATH, HOME, locale, …), never the full environment. The gateway token and all provider API keys are unreachable from the browser process. (Lesson from a real Hermes incident, GHSA-m4m8-xjp4-5rmm.) - **SSRF.** `navigate` refuses private ranges, loopback, and cloud-metadata hosts (`169.254.169.254`, …), and re-checks the final URL after redirects. `about:blank` is allowed; `file://`, `data:`, and other `about:` URLs are refused. - **Private-page read guard.** In managed mode, a read action re-checks the live page URL — a JavaScript redirect onto a private address after navigation does not let the next snapshot exfiltrate it. Relaxed in attach mode (your Chrome legitimately sits on intranet pages, and the attach consent covers that). - **Untrusted envelope.** Everything the engine returns — snapshots, `eval` results, tab titles and URLs, every action payload — is wrapped in the `<untrusted>` envelope, so page content can't smuggle instructions to the agent. `eval("document.body.innerText")` is the shortest path from a page into the transcript, so it carries the boundary like any other read. - **Output redaction.** Snapshots, console output, and eval results are masked for credentials before reaching the model. - **Secret-typing guard.** `type` and `fill` refuse text that looks like a credential or matches a value in the environment store. - **No cron.** The tool is excluded from the cron read-only surface. - **Domain allowlist (optional).** `allowed_domains = []` (the default) allows the open web. When you set a list, navigation off it is refused, and the list is also passed to the engine (`--allowed-domains`) so in-page JavaScript navigation is bounded too. ## eval and JavaScript `eval` runs a JavaScript expression in the page and returns its value. It is powerful: JavaScript can read `document.cookie`, storage, and form values — so `eval` can reach things the secret-typing guard blocks for `type`/`fill`. That tradeoff is intentional (it matches how Hermes exposes eval), mitigated by output redaction and an **opt-in** denylist: ```toml [browser] restrict_evaluate = true # block document.cookie, fetch, storage, … in eval allow_unsafe_evaluate = false ``` `restrict_evaluate` is **off by default** because gating on primitive names cripples ordinary DOM extraction. When on, it refuses sensitive primitives (including obfuscated spellings like `document["coo"+"kie"]`); set `allow_unsafe_evaluate = true` to override for a trusted page. `eval` is SSRF-pre-scanned in **both** modes: an expression containing an `http(s)://` literal that points at a private, loopback, or cloud-metadata address is refused before it runs. The managed browser is not exempt — it runs on your machine and reaches those addresses exactly as your own browser does. In managed mode the page URL is also re-checked after the call, so an expression that navigates somewhere private cannot return that page's content. `file` upload and raw CDP passthrough are intentionally not exposed. ## Dialogs Native `alert` / `confirm` / `prompt` / `beforeunload` dialogs are captured by a CDP supervisor and surfaced as `pending_dialogs` in a snapshot. Respond with `browser(action="dialog", dialog_action="accept" | "dismiss", prompt_text=…)`. Policy for unanswered dialogs: ```toml [browser] dialog_policy = "must_respond" # or auto_dismiss | auto_accept dialog_timeout_s = 300 ``` Dialog interception needs a CDP endpoint: it works in attach mode, and in managed mode when the engine exposes its (loopback) CDP endpoint. If no endpoint is available the browser still works; dialogs just aren't intercepted. ## Configuration reference ```toml [browser] enabled = true # master switch; false hides the tool even if installed headless = true # managed mode; false opens a visible window binary_path = "" # optional; default: PATH, then npm global dirs cdp_port = 0 # 0 = managed. >0 = attach to your Chrome (localhost only) attach_confirmed = false # must be true to let the agent drive your Chrome allowed_domains = [] # [] = open web (SSRF still blocks private ranges) persist_profile = false # true = keep cookies/login between sessions (on disk) session_ttl_minutes = 15 max_sessions = 3 snapshot_max_chars = 24000 # snapshots over this are truncated with a marker dialog_policy = "must_respond" # must_respond | auto_dismiss | auto_accept dialog_timeout_s = 300.0 restrict_evaluate = false # true = block sensitive JS primitives in eval allow_unsafe_evaluate = false # true = override restrict_evaluate for trusted pages ``` Every field can also be set via `AGENTOS_BROWSER_*` environment variables. ## Limitations - **Anti-bot walls.** Managed headless Chromium is detectable, and major search engines block it. Verified on 2026-08-21: `google.com/search` returns a reCAPTCHA ("Our systems have detected unusual traffic from your computer network"), `duckduckgo.com` returns an image challenge, and `booking.com` answered a bare `502`. Sites that did work headless in the same test: `bing.com/search` and Wikipedia. The agent must never solve a CAPTCHA — when it hits one, the honest move is to report the wall and use a source that allows automated access, or `web_search` / `web_fetch` instead. For sites that need a real signed-in identity, attach mode (your own Chrome) is the intended path, not fingerprint evasion. - Cloud CDP providers (Browserbase, Browser Use) are not supported. - File upload/download, raw CDP passthrough, and vision-model screenshot analysis are out of scope. - In-page sub-resource requests are not intercepted for SSRF in managed mode (only top-level navigation is). --- # Image Flows > Source: https://useagentos.dev/docs/core/flows An **Image Flow** is a small node graph that makes images: a prompt goes in, optionally a prompt writer or an image description in between, one or more image model calls, and a Save node that writes PNG files. You build flows in the desktop app (**Flows** in the sidebar, after Jobs); the gateway stores and runs them, so the same flow can be run again from the editor, from the terminal (`agentos flows run`) or by an agent (`flow_run`). Two things make a flow worth having over a one-off `image_generate` call: - **It is reusable.** A flow keeps its prompt, model, aspect, count and the wiring between steps. Its *public inputs* (for example `prompt` and `count`) are the values a run may override; everything else stays as you set it. - **It is cached.** Every node's result is cached by what went into it. Run a flow again with one input changed and only the nodes downstream of that input call a model again; the rest are reported as `cached` and cost nothing. ## Concepts - **Links** carry one of two types: `TEXT` or `IMAGE` (a list of 1..n images). An input that has a type can be linked; when it is, the link wins over the input's own value. Numbers, choices and toggles are values only. - **A run** has targets: the node you asked for (`--to NODE`) or else every node with no outgoing link. Only the targets and what they need run. - **Run status** is `queued`, `running`, `done`, `failed` or `cancelled`. Each node is `queued`, `running`, `cached`, `done`, `error` or `skipped`. When a node fails, nodes already calling a model finish (and are cached), nothing new starts, the rest are `skipped`, and the run is `failed`. - **Runs queue** first in, first out; `[flows].max_concurrent_runs` (default 1) run at once, at most 2 calls per image provider. A run still queued or running when the gateway stops ends `failed` with `flows.interrupted`. ### Nodes | Node | Inputs | Output | Notes | | --- | --- | --- | --- | | `text` | `text` | `TEXT` | A fixed piece of text. | | `load_image` | `image` (an uploaded image) | `IMAGE` | Upload in the editor or drop a PNG. | | `join_text` | `a`, `b` (optional), `template` (default `{a}, {b}`) | `TEXT` | A missing `b` drops the dangling `, `. | | `prompt_writer` | `idea`, `context` (optional, link only), `style` | `TEXT` | Turns a short idea into a detailed image prompt with the auxiliary model (task `flow_prompt`). Paid. | | `describe_image` | `image`, `focus` | `TEXT` | Describes an image with the vision model the `image` tool uses (task `vision`). Paid. | | `image` | `prompt`, `images` (optional, several links), `model`, `aspect` / `resolution` / `size` / `quality` / `background` (shown when the model has them), `count` (1-4), `variation` | `IMAGE` | Text to image with nothing linked to `images`; edit / multi-reference with 1..n images linked. `variation = new` always calls the model again; `keep` reuses the cached result for the same inputs. Paid. | | `save` | `images` (several links), `name` (default `{flow}_{run}_{n}`) | none | Writes PNG files that carry the flow inside them (an `agentos-flow` text chunk with the flow id, revision, run id and graph; never a key). | `agentos flows nodes` lists them from the running gateway. In the desktop editor, each image on a Save node has a download button, and so does the image viewer you open by clicking any image on the canvas or in Results. It asks where to save and writes the stored file as it is, at full size. An image from a Save node keeps the name Save gave it and the flow inside it. Any other image is named after its hash (`agentos-flow-1a2b3c4d.png`). ### Models and keys `agentos flows models` lists every image model with whether it can be used, why not, and its price per image. A model is available when its provider has an API key; `[image_generation].enabled` only gates the `image_generate` agent tool and does not affect flows. Keys and base URLs come from `[image_generation.providers.*]`: | Provider | Key (default env) | Models | | --- | --- | --- | | Surplus Intelligence | `SURPLUS_API_KEY` (`[image_generation.providers.surplus]`) | Nano Banana 2 / 2.1 / Pro, GPT Image 2, Seedream, FLUX.2 Pro, Qwen Image (from Surplus's public catalog, refreshed every 6 h, with a bundled snapshot as fallback). | | OpenRouter | `OPENROUTER_API_KEY` | Nano Banana 2 / 2.1 / Pro, GPT-5 Image Mini. | | OpenAI | `OPENAI_API_KEY` | GPT Image (`openai/gpt-image-1`): sizes, qualities, transparent background. | Set a key with `agentos env set SURPLUS_API_KEY` (or the desktop's Settings). A node's `model = auto` means `[image_generation].primary` when that names an available flow model (the built-in default `openai/gpt-image-1` does not count as a choice), else the first available model in the order above (Surplus first), else none: an `image` node then fails validation with "No image model is available" before anything is called. ### Costs Prices are the best known public per-image prices and are marked approximate (`~`). An estimate is per node: `per_image × count + per_ref × linked images`; the run's total adds only the nodes that will run and are not cached. A node's recorded cost is what the provider reported when it reports one, else the estimate. Costs are booked in the usage tracker under the scope `flow:<run_id>` (see `agentos cost`). ## Running flows from the terminal ```sh agentos flows list # saved flows, newest first agentos flows show "Lighthouse study" # nodes, links, public inputs agentos flows nodes # node types agentos flows models # image models, keys, prices agentos flows run "Lighthouse study" --input prompt="a red fox in snow" --input count=2 agentos flows run flw_2af4f4b5 --to n2 --json # only up to node n2 agentos flows run flw_2af4f4b5 --no-wait # queue and return the run id agentos flows runs "Lighthouse study" # recent runs of one flow agentos flows stop run_0123456789ab ``` `run` resolves the flow by id, or by exact name (ids win; two flows with the same name are refused, pass the id). It waits for the run (polling `flows.run.get` every second, `--timeout` seconds, default 600) and prints the status, node progress and cached count, the cost against the estimate (written like the editor: `free`, `~$0.067`, `~$0.0034–$0.10`, `unknown`), and the saved files: ```text run_0123456789ab Lighthouse study done 3/3 nodes, 1 cached cost $0.050 (estimate ~$0.067) 1 image(s): ~/.agentos/flows/outputs/flw_2af4f4b5/Lighthouse-study_run_0123456789ab_1.png 1024x1024 ``` Exit codes: 0 when the run is `done`; 1 when it failed, was cancelled or is still going at the timeout (it keeps running; check `agentos flows runs`); 2 for an input the engine refuses (unknown flow, a name that is not a public input, a graph that does not validate: each node error is printed). With `--json`, stdout is one summary object (`run_id`, `status`, `images[]` with `path`, `sha256`, `width`, `height`, `cost_usd`, `est_usd`, `cached`, `nodes {done,total}`, `estimate` (the total Price), `error`, `node_errors`, `timed_out`) and errors are a JSON envelope on stderr. Runs started here carry `origin: "cli"` and show up live in the editor. Like every gateway-backed command, `agentos flows` connects to `AGENTOS_GATEWAY_URL`, else the port in the file `AGENTOS_GATEWAY_CONFIG_PATH` names, else `ws://localhost:18791/ws`; `AGENTOS_STATE_DIR` alone does not move it (point `AGENTOS_GATEWAY_URL` at a gateway on another port). Running a flow spends money, so `flows run` and `flows stop` are the user's actions: from an agent's shell (an agent-bound connection) the gateway refuses them with `flows.operator_required`. Agents use `flow_run` instead. ## Agent tools Three built-in tools let an agent use the flows you built (three more let it build and edit them: see [Agents can build flows](#agents-can-build-flows)). All are in the deferred set (the model loads them with `tool_search`), and all are offered only while `[flows].enabled` is on and at least one image model has a key. - `flow_list()` returns each flow's id, name, node count and public inputs with their current values, plus the default model and the agent cost limit. - `flow_publish(flow?)` posts the images of a flow's latest run that made images to the chat, without running anything (free). With no `flow`, it takes the most recent such run of any flow. Use it for a result you made in the editor: one artifact per image of the run. The `media/` store under the flows state directory is not a list of results: Save re-encodes each image to add the flow's metadata and stores that as a second blob, so one picture is two files there. - `flow_run(flow, inputs?, wait_seconds?)` runs a flow by id or exact name, with `inputs` overriding public inputs only. The tool descriptions steer the model to `flow_run` when you ask to run or reuse a flow you built, and to `image_generate` for a one-off picture. When `image_generate` is not available (off, or no key) but flows are, the system prompt tells the model that it can make the picture you ask for by running one of your flows, and that it should ask you to create one in the Flows editor when none fits; the tools never create a flow themselves. Their descriptions carry the words image, picture, draw, photo and illustration, so `tool_search` finds them for an image request. **The cost gate.** `flow_run` asks the engine for the estimate before anything is queued. A known estimate at or under `[flows].agent_cost_limit_usd` (default $0.50) runs at once. A higher estimate, or one that cannot be known, goes through the approval queue: you see "Runs the Image Flow 'Lighthouse study' for an estimated ~$0.27, above the $0.50 agents may spend per run without asking" in the same prompt that guards shell commands, and the turn waits for you. The approval is bound to that flow, its revision and those inputs; the run is then capped at the approved amount (if the estimate rose in between, nothing is queued and the agent is told). The prompt has its own approval namespace, `flow`, and offers only allow once or deny: no "Always Allow" and no "Stop Asking" (the gateway ignores both for this namespace), so approving one run never unlocks the next, and a session bypass of shell prompts never approves a spend. **A "no" sticks.** Denied, the agent gets a refusal that tells it plainly not to retry or work around it (fewer images, other inputs, a cheaper model, another flow, `image_generate`) unless you ask, and nothing is spent. For the next 30 minutes every `flow_run` of that flow in that session needs a fresh approval, even one under the limit; the prompt says "You declined a run of the Image Flow ... N min ago". A prompt the agent stopped waiting for counts when you decline it later. Approving such a prompt lifts the block. Other sessions and other flows are not affected; the memory is in the gateway process, so a gateway restart clears it. (A new chat message is not taken as consent on its own: whether it "asks again" cannot be told reliably, so the fresh approval prompt is the consent.) The approval mode applies as usual (`auto-approve` runs without a prompt, `auto-deny` refuses and counts as a "no"); an unattended run (cron, heartbeat) refuses instead of waiting. Direct tool calls over HTTP (`/tools/invoke`) never run `flow_run`. **One-off variants.** `flow_run(flow, overrides={"<image node>": {...}})` changes `model`, `count`, `aspect`, `resolution`, `size`, `quality` or `background` of an image node for that run only; the saved flow stays as it is. The cost gate uses the overridden estimate, and an approval is bound to those overrides (approving 2 images does not approve 4). The agent uses this for "make 4 of these with GPT Image 2" instead of saving that configuration. `count` stays at most 4 per image node: for more, the agent runs again (each run cost-gated on its own) or asks whether 4 will do. The tool waits for the run (`wait_seconds`, default 300, at most 900). A run still going then keeps running; the tool says so and the card updates when it ends. Stopping the turn stops its run. **What lands in the chat.** Each PNG a Save node writes is published into the session as an image artifact while the run executes (channels deliver them like any generated image), and a run card is published ahead of them: - **Run card** (`application/vnd.agentos.flow-run+json`): the flow name, the status, node progress `n/m` with a bar, the cost (or the estimate while it runs), the cached count and thumbnails. The card re-reads the run with `flows.run.get` whenever it is drawn and follows the `flows.run` / `flows.node` events while the run is going, so a reload or a re-render never shows a stale snapshot. Thumbnails come from `flows.media` (256 px). It is read-only. On the desktop it has **Open in Flows**, which opens the flow in the editor; the web console has no editor and no button. The tool's result (what the model reads) carries `status`, `run_id`, `flow {id, name}`, `images[]` (`path`, `sha256`, `width`, `height`, `artifact_id`), `cost_usd`, `est_usd`, `cached`, `nodes {done, total}`, `error`, `node_errors` and the published `artifacts`. ### The card payload ```json { "version": 1, "kind": "flow_run", "run_id": "run_0123456789ab", "flow_id": "flw_2af4f4b5", "flow_name": "Lighthouse study", "status": "done", "origin": "agent", "progress": {"done": 3, "total": 3}, "cached": 1, "est_usd": 0.0672, "cost_usd": 0.05, "images": [{"sha256": "…", "mime": "image/png", "width": 1024, "height": 1024, "name": "Lighthouse-study_run_0123456789ab_1.png"}], "error": null, "created": "2026-10-29T10:00:00Z", "ended": "2026-10-29T10:00:21Z", "fetchedAt": "2026-10-29T10:00:21Z" } ``` `images` lists what the Save nodes wrote, or the generated images when the flow has no Save node (`name` is then null). `progress.done` counts `done` and `cached` nodes. A client that has the run (`flows.run.get`) derives the same fields from the RunRecord. ## Agents can build flows An agent can also create and edit your flows from the chat, with three more tools in the deferred set (found by `tool_search` for "create flow", "build workflow", "pipeline", "automate images", "edit flow", "add node"). Building a flow costs nothing, so there is no approval step; **running** it is still `flow_run`, with its cost gate. No tool deletes a flow, and every save, yours or the agent's, keeps the previous version: the editor's version history lists each revision with its author (you or the agent, and the chat it came from) and restores any of them. - `flow_get()` returns the node catalog (types, inputs with their widgets, options and defaults, outputs), the image models (availability, edit support, how many reference images, ratios, prices) and the spec format. `flow_get(flow)` returns that flow as a spec, its revision, who created it, and its public inputs. - `flow_create(spec)` validates the spec, lays the nodes out and saves a new flow marked as created by the agent. - `flow_update(flow, spec, base_rev)` replaces the graph of an existing flow (yours or the agent's). `base_rev` is required: the revision the agent read with `flow_get` (or got back from its last save). If the flow changed since (you edited it, or restored an older version), nothing is saved and the agent is told the current revision and what changed, so it reads the flow again and re-applies only the change you asked for; it never writes a graph from memory over yours. Nodes keep their place by id, new ones are placed for them; the name stays unless the spec renames it. The result says what changed in one line. A spec has no positions and writes links as pairs: ```json {"name": "AgentOS infographic", "nodes": [{"id": "ref", "type": "load_image", "title": "Style reference", "values": {"image": {"attachment": "latest"}}}, {"id": "content", "type": "text", "values": {"text": "..."}}, {"id": "gen", "type": "image", "values": {"model": "surplus/gpt-image-2", "aspect": "21:9"}}, {"id": "out", "type": "save"}], "links": [["ref.image", "gen.images"], ["content.text", "gen.prompt"], ["gen.image", "out.images"]], "inputs": {"content": "content.text"}} ``` A `load_image` value may be an image already in the Flows media store, or: - `{"attachment": "latest"}`: the image you attached most recently in this chat (`"2"` is the one before, and so on), or its file name, or `{"attachment": "<sha256>"}`; - `{"attachment": "<artifact id>"}`: an image published in this chat (for example a flow run's saved PNG, whose `artifact_id` the agent sees); - `{"path": "<file>"}`: a PNG, JPEG, GIF or WebP inside the agent's workspace. Anything outside it (an absolute path elsewhere, `..`, a symlink that leads out) is refused. Chat images are read from this chat's transcript, where the gateway records each message you send with its attachments: an image up to 2 MB is stored in the message itself, a larger upload in the session's attachment store. An image from another chat cannot be reached, and the agent is told never to search the disk for your images; if it cannot find one, it asks you to attach it again. A spec that does not validate is not saved: the agent gets each problem by node (an unknown node type, a missing prompt, a model without edit support for a reference image, an image it could not resolve) and fixes it. A model whose provider has no key yet only matters at run time, so that saves with a warning. After a save the chat shows a **change card** (`application/vnd.agentos.flow-change+json`): the flow's name, created or updated, the one-line summary, the node count, the estimate per run and the revision; on the desktop it has **Open in Flows**. The agent then says what the flow does and offers to run it; it runs it straight away only when you asked for the image now. ```json {"version": 1, "kind": "flow_change", "flow_id": "flw_2af4f4b5", "name": "AgentOS infographic", "rev": 1, "change": "created", "summary": "created with 4 nodes and 3 links", "node_count": 4, "estimate": {"kind": "usd", "usd": 0.27, "approximate": true}, "fetchedAt": "2026-10-30T10:00:00Z"} ``` Direct tool calls over HTTP (`/tools/invoke`) never run `flow_create` or `flow_update`; `flow_get` is read-only. ## Configuration ```toml [flows] enabled = true # off: runs are refused (editor, CLI, agent tools) and the tools are hidden max_concurrent_runs = 1 # 1-8; further runs wait in a FIFO queue agent_cost_limit_usd = 0.50 # an agent's flow_run above this (or unknown) needs approval cache_max_mb = 500 # node cache size, least recently used evicted first ``` Environment overrides: `AGENTOS_FLOWS_ENABLED`, `AGENTOS_FLOWS_MAX_CONCURRENT_RUNS`, `AGENTOS_FLOWS_AGENT_COST_LIMIT_USD`, `AGENTOS_FLOWS_CACHE_MAX_MB`. For example `agentos config set flows.agent_cost_limit_usd 1.00`. State lives under `<state_dir>/flows/` (`~/.agentos/flows/` by default): `<flow_id>.json` flow documents, `flows.db` (runs and the node cache), `media/` content-addressed images (and their thumbnails), `surplus_catalog.json`, and `outputs/<flow_id>/` the PNG files Save writes. ## RPC and events Control surface (`flows.*`). Reads are open to every control connection; everything that writes or spends (`create`, `save`, `delete`, `run`, `stop`, `upload`, `import_png`) is refused on an agent-bound connection with `flows.operator_required`. | Method | Params | Result | | --- | --- | --- | | `flows.nodes` | – | node catalog (types, inputs, outputs, prices) | | `flows.models` | – | `{default, models[]}` with availability and prices | | `flows.list` | – | `{flows: [{id, name, rev, updated, node_count, preview}]}` | | `flows.create` | `{name, template?}` (`blank`, `text_to_image`, `edit_image`, `describe_remix`) | `{flow}` | | `flows.get` | `{id}` | `{flow}` | | `flows.save` | `{flow, base_rev}` | `{flow}`; `flows.conflict` when the stored revision moved | | `flows.delete` | `{id}` | `{ok}` | | `flows.validate` | `{flow, to_node?}` | `{ok, node_errors}` | | `flows.estimate` | `{flow, to_node?, inputs?}` | `{nodes, total, will_run, cached}` | | `flows.run` | `{flow_id, flow?, inputs?, to_node?, origin?}` (`canvas` or `cli`) | `{run_id, status: "queued"}` | | `flows.stop` | `{run_id}` | `{ok}` | | `flows.runs` | `{flow_id?, limit?}` | `{runs: [RunSummary]}` newest first | | `flows.run.get` | `{run_id}` | `{run: RunRecord}` (summary + inputs, graph, nodes, outputs, to_node, estimate, seq) | | `flows.media` | `{sha256, max_side?}` | `{mime, data_b64, width, height}` | | `flows.upload` | `{name, mime, data_b64}` | `{image}` | | `flows.import_png` | `{data_b64}` | `{image, flow}` (the graph a saved PNG carries, not saved) | Error codes: `flows.not_found`, `flows.conflict`, `flows.invalid` (`details.node_errors`), `flows.busy`, `flows.unavailable`, `flows.cost_gate` (`details.estimate`, `details.limit_usd`), `flows.operator_required`. Events go to control connections; each carries `run_id`, `flow_id` and a per-run increasing `seq`. Clients that reconnect read `flows.run.get`. - `flows.run` `{run_id, flow_id, seq, status, est_usd?, cost_usd?, error?}` - `flows.node` `{run_id, flow_id, seq, node_id, state, progress?, ms?, cost_usd?, outputs?, error?}` - `flows.changed` `{flow_id, rev, deleted?}` after a create, save or delete. --- # ACP Coding Harnesses > Source: https://useagentos.dev/docs/core/acp-agents AgentOS can hand coding work to an external coding agent (Claude Code, Codex, Gemini CLI, Cursor, GitHub Copilot, OpenCode and 20 more) and get the result back as a normal child session. It talks to each one over the [Agent Client Protocol](https://agentclientprotocol.com) (ACP): AgentOS is the ACP *client*, the harness runs as an ACP *agent* subprocess speaking JSON-RPC over stdio. Compared with running `codex exec` or `claude -p` in a background shell, the ACP route gives you: - one structured event stream (text, tool calls, plans, usage) instead of scraped terminal text; - harness permission prompts routed to the AgentOS approval queue (or answered by a policy you choose); - resumable sessions, cancel, and a per-turn wall-clock limit; - process leases, so no harness outlives the gateway; - token and cost accounting on the child session (USD when the harness reports it; Claude Code does); - a completion pushed back to the parent session with a `Stats:` line. The design follows OpenClaw's `acpx` runtime (MIT); see [THIRD_PARTY_NOTICES.md](https://github.com/use-agent-os/agent-os/blob/main/THIRD_PARTY_NOTICES.md). ## Quick start ```sh agentos acp list # every harness and how it would launch agentos acp doctor claude # CLI on PATH? adapter installed? agentos acp doctor claude --probe # spawn it and run ACP initialize (30 s cap) agentos acp run claude "Summarize this repo in five bullets" --cwd ~/code/app ``` `agentos acp run` needs no gateway: it starts the harness on this machine, sends one prompt, streams the reply and prints a stats line. From a chat, ask the agent to delegate instead ("have Claude Code fix the failing test in ~/code/app"); it calls `sessions_spawn` with `runtime="acp"`. ## Supported harnesses `id` is what you pass to `--agent` / `acp_agent`. Aliases such as `claude-code`, `gemini-cli`, `github-copilot`, `cursor-agent`, `factory-droid`, `kilo`, `kimi-cli`, `kiro-cli`, `qwen-code` and `grok` resolve to the same ids. | id | Harness | Default launch | Needs on PATH | | --- | --- | --- | --- | | `claude` | [Claude Code](https://claude.ai/code) | `npx -y @agentclientprotocol/claude-agent-acp@^0.91.0` (or `claude-agent-acp` when installed) | `claude` | | `codex` | [Codex CLI](https://developers.openai.com/codex/cli) | `npx -y @agentclientprotocol/codex-acp@^2.2.2` (or `codex-acp`) | `codex` | | `gemini` | [Gemini CLI](https://github.com/google-gemini/gemini-cli) | `gemini --acp` | `gemini` | | `cursor` | [Cursor CLI](https://cursor.com/docs/cli/acp) | `cursor-agent acp` | `cursor-agent` | | `copilot` | [GitHub Copilot CLI](https://docs.github.com/en/copilot/concepts/agents/copilot-cli/about-copilot-cli) | `copilot --acp --stdio` | `copilot` | | `opencode` | [OpenCode](https://opencode.ai) | `npx -y opencode-ai acp` (or `opencode acp`) | - | | `pi` | [Pi Coding Agent](https://github.com/earendil-works/pi) | `npx pi-acp@^0.0.33` (or `pi-acp`) | `pi` | | `droid` | [Factory Droid](https://www.factory.ai) | `droid exec --output-format acp` | `droid` | | `grok-build` | [Grok Build](https://docs.x.ai/build/overview) | `grok agent stdio` | `grok` | | `iflow` | [iFlow CLI](https://github.com/iflow-ai/iflow-cli) | `iflow --experimental-acp` | `iflow` | | `junie` | [Junie](https://github.com/openclaw/acpx/blob/main/agents/Junie.md) | `junie --acp=true` | `junie` | | `kilocode` | [Kilo Code](https://kilocode.ai) | `npx -y @kilocode/cli acp` (or `kilo acp`) | - | | `kimi` | [Kimi CLI](https://github.com/MoonshotAI/kimi-cli) | `kimi acp` | `kimi` | | `kiro` | [Kiro CLI](https://kiro.dev) | `kiro-cli-chat acp` | `kiro-cli-chat` | | `mcode` | MiniMax Code | `mcode acp` | `mcode` | | `mux` | [Mux](https://mux.coder.com) | `npx -y mux@^0.28.0 acp` | - | | `pool` | Poolside | `pool acp` | `pool` | | `qoder` | [Qoder CLI](https://docs.qoder.com/cli/acp) | `qodercli --acp` | `qodercli` | | `qwen` | [Qwen Code](https://github.com/QwenLM/qwen-code) | `qwen --acp` | `qwen` | | `trae` | [Trae CLI](https://docs.trae.cn/cli) | `traecli acp serve` | `traecli` | | `zeroclaw` | ZeroClaw | `zeroclaw acp` | `zeroclaw` | | `devin` | [Devin](https://github.com/openclaw/acpx/blob/main/agents/Devin.md) | `devin acp` | `devin` | | `fx` | [fx](https://github.com/openclaw/acpx/blob/main/agents/Fx.md) | `fx acp` | `fx` | | `fast-agent` | [fast-agent](https://fast-agent.ai) | `uvx fast-agent-mcp acp` | `uvx` | | `antigravity` | [Google Antigravity](https://github.com/openclaw/acpx/blob/main/agents/Antigravity.md) | `agy_acp_server.par` (`--uid=` on Linux, `.exe` on Windows) | the same binary | | `openclaw` | [OpenClaw ACP bridge](https://github.com/openclaw/acpx/blob/main/agents/OpenClaw.md) | `openclaw acp` | `openclaw` | Launch order: an `[acp.agents.<id>]` override wins, then an installed adapter binary on `PATH`, then the zero-install `npx` / `uvx` form. `agentos acp list` shows which one each id would use (`override`, `installed`, `package-exec`) and which required CLIs are missing. ## Setup per harness AgentOS never signs in for a harness. Install its CLI and log in once, as the same OS user that runs the gateway; the harness keeps its own credentials and billing. - **Claude Code**: `npm install -g @anthropic-ai/claude-code`, then run `claude` once and log in (subscription OAuth), or export `ANTHROPIC_API_KEY`. Optional: `npm install -g @agentclientprotocol/claude-agent-acp` to skip the first-run download. Reports USD cost per turn. - **Codex**: `npm install -g @openai/codex`, then `codex login` (ChatGPT plan) or export `OPENAI_API_KEY`. Optional: `npm install -g @agentclientprotocol/codex-acp`. With `isolate_codex_home = true` (default) the harness gets its own `CODEX_HOME` under `<state>/acp/codex-home/`: your `~/.codex/auth.json` is copied in, the session directory is marked trusted, and only `model`, `model_provider`, `model_reasoning_effort`, `sandbox_mode` and `[model_providers.*]` are inherited from your `~/.codex/config.toml`. Session modes: `read-only`, `workspace-write`, `full-access`. Codex reports tokens, not USD. - **Gemini CLI**: `npm install -g @google/gemini-cli`, run `gemini` once to log in, or export `GEMINI_API_KEY`. - **Cursor**: install the Cursor CLI and run `cursor-agent login`. If your install exposes ACP as `agent acp`, set an override (below). - **GitHub Copilot**: `npm install -g @github/copilot`, then `copilot login`. Usage counts against your Copilot plan. - **Everything else**: install the CLI from the link in the table, sign in with its own login command, then check with `agentos acp doctor <id> --probe`. Credentials the harness reads from the environment (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `GEMINI_API_KEY`, its OAuth files) pass through to it. AgentOS's own secrets do not: every harness environment is scrubbed of `AGENTOS_*`, gateway tokens, channel bot tokens and anything named `*_TOKEN`, `*_SECRET` or `*_PASSWORD`. Add what a harness needs with `[acp.agents.<id>] env`. ## Using it from a chat The main agent delegates with `sessions_spawn`: ```json { "task": "Fix the failing test in tests/test_api.py and run pytest.", "runtime": "acp", "acp_agent": "claude", "cwd": "/path/to/app", "mode": "oneshot" } ``` | Parameter | Meaning | | --- | --- | | `runtime` | `"acp"` routes to a harness; the default `"subagent"` is an in-process AgentOS agent. | | `acp_agent` | Harness id (default `[acp] default_agent`). Must be in `allowed_agents`. | | `cwd` | Working directory (default: the agent workspace). Must be inside the workspace, a managed worktree or an `[acp] allowed_cwds` entry; see [Working directory](#working-directory). | | `mode` | `oneshot` (default for spawn): the harness process exits after each turn, and a follow-up resumes the same harness session in a new process. `persistent`: the process stays up between turns. | | `harness_mode` | ACP session mode id the harness advertises (`read-only`, `acceptEdits`, `plan`, ...). | | `resume_session_id` | Carry a closed child's harness conversation (its `acp_session_id`) into a new child. A finished or stopped child is continued with `sessions_send` to its key instead; a session key passed here is refused with that advice. | | `worktree`, `worktree_name`, `worktree_base_ref` | Run in a managed git worktree under `<state>/acp/worktrees/` instead of the checkout itself. | The child session key looks like `agent:main:acp:1a2b3c4d`. After spawning, the agent calls `sessions_yield`; the harness's final answer comes back to the parent as a completion message with a stats line such as `Stats: runtime 5m12s • tokens 48210 (in 45100 / out 3110) • cost $0.4120`. The completion (the live `session.event.subagent_completion` event and the parent's system message) also carries `runtime: "acp"`, `acp_agent`, `acp_agent_name`, `cwd`, `mode`, `harness_mode` and a structured `usage` object (`duration_ms`, `input_tokens`, `output_tokens`, `total_tokens`, `cost_usd`, `tool_calls`; `null` when the harness did not report a value). Other subagent completions carry `runtime: "subagent"`. The completion's `result.text` is the harness's final answer: the text runs of the turn (split by tool calls) from the last substantial one (at least 40 characters and half the longest run) to the end, so interim "Now reading X." lines are dropped and a report followed by a tool call and a closing remark is kept; the whole text when no run qualifies. The child transcript keeps everything, with text runs separated by a tool call as separate paragraphs. `result.text` holds up to 12,000 characters and `result.full_chars` the answer's whole length; when it was cut, the parent's wake says so ("The answer was cut at 12,000 of 17,116 characters; read the rest with sessions_history(session_key=..., answer_offset=12000) - do not redo the work.") and `sessions_history(session_key, answer_offset=N)` returns the rest of that same answer in pages of up to 3,900 characters (sized so a page reaches the model whole, now and in later turns) with a `next_offset`. Otherwise `sessions_history` on an ACP child clips each tool input and result to 500 characters (`[…N chars]`) so the harness's own text is not lost to truncation. When the user stops a run (the card or bar Stop, `acp.cancel`, `acp close`, the child chat's Stop), the completion carries `stopped_by: "user"`, a `terminal_message` for the parent that its wake shows as well ("The user stopped this Claude Code run after N tool calls (m:ss). Do not restart it; tell the user what was done so far and ask how to continue.") and a `user_message` for the chat ("You stopped this Claude Code run after N tool calls (m:ss)."). When the parent stops its own child (`subagents kill`), the completion says `stopped_by: "agent"` ("Stopped by the agent after ...") and is recorded in the parent transcript without waking the parent, which already answered in the turn that stopped it. A parent's `steer` replaces the turn and is not reported as a stop. The stopped turn's `last_turn` carries `stopped_by` and a `summary` ("Stopped by you after 3 tool calls (0:18).") instead of an error text. To continue a child, `sessions_send` to its key: `followup` queues the text as the next turn, `steer` cancels the running turn and sends the new text. This works for a finished `oneshot` child too: the harness starts again with the recorded ACP session (`session/load`) and closes after the turn. If the harness cannot resume it, a fresh harness session starts in the same `cwd` and the turn's text begins with "Started a new `<harness>` session; the previous context could not be resumed." The user can also type into the child session directly; those turns are not announced to the parent. Only a session closed by an operator (`acp.close`, `agentos acp close`, `subagents kill`) refuses new turns; the refusal is logged (`acp.dispatch.turn_refused`), written to the child transcript as an `Error:` row for the person reading it ("This Claude Code session has ended. Start a new chat to continue.") and sent as the normal `error` event, whose `error_message` carries the agent-facing detail (spawn a new one, `resume_session_id=...`). `subagents` lists ACP children with `runtime: "acp"`, `acp_idle` (finished, takes follow-ups) and `acp_closed`; `kill` cancels and closes one. `subagents` is a deferred tool: spawning a harness loads it (otherwise one `tool_search` does). `acp.cancel` and `acp.close` refuse a key that is not an existing ACP session. The operator-only `acp` tool (not exposed by default) offers `agents`, `sessions`, `status`, `cancel`, `close`, `set_mode`, `set_model` and `doctor`. ## Working directory With the default `[acp] allowed_cwds = []`, a harness may run in the agent workspace and in managed worktrees (`worktree: true`), nowhere else. - Read-only work (a review, a summary, an investigation) may run in the agent workspace when the spawn uses a read-only `harness_mode` (`plan` for Claude Code, `read-only` for Codex). - Work that writes files belongs in the project's own checkout: add it to `allowed_cwds`, or spawn with `worktree: true` from a repository that is already allowed. - A refused `cwd` fails the spawn with `ACP_CWD_NOT_ALLOWED`. The error tells the agent to check its guess first (a folder named in the task usually lives in the agent workspace) and, if the task really targets that directory, gives the exact command that allows it (the list is replaced as a whole, so keep the entries you already have): ```sh agentos config set acp.allowed_cwds '["~/Code/my-app"]' ``` ## Permission modes Harnesses ask before they edit files or run commands. `[acp] permission_mode` decides who answers: | Mode | Behaviour | | --- | --- | | `ask` (default) | The prompt goes to the approval queue (namespace `acp`) and shows up in the Web UI / desktop / CLI approvals like any other approval. No answer within `approval_timeout_s` = rejected. | | `approve-reads` | Reads, searches, fetches and thinking are allowed; anything else follows the `ask` path. | | `approve-all` | Everything is allowed. Only this mode may answer "always allow". | | `deny-all` | Everything is rejected; the harness continues without the tool. | Answering an `ask` prompt with **Always allow** skips later prompts of the same kind in that harness session. For commands the grant covers one program and subcommand: Always allow on `git log --oneline` covers `git log -p` but not `git status`. The program is matched by the absolute path it resolves to on the gateway's `PATH`, so `/tmp/x/git push` or `./git push` still asks. These commands always ask, even after Always allow: - anything with `;`, `&`, `|`, `<`, `>`, `$`, a backtick, `(`, `)`, `{`, `}`, `\` or a line break, quoted or not (chaining, pipes, redirection, substitution, expansion); - a `VAR=value` prefix, a relative program path, or a program that does not resolve; - shells and wrappers that run another command (`bash`, `sh`, `env`, `sudo`, `xargs`, `eval`, `nohup`, `timeout`, ...). `bash -lc '<command>'` is matched by the one command inside; - programs that delete data or run whatever code they are handed, under any arguments: `rm`, `rmdir`, `unlink`, `dd`, `mkfs*`, `shred`, `truncate`; interpreters (`python`, `python3*`, `py`, `node`, `deno`, `bun`, `ruby`, `perl`, `php`, ...); every shell (`sh`, `bash`, `zsh`, `fish`, `dash`, `pwsh`, `powershell`, `cmd`, ...); package runners and build tools that run a file the harness can edit (`uvx`, `npx`, `make`, `just`); `docker`, `podman`, `kubectl`, `curl`, `wget`; - subcommands that run a package or script, or publish or discard work, wherever they appear in the command (`uv --quiet run` counts): `uv run`, `uv tool run`, `pipx run`, `poetry`/`pdm`/`hatch`/`pixi`/`conda run`, `npm exec`/`run`/`test`/`start`, `pnpm dlx`/`exec`/`run`, `yarn dlx`/ `exec`/`run`, `cargo run`, `go run`/`generate`, `git push`, `reset`, `clean`, `checkout` (a path checkout discards changes; `git switch` stays rememberable), `restore`, `rm`, `stash drop`/`clear`, `switch -f`, and `git -c`/`--config-env`/`--exec-path`; - `chmod`, `chown` or `chgrp` with `-R`/`--recursive`, and `find` with `-delete`, `-exec`, `-execdir`, `-ok` or `-fprint*`; - a command that does not parse (an unbalanced quote). The program is recognised by its file name, lower-cased and without an `.exe`, `.cmd`, `.bat`, `.ps1` or `.com` suffix, and by the name of the file a link points to, so `C:/Tools/Python.EXE`, `npx.cmd` and a link named `ls` to `python3` all ask. A grant remembered before this rule never answers one of these prompts. With `ask` and nobody able to answer (cron, unattended runs), `non_interactive_permissions = "fail"` fails the turn with `ACP_PERMISSION_PROMPT_UNAVAILABLE`; `"deny"` rejects and lets the harness carry on. Harness questions (ACP elicitation) go to the same queue under `acp_elicitation`; they are declined after 15 minutes. `agentos acp run` has no approval surface: it uses `approve-reads` with reject-instead-of-ask, unless you pass `--permissions approve-all` or `--permissions deny-all`. It declines harness questions. Never give `approve-all` to a harness working on a branch or pull request you have not read: a hostile repository can instruct the harness to run anything. ## Sessions, resume and cancel - Each harness session has a record in `<state>/acp/sessions/<record_id>.json`. A record is reused only when the harness id, working directory and launch command all match. - Resume uses ACP `session/load` when the harness supports it, otherwise a new harness session starts. If resuming fails, AgentOS retries once fresh, then reports `ACP_SESSION_INIT_FAILED`. - `persistent` sessions keep the harness process alive between turns until closed, cancelled or the gateway stops; `oneshot` sessions stop the process after every turn and stay resumable (`idle`) until an operator closes them. - A turn that has to resume (a oneshot follow-up, a persistent session after a gateway restart) but gets a fresh harness session instead starts its text with a one-line notice that the previous context was lost. - Cancel sends ACP `session/cancel`, waits 2 s, then stops the process group (SIGTERM, SIGKILL 750 ms later). A stopped turn keeps what it did in the child transcript (tool calls and any text) followed by a "Cancelled after N tool calls (m:ss)." row; its duration, tool calls and cost (when reported) still reach `last_turn` and the completion. - Cost: Claude Code reports a running total per ACP session, and a resumed session may carry it over. AgentOS keys its baseline by ACP session id, so each turn is charged only its increase; a reading below the baseline (the total restarted) is charged as it is. - One harness turn keeps up to 100,000 characters of text (the rest is marked as cut). While a turn runs, `activity` names the tool call in progress, "Thinking…" when none is running and no text has arrived, and "Writing the answer" while text streams. - Tool rows in a child transcript are titled with a short label built from the tool call ("Run git status", "Read ~/app/src/x.py", "Search TODO", "Fetch docs.python.org", "Looking up tools"); the ACP tool kind is in the row's `input.acp_kind`. - `turn_timeout_s` (0 = none) is a wall-clock limit per turn. A quiet harness is not a failed one; only the limit ends a turn. ```sh agentos acp sessions # live from the gateway, else the stored records agentos acp cancel agent:main:acp:1a2b3c4d agentos acp close agent:main:acp:1a2b3c4d --discard # also forget the resume record agentos acp run claude "continue" --resume <acp-session-id> ``` Gateway RPC for UIs: `acp.sessions` lists sessions with a live harness process; each row has `agent_name` (registry display name), `activity` (a short label of the current or last step, such as `Read ~/app/src/x.py`, `Run pytest -q` or `Writing the answer`), `activity_kind` (the ACP tool kind `read|edit|delete|move|search|execute|think|fetch|other`, or `text` while the answer streams), `turn_tool_calls` and, during a turn, `turn_elapsed_s`. `acp.status {session_key}` returns the same fields for any ACP session, live, idle or closed, plus `idle`, `closed`, `mode`, `harness_mode`, `cwd` and `last_turn`; a non-ACP key fails with `ACP_SESSION_INVALID`. `acp.cancel {session_key}` stops the running turn (and any queued one); `acp.close {session_key, discard?}` closes the session for good. ## Configuration All keys live under `[acp]` (see also [Configuration](https://useagentos.dev/docs/core/configuration#acp-coding-harnesses)): ```toml [acp] enabled = true # false = no ACP spawns, agentos acp run refuses default_agent = "claude" allowed_agents = ["*"] # ids sessions_spawn(runtime="acp") may launch permission_mode = "ask" # ask | approve-all | approve-reads | deny-all non_interactive_permissions = "fail" # fail | deny (ask mode with nobody to answer) approval_timeout_s = 900 turn_timeout_s = 0 # 0 = no wall-clock limit max_concurrent = 8 # live harness sessions per gateway (1-64) # state_dir = "~/.agentos/state/acp" isolate_codex_home = true install_missing_adapters = true # allow npx -y / uvx downloads on first use stream_delivery = "live" # live (text streams as it arrives) | final_only allowed_cwds = [] # extra dirs a harness may use as cwd (besides workspace / worktrees) [acp.agents.cursor] # per-harness override command = "agent" args = ["acp"] env = { HTTPS_PROXY = "http://127.0.0.1:8080" } ``` `command` + `args` replace the registry launch for that id; an entry with only `env` keeps the registry launch and adds variables. You can also add a harness that is not built in by giving it a new id and a `command`. State lives in `<state>/acp/` (default `~/.agentos/state/acp/`): `sessions/`, `leases/`, `codex-home/`, `worktrees/`, and `logs/<record_id>.stderr.log` (the harness's stderr, redacted, last 256 KiB). ## Troubleshooting Start with `agentos acp doctor <id> --probe`; it shows the exact launch command, missing CLIs, and whether ACP `initialize` succeeds. - **The first turn hangs for a minute.** The `npx` / `uvx` launch downloads the adapter on first use. Install it once (`npm install -g @agentclientprotocol/claude-agent-acp`, `npm install -g @agentclientprotocol/codex-acp`) and `doctor` shows `installed`. With `install_missing_adapters = false` the download is refused and `doctor` says so. - **`ACP_HARNESS_MISSING`.** The harness CLI is not on the gateway's `PATH`. Install it, or set `[acp.agents.<id>] command` to an absolute path. A gateway started by launchd or the desktop app may have a shorter `PATH` than your shell. - **Claude Code says it is not logged in.** Do not add `--bare` to a Claude launch override: bare mode skips OAuth and the keychain, so subscription logins stop working. Run `claude` once interactively to refresh the login, or export `ANTHROPIC_API_KEY`. - **Codex prints skill or frontmatter errors.** Codex loads skills from `~/.agents/skills`; a `SKILL.md` there with invalid YAML frontmatter makes it log errors (see `<state>/acp/logs/<record_id>.stderr.log`) and can fail the session. Fix or move that skill. - **Codex asks to trust the directory.** Leave `isolate_codex_home = true`; the isolated home marks the session directory trusted. With it off, run `codex` once in that directory and trust it. - **Harness processes left over after a crash.** Every harness gets a lease file in `<state>/acp/leases/` and an `AGENTOS_ACP_LEASE` marker in its environment. At gateway start, AgentOS stops leftover processes whose pid, command and marker match a stale lease, and never touches anything else. - **`ACP_AGENT_NOT_ALLOWED`.** The id is not in `[acp] allowed_agents`, or `[acp] enabled = false`. - **`ACP_CWD_NOT_ALLOWED`.** The spawn's `cwd` is outside the workspace, the managed worktrees and `[acp] allowed_cwds`. Run the `agentos config set acp.allowed_cwds ...` command from the error message. - **`ACP_SESSION_CLOSED`.** The session was closed by an operator (`acp close`, `subagents kill`). Spawn a new one; `resume_session_id` (in the error) continues the harness conversation. - **`ACP_UNAVAILABLE` from `agentos acp sessions/cancel/close`.** The running gateway has no ACP session manager (older build, or ACP disabled). `agentos acp list` / `doctor` still work locally. - **`ACP_PERMISSION_PROMPT_UNAVAILABLE`.** `permission_mode = "ask"` in a run nobody can answer. Choose `approve-reads` / `deny-all` for that agent, or set `non_interactive_permissions = "deny"`. Read next: - [Sessions and History](https://useagentos.dev/docs/core/sessions) - [Approvals and Permissions](https://useagentos.dev/docs/core/approvals-and-permissions) - [CLI Reference](https://useagentos.dev/docs/core/cli#acp-coding-harnesses) --- # Compaction and Cache Continuity > Source: https://useagentos.dev/docs/core/features/compaction-and-cache Long agent sessions need context management. AgentOS uses compaction, bounded history, tool-result projection, and cache-aware prompt placement to keep long-running tasks moving. Compaction is separate from memory. Memory is durable recall. Compaction is an active-session continuity tool. ## What Compaction Does When session history approaches the configured context budget, AgentOS can compact older transcript entries into a durable summary and keep the recent tail active. The goal is to preserve: - user goal; - current status; - open steps; - changed files and artifacts; - known failures; - important tool results; - next action. Compaction is not a guarantee that every old word remains model-visible. Export sessions or save files when exact historical text matters. ## User-Visible Lifecycle Depending on surface and trigger, users may see: - compaction started; - compaction skipped; - compaction completed; - compaction failed. When no compaction is needed, AgentOS uses this stable message: ```text Already within context budget; no compact was applied ``` That message is a no-op, not a failure. A compaction inside a turn records what triggered it, in the session summary's `trigger_reason` and in the lifecycle notice's `phase`: `agent_inline_preflight` (the request was about to exceed the threshold), `agent_inline_overflow` (the provider refused the request as too large) or `agent_inline_timeout` (a large request timed out twice; see [Retrying transient failures](https://useagentos.dev/docs/core/providers-and-models#retrying-transient-failures)). Records written before this distinction, and compactions with no known trigger, say `agent_inline_overflow`. Each compaction decision is also logged as `compaction.decision` with its trigger: at info level when it compacted or failed, at debug level when the request was simply under the threshold. ## When to Compact Manually Manual compaction is useful when: - the session is long and you are about to start a new phase; - a previous tool-heavy turn produced a lot of context; - the UI indicates context pressure; - you want the next answer to focus on the current state rather than the whole transcript. Avoid compact loops when the runtime says the session is already within budget. ## Passive Compaction Passive compaction happens when the next model request would take more than 85% of the model's context window (`preflight_compact_ratio` in `agentos.toml`, default `0.85`). The check runs before every model call -- the first one of a turn included -- and never after a reply has streamed, so compacting does not make the model answer the same step twice. It also never runs while a tool call is waiting for its result. A compaction replaces everything before the current turn with one summary, written by the session's own model. The current turn -- your message, its attachments and every tool step so far -- stays word for word. Only when the current turn alone is too large are its oldest finished tool steps folded into the summary as well; your message and the latest step are always kept. If passive compaction fails, the safest user response is usually: 1. let the current turn finish or fail cleanly; 2. export the session if exact history matters; 3. retry with a narrower request or manually save key artifacts; 4. enable diagnostics if the failure repeats. ## Prompt Cache Continuity Prompt caching works best when stable prompt parts stay stable. AgentOS keeps the conversation append-only: once a message has been sent to the model it is replayed byte for byte on every later request, in the same turn and in later turns. In practice: - the system prompt and tool definitions come first and stay the same between requests (workspace files and project knowledge are part of that cached system prompt); loading a deferred tool with `tool_search` appends its definition, which costs one cache write for the tool list; - the current time, the skills list and other per-turn context (memory recall, plan mode, ...) are added at the end of your message for that turn and stay there; each part is only repeated when it changes; - a tool result too large for the request is shortened once, before the model first sees it; when the turn ends, results and tool-call arguments longer than `[compaction] history_tool_result_max_chars` (default: 2% of the context window, 4k-12k characters) are kept as head/tail plus a handle to the full output for later turns. That happens once per turn, so the next request re-caches only the end of the previous turn; - compaction is the only thing that rewrites earlier context; - model/provider switches stay visible through diagnostics when they may affect cache continuity. Cache continuity is best-effort. Routing, tools, attachments, provider changes, or a large new context can reduce cache reuse. ### Prompt Cache Configuration Control prompt caching behavior via `agentos.toml`: ```toml [prompt_cache] mode = "auto" # "auto" | "on" | "off" ``` - `auto` (default): Enables prompt prefix caching when supported by the provider and model. - `on`: Forces prompt caching on for all requests. - `off`: Disables prompt caching. Environment variable override: `AGENTOS_CACHE_MODE=auto|on|off`. The legacy `prompt_cache.enabled` config key and `AGENTOS_CACHE_ENABLED` environment variable are deprecated and mapped to `mode` (`on`/`off`) automatically. ## Related Commands and Surfaces Manual compaction is primarily surfaced in chat and Web UI flows. For inspection and recovery: ```sh agentos sessions show <session-key> agentos sessions export <session-key> agentos diagnostics on ``` Sessions whose memory never landed are visible in `agentos doctor`. Automatic repair was removed; the raw transcripts remain on disk: ```bash agentos memory raw-fallbacks list ``` ## Best Practices - Keep important final artifacts in files or published artifacts. - Use memory for durable preferences and reusable project facts. - Use session export for exact old transcripts. - Use manual compaction before a new phase in a very long session. - Do not repeatedly compact a short or already-within-budget session. --- # Channels > Source: https://useagentos.dev/docs/core/channels Channels let AgentOS run from messaging platforms while sharing the same agent runtime as the CLI and Web UI. Use channels when you want the same agent to answer from Slack, Telegram, Discord, or plain email. ## Supported Channel Types Inspect your local install: ```sh agentos channels types agentos channels types --json agentos channels describe slack ``` This build exposes the following channel families: | Type | Label | Transport | Public URL needed | | --- | --- | --- | :---: | | `discord` | Discord | websocket | no | | `email` | Email (IMAP/SMTP) | polling | no | | `slack` | Slack | mixed | depends on mode | | `telegram` | Telegram | mixed | depends on mode | The local `channels describe <type>` output is the source of truth for required fields, secrets, extras, and restart behavior. ## Setup Flow Interactive setup: ```sh agentos configure channels ``` Add a channel explicitly: ```sh agentos channels add telegram --name personal ``` Add provider-specific fields as needed. Slack supports two modes: ```sh # Slack Socket Mode: outbound websocket, no public URL. agentos channels add slack --name team \ --field connection_mode=socket \ --field app_token=xapp-... \ --token xoxb-... # Slack Events API webhook: requires a public Request URL and signing secret. agentos channels add slack --name team-webhook \ --field connection_mode=webhook \ --field signing_secret=... \ --token xoxb-... ``` Restart the gateway process after config edits: ```sh agentos gateway restart ``` Verify runtime connection: ```sh agentos channels status agentos channels status personal --json ``` Saving a channel proves the config was written. `channels status` proves whether the running gateway loaded and connected it. ## Manage Channels ```sh agentos channels list agentos channels enable <name> agentos channels disable <name> agentos channels edit <name> agentos channels restart <name> agentos channels logout <name> agentos channels remove <name> ``` Use `gateway restart` after config changes. Use `channels restart <name>` only for an already-loaded live adapter. ## Sender Admission Every channel that can start an agent turn admits only senders the operator chose. A channel turn runs with the operator's tools (including the shell), so "anyone who can message the bot" must never be the default. | Channel | How senders are admitted | | --- | --- | | Telegram | Pairing, always (see [Telegram Account Pairing](#telegram-account-pairing)). | | Email | `allowed_senders` From-address allowlist (required). | | Discord, Slack | `allowed_user_ids` and/or `pairing_enabled`. With neither, nobody is admitted. | For Discord and Slack, set at least one of: - `allowed_user_ids`: comma-separated platform user ids that are always admitted. Discord ids are numeric snowflakes (Developer Mode › right-click the user › Copy User ID); Slack ids are member ids such as `U012ABCDEF` (profile › ⋯ › Copy member ID). - `pairing_enabled = true`: an unknown user who DMs the bot gets a one-time code, exactly like Telegram, and is admitted once you approve it with `agentos channels pairing approve <name> <code>`. Codes are only issued in DMs; group messages from unpaired users are ignored. ```sh agentos channels edit team --field allowed_user_ids=U012ABCDEF,U034GHIJKL agentos channels edit my-discord --field pairing_enabled=true agentos gateway restart ``` ```toml [[channels.channels]] type = "discord" name = "my-discord" token = "..." allowed_user_ids = ["123456789012345678"] pairing_enabled = false ``` The same admission decision gates every inbound path: DMs, group messages that @mention the bot (the mention is still required), slash commands, and interactive approval buttons (Discord message components, Slack block actions). A refused sender gets no reply unless pairing just issued them a code; a refused Discord slash command is answered with "not authorized" so the deferred interaction does not hang. A Discord or Slack channel with neither setting **fails closed**: it still connects and can deliver outbound messages (cron results, notifications), but refuses every inbound sender. The gateway logs `channel.admission_closed` at start, each refused message is logged as `channel.sender_not_admitted` with the sender id (copy it into `allowed_user_ids`), and `agentos doctor` reports `channel.<name>.admission_closed` with the fix commands. The MS Teams adapter (not yet exposed in the channel catalog) follows the same rules: `allowed_user_ids` holds Teams user ids (`29:…`, the activity `from.id`). Admitting a sender is your decision, never an agent's: a connection the gateway recognizes as an agent's (an agent token, a process it spawned, or one opened while an agent shell runs) is refused `channels.pairing.approve`, and any config write (`config.set` / `patch` / `apply`, `onboarding.channel.upsert`) that adds an id to a channel's `allowed_user_ids`. It may still deny, revoke, or remove ids. ## Email (IMAP/SMTP) The email channel needs no platform app registration — only IMAP and SMTP credentials for a mailbox the agent owns. Inbound is IMAP polling; outbound is SMTP, with `In-Reply-To`/`References` set so replies land in the originating thread. ```sh agentos channels add email --name inbox \ --field imap_host=imap.example.com \ --field imap_username=agent@example.com \ --field imap_password=<app-password> \ --field smtp_host=smtp.example.com \ --field from_address=agent@example.com \ --field allowed_senders=you@example.com,*@yourteam.example ``` Providers with two-factor authentication normally require an app password rather than the account password. Set `smtp_ssl=true` (and `smtp_port=465`) for implicit TLS; the default is STARTTLS on port 587. `imap_folder` picks the mailbox to poll and defaults to `INBOX`. Names with spaces (`Sent Items`, `Archive 2026`) are quoted per RFC 3501 before they go on the wire, so they need no quoting of your own; a name carrying a control character is rejected at channel start rather than at poll time. ### Access Control `allowed_senders` is a fail-closed From-address allowlist and is **required** — a channel with an empty list is rejected at config load, because an open inbox would let anyone who can send mail drive the agent. Entries are exact addresses (`you@example.com`) or domain patterns (`*@example.com`, equivalently `@example.com`). Mail from any other sender is logged and dropped without ever being queued. The allowlist also governs where a reply goes. `Reply-To` is set by the same sender the allowlist is meant to constrain, so it is honoured only when the address it names is itself on the list; otherwise the reply goes back to the `From` address and the off-list header is logged and ignored. The message is still processed — an off-list `Reply-To` redirects the answer, it does not make the mail untrusted. The adapter also refuses to answer itself and drops machine-generated mail — anything carrying `Auto-Submitted`, `X-Autoreply`, `List-Id`, `List-Unsubscribe`, or `Precedence: bulk`. Without that guard an autoresponder on the far end and the agent would reply to each other indefinitely. ### Threads and Sessions One mail thread is one session. The thread identity is the first id in `References`, falling back to `In-Reply-To` and then the message's own `Message-ID`, so a long back-and-forth keeps its context while a fresh email from the same person starts a fresh session. The thread routing table (which address and subject a reply goes back to) is rebuilt from each inbound message and kept in memory only, so a gateway restart does not affect replying to live conversations. A reply into a thread the table no longer knows -- a scheduled job or artifact delivery that fires after a restart, before the correspondent has written again -- is refused with `email.send has no recipient for unknown thread` rather than guessed: the thread key is the inbound `Message-ID`, which looks like a mailbox but whose domain the original sender chose. Cron and heartbeat deliveries that are configured with an address (cron `channel_id: "alerts@example.com"`, heartbeat `to:`) do not depend on the table. Quoted history below a reply is stripped before the text reaches the model, and HTML-only mail is flattened to text. Replies are sent as plain text: mail clients do not render Markdown, so the agent is told to answer without it. ### Attachments Inbound attachments are decoded and passed through the shared attachment pipeline under the same per-type size limits as every other channel; anything over the limit is dropped with a warning rather than truncated. Generated artifacts are mailed back into the same thread as attachments. Whole messages larger than `max_message_bytes` (25 MB by default) are skipped without being downloaded. ### Polling `poll_interval_s` (default 30) sets how often the mailbox is checked, and `max_messages_per_poll` (default 10) bounds one cycle. Handled mail is flagged `\Seen`; set `mark_seen=false` to leave the mailbox untouched, at the cost of re-reading the same messages on the next poll. There is no IMAP IDLE support — a failed poll is logged, surfaces in `agentos channels status`, and the loop retries on the next interval. ## Telegram Account Pairing Discord and Slack channels with `pairing_enabled = true` use this same flow and the same `agentos channels pairing` commands; everything below applies to them except the Telegram group settings. Telegram direct messages always require pairing. There is no Telegram admin/owner role and no open or allowlist mode. An unknown sender is stopped before commands or agent execution, then receives a one-time 8-character code. Any connected Control client can pair the sender from Settings › Channels or with: ```sh agentos channels pairing list personal agentos channels pairing approve personal ABCD2345 ``` Pairing survives gateway restarts. To review or disconnect a sender: ```sh agentos channels pairing list personal --json agentos channels pairing deny personal <telegram-user-id> agentos channels pairing revoke personal <telegram-user-id> agentos channels pairing clear-pending personal ``` Pairing codes expire after one hour. Requests are limited to one per account every 10 minutes and three pending accounts per configured Telegram channel. Five invalid approval attempts lock approval for one hour. Pairing state is stored outside the main config under `$AGENTOS_STATE_DIR/pairing` (by default `~/.agentos/pairing`) with `0600` filesystem permissions. Telegram groups are disabled by default. Enabling groups requires all three admission checks: the chat ID is explicitly configured, the sender is paired, and the bot is mentioned when `group_mention_required` is true. Configure the group posture during setup or with channel fields: ```sh agentos channels add telegram --name personal --token <bot-token> \ --field groups_enabled=true \ --field group_chat_ids=-1001234567890,-1009876543210 \ --field group_mention_required=true ``` ### Voice Transcription Telegram channels can automatically transcribe inbound voice messages, audio files, and video notes before routing them to the model. This requires global audio features to be enabled (with valid ElevenLabs Speech-to-Text credentials) and the following fields set: ```sh agentos channels add telegram --name personal --token <bot-token> \ --field transcribe_voice=true \ --field max_voice_duration_s=120 ``` Pairing is sender-level: the same paired sender may use direct messages and explicitly configured groups. Removing the pairing disconnects that sender from both surfaces immediately. ## Channel Command Authorization Channel admission runs before native or text slash-command dispatch. An unpaired Telegram sender, or a Discord/Slack sender who is neither in `allowed_user_ids` nor paired, cannot execute commands or start an agent turn. Once paired, the sender gets the channel command surface, including session and router operations such as `/new`, `/reset`, `/compact`, `/abort`, `/c0` through `/c3`, and `/auto`. Direct messages and configured groups use the same rules; there is no command privilege tier. `/restart [force]` is the one exception that is gated by configuration rather than by pairing: it asks the gateway to restart itself in place and is refused on every channel until the operator sets `[gateway_control] chat_restart = true` (see [Configuration](https://useagentos.dev/docs/core/configuration#gateway-control)). With the toggle on, any paired sender may use it; without it, the sender gets a reply naming the setting. The native command menus (Telegram, Discord, Slack) always list `/restart`, since they are registered once at channel start. A restart acknowledges first, drains the active turns (`force` cancels them), and posts "Gateway restarted" back into the same chat or thread once the new process is up. Messages that arrive while the gateway is draining get "The gateway is restarting; please send that again in a moment." and are not queued. Tool visibility is not derived from a sender role. It is resolved from the agent/global tool configuration, runtime capabilities, sandbox policy, and approval gates. Channel RPC exposure is a separate protocol boundary: channel clients receive only the explicitly registered channel-safe RPC methods, while Control-only configuration RPCs remain unavailable. `gateway.restart` is the one lifecycle RPC exposed to channels, behind the toggle above. ## Slack Modes Slack Socket Mode uses an outbound websocket and does not require a public Request URL. It requires the bot token (`xoxb-...`) plus an app-level token (`xapp-...`) saved as `app_token`. Slack webhook mode uses the Events API Request URL. It requires the bot token plus `signing_secret`, and the gateway must be reachable by Slack. The secret is mandatory, not advisory: without it the endpoint answers Slack's `url_verification` handshake and rejects everything else with `401`, because an unsigned POST cannot be attributed to Slack. Leave `webhook_path` empty or omit it to select the automatic path. The first enabled Slack webhook account in your config (by configuration order, not name) keeps `/slack/events` regardless of how many other webhook accounts are enabled — adding a second account never changes an already-configured account's Request URL. Every other enabled Slack webhook account with no explicit `webhook_path` gets `/slack/events/<account_name>`, for example `/slack/events/team-b`. Disabled entries and Socket Mode accounts do not affect this choice or count toward "first". A non-empty `webhook_path` always overrides the automatic path. You can set it with `agentos channels add slack --name team-a --field webhook_path=/slack/team-a/events` alongside the token and signing-secret fields above. Automatic account names (for every account but the first) must use letters, digits, `.`, `_`, `~`, or `-` and cannot be `.` or `..`; otherwise set an explicit path. Configure each Slack app's Events API and Interactivity Request URLs to use its matching public URL; use the same URL for slash commands (`command_request_url` or the exported manifest). Restart the gateway after changing paths. Duplicate channel webhook paths with overlapping HTTP methods cause a startup error naming the conflicting entries, instead of silently routing every request to the first account. Socket Mode does not register a webhook route and is unaffected. Leave `slack_channel_id` empty when the adapter should reply to the incoming conversation. Set it only when you want a default fallback channel. Enable `reply_in_thread` when replies should stay in Slack threads. ## Native Slash-Command Menus Telegram and Discord synchronize their native command menus when the adapter starts. The entries are derived from AgentOS's unified channel command registry, so they stay aligned with text `/command` dispatch. Slack requires slash commands to be declared in the Slack app manifest. To synchronize them automatically at adapter startup, configure `app_id`, `manifest_token`, and `command_request_url` on the Slack channel entry. The manifest token must be a short-lived Slack app configuration access token (`xoxe.xoxp-...`), not the Socket Mode app-level token (`xapp-...`). AgentOS exports the existing manifest first and replaces only `features.slash_commands` so unrelated app configuration is preserved. When those optional credentials are absent, print the manifest fragment with the public Request URL for the Slack webhook route and import it in the Slack app settings: ```sh agentos channels native-commands slack \ --request-url https://agent.example/slack/events ``` The command endpoint acknowledges Slack's form submission and routes the resulting `/command` through the same channel dispatcher. Keep text command interception as the fallback for platforms without native command menus. ## In-Flight Reply Feedback Slack, Discord and Microsoft Teams stream the reply itself: AgentOS posts one message as soon as text is available and edits it as the answer grows. Telegram does not stream by default. The chat shows Telegram's typing status for the whole turn, and the finished reply arrives in one go (split into several messages only past the 4096-character ceiling). Set `stream_replies = true` on a Telegram channel to live-edit instead: ```sh agentos channels add telegram --name personal --token <bot-token> \ --field stream_replies=true ``` A streaming Telegram channel edits at most once every 1.2 seconds — its rate limit is far stricter than Slack's — and rolls over into a second message when an answer passes the 4096-character ceiling. If Telegram starts answering `429`, the edit loop stops and the remainder is delivered as one final message instead of fighting the limiter; no text is lost either way. Forum topic replies go to the originating topic in both modes. Streaming adapters that also have a typing indicator — Discord, and Telegram with `stream_replies` — show it while the model is still thinking, and drop it the moment the first chunk reaches the chat. Nothing can be streamed until the first token exists, and with tool calls in the loop that wait is often tens of seconds, so the indicator covers exactly that gap and then hands the chat over to the live-edited message. Adapters without a streaming surface fall back to their native typing indicator for the whole turn. Telegram refreshes `sendChatAction` every four seconds in either mode, because Telegram clients expire the status after at most five seconds. Reply feedback is best-effort and never interrupts the underlying agent turn. ## Webhook Channels Slack webhook mode requires a public, provider-reachable URL. Telegram may require one depending on mode. Discord and email need none. For public channels: - bind the gateway to a reachable interface; - place it behind a trusted reverse proxy or tunnel; - configure auth; - check provider callback URLs and secrets carefully. Example bind for a controlled network: ```sh agentos gateway run --listen 0.0.0.0 --port 18791 ``` Do not expose an unauthenticated gateway to the public internet. ## Attachments and Artifacts Channel adapters can differ in attachment and artifact delivery behavior. AgentOS normalizes agent execution through the same runtime path, but the platform transport still controls file size limits, message threading, and download/upload capabilities. When a channel cannot deliver a large artifact directly, use the Web UI artifact card or session export as the recovery path. ## Troubleshooting If a channel does not respond: 1. Check config entries: ```sh agentos channels list ``` 2. Check runtime status: ```sh agentos channels status <name> --json ``` 3. Restart the gateway process after config changes: ```sh agentos gateway restart ``` 4. For webhook channels, confirm the public URL, provider callback secret, and gateway auth/network boundary. 5. For Discord and Slack, confirm the sender is admitted: look for `channel.sender_not_admitted` in the gateway log and run `agentos doctor`. See [Sender Admission](#sender-admission). --- # Providers and Models > Source: https://useagentos.dev/docs/core/providers-and-models AgentOS supports multiple LLM providers through one configuration surface. You can run direct single-model mode or enable Pilot Router for tiered routing. Use this page when you need to configure a provider, inspect model support, or choose between direct model mode and router mode. ## Inspect Providers List provider metadata from the local install: ```sh agentos providers list agentos providers list --json ``` Show runtime provider diagnostics from the running gateway: ```sh agentos providers status agentos providers status openrouter --json agentos providers status --probe-models ``` `providers list` does not require a running gateway. `providers status` does. ## Configure a Provider Interactive (the provider steps of `agentos onboard`, skipping channels and search): ```sh agentos configure provider ``` `agentos onboard` runs the full first-run wizard, which also covers channels and search. Non-interactive onboarding-style configuration: ```sh export OPENROUTER_API_KEY="sk-..." agentos configure provider --provider openrouter --api-key-env OPENROUTER_API_KEY export OPENCAP_API_KEY="ocap_..." agentos configure provider --provider opencap --api-key-env OPENCAP_API_KEY export SURPLUS_API_KEY="inf_..." agentos configure provider --provider surplus --api-key-env SURPLUS_API_KEY ``` When testing OpenCAP from a source checkout, prefix both configuration and gateway commands with `uv run` (for example, `uv run agentos gateway restart`). This keeps the config writer and restarting gateway on the same local schema instead of invoking an older globally installed AgentOS. Direct provider examples: ```sh agentos configure provider --provider openai --model gpt-5.4-mini --api-key-env OPENAI_API_KEY agentos configure provider --provider anthropic --model claude-sonnet-4-6 --api-key-env ANTHROPIC_API_KEY agentos configure provider --provider gemini --model gemini-2.5-flash --api-key-env GEMINI_API_KEY agentos configure provider --provider ollama --model llama3.1 ``` Prefer environment-variable references for API keys so secrets are not written directly into configuration files. Once a provider has a key or key reference configured, switch the active provider and model without prompts: ```sh agentos providers configure openrouter --model anthropic/claude-sonnet-4 ``` `providers configure` never prompts and has no `--api-key-env`; set the key with `agentos configure provider` first. ## Onboarding-Verified Providers This build exposes onboarding support for: - OpenRouter (default provider) - Bankr LLM Gateway - OpenCAP - Surplus Intelligence - OpenAI - Anthropic - Ollama - DeepSeek - Gemini - DashScope / Qwen - Moonshot AI - Zhipu / Z.AI - Baidu Qianfan - Volcengine Ark The provider registry may contain additional compatible providers for advanced or self-hosted setups. Use `agentos providers list` on your install for the current catalog. ### OpenCAP routing OpenCAP defaults to `https://gw.capminal.ai/api/inference/v1` and uses one OpenAI-compatible key for inference. Its public model catalog is unauthenticated. The default direct/fallback model is the balanced `c1` model, `claude-haiku-5.5`. The `recommended` router profile selects bare OpenCAP model IDs across [`c0`–`c3`](https://useagentos.dev/docs/core/features/pilot-router#model-tiers) and the vision route: | Tier | Model | Role | | --- | --- | --- | | `c0` | `claude-haiku-5.5` (low thinking) | trivial chat, short rewrites, extraction | | `c1` | `claude-haiku-5.5` (medium thinking) | default balanced route for normal agent work | | `c2` | `claude-sonnet-5.5` | multi-step coding, structured reasoning, larger synthesis | | `c3` | `claude-opus-5.5` | difficult planning, deep review, high-stakes synthesis | | `image_model` | `claude-haiku-5.5` | image attachments, screenshots, diagrams | These are OpenCAP's own defaults, not a copy of the Bankr profile — the two gateways publish overlapping but different catalogs. Run `agentos models list` against a configured OpenCAP key to see everything the gateway currently serves. At gateway boot, AgentOS fetches the public catalog asynchronously for model choices, capabilities, and provider-scoped cost estimates. If that fetch fails, configured models can still run with static capability and cost fallbacks. OpenCAP chooses the cheapest eligible upstream when no route is configured. To restrict one model to a supported upstream, use bare model IDs and an upstream provider ID advertised by the current live catalog: ```toml [llm.provider_routing] "claude-sonnet-5.5" = "provider-id-from-live-catalog" ``` AgentOS sends this as OpenCAP's provider allow-list. OpenRouter uses the same configuration table but retains its existing preferred-order payload. ### Surplus Intelligence routing [Surplus Intelligence](https://www.surplusintelligence.ai/) is a two-sided marketplace for inference: sellers list endpoints, buyers get routed to the cheapest healthy one, and settlement happens in USDC on Base. AgentOS talks to it as an ordinary OpenAI-compatible provider using a buyer API key (`inf_...`), so no wallet or on-chain payment support is required. It defaults to `https://api.surplusintelligence.ai/v1`. Its model catalog is public and unauthenticated. The default direct/fallback model is the balanced `c1` model, `claude-haiku-5.5`. The `recommended` router profile selects bare Surplus model IDs across [`c0`–`c3`](https://useagentos.dev/docs/core/features/pilot-router#model-tiers) and the vision route: | Tier | Model | Role | | --- | --- | --- | | `c0` | `claude-haiku-5.5` (low thinking) | trivial chat, short rewrites, extraction | | `c1` | `claude-haiku-5.5` (medium thinking) | default balanced route for normal agent work | | `c2` | `claude-sonnet-5.5` | multi-step coding, structured reasoning, larger context | | `c3` | `claude-opus-5.5` | difficult planning, deep review, high-stakes synthesis | | `image_model` | `claude-haiku-5.5` | image attachments, screenshots, diagrams | Surplus lists `claude-haiku-5.5` with a 100K context window and a 50K output cap, where OpenCAP publishes 1M and 128K for the same id. AgentOS sizes requests to the Surplus figures, so long sessions on `c0` and `c1` compact sooner here than on the other gateways. Because prices move with seller competition, cost estimates come from the live catalog rather than a static table. At gateway boot AgentOS fetches it once and reuses that response to seed pricing; the cache refreshes on its own TTL afterwards. Set `AGENTOS_SURPLUS_LIVE_PRICING=0` to pin estimates to the static table instead. If the fetch fails, configured models still run on static capability and cost fallbacks. Surplus routes to the cheapest eligible seller when no route is configured. To restrict one model to particular sellers, use bare model IDs and a seller ID advertised by the current live catalog: ```toml [llm.provider_routing] "claude-sonnet-5.5" = "seller-id-from-live-catalog" ``` AgentOS sends this as Surplus's provider allow-list, the same shape OpenCAP takes. ## Model Inspection List models: ```sh agentos models list ``` If runtime-backed model inspection cannot connect, start the gateway: ```sh agentos gateway run ``` For provider metadata that does not require the gateway, use: ```sh agentos providers list ``` ## Direct Model vs Router Direct model mode: ```sh agentos configure router --router disabled agentos configure provider --provider openai --model gpt-5.4-mini --api-key-env OPENAI_API_KEY ``` Router mode: ```sh agentos configure router --router recommended ``` | Mode | Use when | | --- | --- | | Direct model | You are testing one exact model, reproducing provider behavior, or auditing provider billing. | | Router mode | You want normal personal-agent use where cost and task complexity vary by turn. | For routing details, see [Pilot Router](https://useagentos.dev/docs/core/features/pilot-router). ## Provider Health Circuit Breaker Failover is health-aware. When the active provider returns consecutive provider-health failures — overload / gateway 5xx, transport errors, or rate limits — AgentOS opens a circuit breaker for that provider and sends the next turns straight down the fallback chain instead of paying the dead provider's timeout on every turn. - `failure_threshold` consecutive failures open the breaker (default `3`). Request-shaped failures (unknown model, bad request, context overflow, auth, billing) never count — they say nothing about provider health. - While open, the provider is skipped for `cooldown_seconds` (default `60`). Each consecutive trip doubles the window up to `max_cooldown_seconds` (default `600`). - After the cooldown, exactly one turn is admitted as a half-open probe. A clean turn closes the breaker; another failure re-opens it with the longer window. - If every provider in the chain is in cooldown, the primary is used anyway — a provider in cooldown still beats no provider at all. - A per-turn model override (an explicit `model`, or one picked by the router) applies to the primary link. While the primary's breaker is open the turn runs on the fallback's own configured model instead — the same semantics as an ordinary failover, but now for the whole cooldown window rather than only after a live failure. Tune or disable it in `agentos.toml`: ```toml [llm.circuit_breaker] enabled = true failure_threshold = 3 cooldown_seconds = 60 max_cooldown_seconds = 600 ``` Inspect the current state: ```sh agentos providers status # "circuit" column: closed | half_open | open (42s) agentos doctor # provider.circuit.open / provider.circuit.half_open curl localhost:8787/api/system/status # circuitBreaker / circuitBreakers ``` Breaker state lives in the running gateway only; restarting clears it. ### Rate limits that say when to come back A 429 (or an overload) whose response names a wait is backpressure, not an outage. AgentOS reads that wait from `Retry-After` (delta-seconds or an HTTP-date), `retry-after-ms`, or, when neither is sent, the reset header of whichever limit is spent (OpenAI's `x-ratelimit-reset-requests` / `x-ratelimit-reset-tokens`, Anthropic's `anthropic-ratelimit-*-reset`). Waits are clamped to 0–300 s. - When the wait is at most 30 s, the turn sleeps at least that long (plus up to 10 % jitter, capped at 1 s) and retries the **same** model, so the prompt cache and the price stay as they were. - A longer wait fails over straight away. With no model to fail over to, the turn fails instead of retrying into the same limit. - A rate limit with a short wait does not count toward the circuit breaker. One without a wait, or with a longer one, still does, and so does an overload / 5xx whatever it says. ### Retrying transient failures With a fallback model configured, a request that fails before the model produced anything (a timeout, a transport blip, an overload or a rate limit without a short wait, an unknown model) switches to the fallback at once, without a retry on the first model. The rules below apply to the model the turn ends up on, to failures after output started, and to every failure when there is no fallback. Rate limits without a wait, overloads (HTTP 529, `overloaded_error`) and transport blips (connection resets, 502/504/52x) are retried on the same model. Each failed attempt gets exactly one recovery decision, which is recorded in the turn's call log as a `turn_policy_decision` entry with the failure kind and the chosen action (`retry`, `failover`, `compact_then_retry` or `fail`). - Retries are bounded by a count (`--max-provider-retries` / `agent_max_provider_retries`, default `6`) **and** a wall-clock budget (`agent_retry_budget_seconds`, default `90`). The budget counts the waits and the failed attempts from the first failure, each failed attempt at most 10 s; `0` leaves only the count. The first retry is always made unless its wait alone is longer than the budget, so one slow failure (a long stream that drops) does not end the turn. - Waits grow exponentially from 1 s, each multiplied by a random factor between 0.5 and 1.5, so sessions that hit the same limit together do not retry in lockstep. - When either bound is reached, the turn fails over once to the next model, and fails if there is none. - No failover happens after the model already streamed visible text for that attempt, so another model's reply is never spliced onto it. - A timeout is retried once. If it times out again and the request is large (at least half of what preflight compaction lets a request grow to), the turn compacts older context and retries one more time; otherwise, or when compaction takes nothing off, it fails over to the next model, and fails if there is none (`agent_timeout_context_recovery`, default `true`). - An invalid API key (HTTP 401, from any provider) is not retried. The error says to check the provider's credentials. ```toml agent_max_provider_retries = 6 agent_retry_budget_seconds = 90 agent_timeout_context_recovery = true ``` The 30 s cap is `AgentConfig.rate_limit_retry_after_cap_seconds` for embedded callers; `0` turns the behaviour off. It has no `agentos.toml` key. ## Repetitive Output Guard A model occasionally gets stuck writing the same line, paragraph or short phrase over and over. Left alone it streams until `max_tokens`, which costs tokens and time and leaves a wall of repeated text. AgentOS watches the visible text and, separately, the reasoning of every response while it streams: - Nothing is checked until the text passes `first_check_chars` (default `16000`). After that a check runs each time the text has grown by as much again (16k, 32k, 64k, then every 64k), and each check reads only the last `tail_chars` (default `64000`), so the cost stays flat however long the reply gets. - A check trips when the tail repeats itself exactly — the same unit at least `min_repeats` times in a row (default `5`), found from a `window_chars`-long anchor (default `60`) — or when one line repeats that often with only small changes between its copies, and in either case the loop fills at least `min_coverage` of the tail (default `0.5`). - On a trip the engine stops reading and closes the provider stream, keeps the text up to the end of the first repeated copy, drops every tool call the cut response had started (none of them run), and logs `provider.repetition_detected`. The response is then continued once, like a response cut by the output limit, and the client gets a `repetition_detected` warning. A second loop in the same step ends the turn with the error code `repetition_detected`. - The saved reply has the repeated part removed; a client that rendered the stream live already showed it until the cut. Long legitimate output — a big table, generated code that repeats the same boilerplate, a numbered list of hundreds of items — differs from row to row, so it is never exactly periodic and does not trip. A response that really should repeat one block verbatim many times (a zero-filled matrix, a template printed 50 times) can trip; raise the thresholds or turn the guard off: ```toml [llm.repetition_guard] enabled = true first_check_chars = 16000 tail_chars = 64000 window_chars = 60 min_repeats = 5 min_coverage = 0.5 ``` ```sh agentos config set llm.repetition_guard.enabled false ``` A cut response never reaches the provider's usage event, so AgentOS counts an estimate for it instead: input from the request-size estimate, output from the length of the text and reasoning it streamed (about four characters per token). The estimate feeds the turn totals, the session usage and the `max_turn_input_tokens` / `max_turn_output_tokens` budgets; with no provider-billed figure the turn's cost is the pricing-table estimate. ## Provider Troubleshooting Start with: ```sh agentos doctor agentos providers status agentos diagnostics on ``` Check: - the API key environment variable is set in the gateway process environment; - the model id matches the provider; - the base URL is correct for compatible APIs; - proxy settings match your network; - router is disabled when debugging one exact provider/model; - the provider's circuit breaker is not open (`agentos providers status`); - the gateway was restarted after config changes. --- # Web Search > Source: https://useagentos.dev/docs/core/search AgentOS can search the web through configured search providers and can fetch pages through guarded web tools. Search is useful for current information, source-backed reports, market research, release notes, and troubleshooting. ## Inspect Search Providers ```sh agentos search list agentos search list --json agentos search status ``` Runtime-supported providers in this build include: - Brave Search - DuckDuckGo - Tavily Search The catalog may include metadata for providers that are not runtime-supported in the current build. Check JSON output when integrating. ## Configure Search No-key path: ```sh agentos configure search --search-provider duckduckgo ``` Equivalent search subcommand: ```sh agentos search configure duckduckgo ``` Brave Search: ```sh export BRAVE_SEARCH_API_KEY="..." agentos configure search --search-provider brave --api-key-env BRAVE_SEARCH_API_KEY ``` Tavily Search: ```sh export TAVILY_API_KEY="..." agentos configure search --search-provider tavily --api-key-env TAVILY_API_KEY ``` Provider-specific fields such as max results, proxy, environment-proxy usage, fallback policy, and diagnostics can be set through the search configuration surface. ## Test Search Run a diagnostic query through the running gateway: ```sh agentos search query "AgentOS release notes" agentos search query "AgentOS release notes" --limit 5 --json ``` Use this before blaming the agent for missing current information. If the diagnostic query fails, fix provider configuration first. ## Search in Agent Workflows Ask naturally: ```text Research the current state of browser automation libraries and cite sources. ``` For a narrower task: ```text Find the latest release notes for this project and summarize only breaking changes. ``` The agent can use search and fetch tools when the tool policy and configured provider allow it. For deeper multi-source work, ask for a research report or use an installed research skill. ## Safety and Source Quality Search results are external data, not instructions. Treat them as evidence for the task, not as authority over AgentOS behavior. Good research prompts ask for: - sources; - dates; - uncertainty; - conflicting evidence; - clear separation between source facts and model inference. Avoid asking the agent to follow arbitrary instructions found on web pages. ## Diagnostics ```sh agentos search status agentos diagnostics on agentos doctor ``` Check: - the selected provider is configured; - required API key environment variables are visible to the gateway process; - proxy settings match your network; - the gateway was restarted after config edits; - tool permissions allow web search/fetch for the current run. --- # X (Twitter) Search > Source: https://useagentos.dev/docs/core/x-search The `x_search` tool searches X posts, profiles, and threads. It is backed by xAI's server-side `x_search` tool on the Responses API at `https://api.x.ai/v1/responses`: Grok runs the search against X's index and returns a synthesized answer with citations to the posts it used. Reach for it instead of `web_search` when you want current discussion, reactions, or claims **on X**. General web pages still belong to `web_search` and `web_fetch`. ## What it is not - **Not a search provider.** `agentos search list` covers the providers behind `web_search`, which return ranked pages. `x_search` returns an answer plus citations, so it is a separate tool and cannot be selected as a `web_search` backend. - **Not a write path.** It cannot post, reply, like, DM, upload media, delete, or read your authenticated X account. AgentOS ships no authenticated X surface; an `x_search` answer is never evidence that anything was written. - **Not model-agnostic.** Only xAI has access to X's post index. Your agent can run on any provider — the tool makes its own call to xAI regardless. - **Not the X developer platform.** `developer.x.com` sells access to the X API (raw posts, writes) and bills separately. This tool talks to `x.ai`. ## Credentials Two paths. **OAuth wins when both are present**, because it spends a subscription you already pay for instead of API credit. | Path | How | `credential_source` | | --- | --- | --- | | SuperGrok / X Premium+ | `agentos auth login xai` | `xai-oauth` | | xAI API key | `XAI_API_KEY` in `~/.agentos/.env`, or `agentos configure x-search --api-key <key>` | `xai` | ### Signing in with a subscription ```sh agentos auth login xai # device-code flow: open a URL, enter a code agentos auth status # never prints a token agentos auth logout xai ``` For a caller that cannot hold a terminal open for minutes — a chat agent, a script — the same flow splits in two: ```sh agentos auth login xai --no-wait --json 2>/dev/null # -> loginId, verificationUri, userCode agentos auth login xai --resume --json 2>/dev/null # exit 0 done, 3 not yet, 1 failed ``` `--resume` picks the newest pending login unless given `--login-id`. Pending logins live in the token store, so the half that starts one and the half that finishes it can be different processes. The login is a device-code grant against `auth.x.ai`. Tokens land in `~/.agentos/auth.json` (owner-only, `0600`) and refresh themselves; you are not asked to paste anything into a prompt. Two things worth knowing: - **A subscription is not automatically entitled to API access.** xAI restricts API/OAuth use to certain SuperGrok tiers, and an account outside them gets HTTP 403 on refresh even though the in-app subscription is active. AgentOS reports that as a tier problem rather than telling you to log in again, because logging in again cannot fix it. - **A broken login is reported, not skipped.** If OAuth is configured but unusable, `x_search` says so instead of quietly falling back to an API key you may not have set. ### Client identity The device-code flow uses xAI's public Grok CLI client id — the OAuth scope literally reads `grok-cli:access` — because xAI publishes no self-service client registration. It is a public client with no secret. Override it with `AGENTOS_XAI_OAUTH_CLIENT_ID` if you have your own registration. ### Browser sign-in Settings › Search can run the same flow: **X search → Sign in with xAI**. It shows the approval link and the code, then polls until you approve. Once signed in the same control becomes **Sign out of xAI**. The card reports which credential is currently in play, so a key configured alongside a login does not look like the one being used. Signing out only forgets the local tokens; nothing is revoked at xAI, and `x_search` falls back to `XAI_API_KEY` if one is set. Without a reachable credential the tool is removed from the model's schema entirely. That is deliberate: every tool schema is fixed overhead on every provider call, so an install with no xAI key should not pay for this one. It also means "the agent says it has no x_search tool" is the expected behaviour before setup, not a bug. `agentos context` still lists and prices `x_search`. That command reports what each *profile* would cost across the whole registry and does not model credential gating — `image_generate` appears there the same way without an image provider. The live per-turn surface is the one that drops it. ## Cost `x_search` bills your xAI account directly. It does not pass through the AgentOS provider layer, so the spend does **not** appear in `agentos cost` or the Usage view. Watch it in the xAI console. ## Configure ```sh agentos onboard catalog x-search agentos configure x-search --api-key-env XAI_API_KEY agentos configure x-search --x-search-model grok-4.5 --x-search-reasoning-effort low agentos configure x-search --no-x-search-enabled ``` Settings › Search carries the same fields under X search, with an **Enable X search** switch and an **API key environment variable** field. Saving applies immediately; no gateway restart. ```toml [x_search] enabled = true # Any Grok model with access to xAI's server-side x_search tool. model = "grok-4.5" base_url = "https://api.x.ai/v1" api_key = "" api_key_env = "XAI_API_KEY" # "", low, medium, high, or xhigh. Empty uses the model's own default; # xhigh is only accepted by models that document it. reasoning_effort = "" # One attempt. A complex X search runs 60-120s. timeout_seconds = 180.0 # Hard wall for the whole call including retries. total_timeout_seconds = 300.0 # Retried on 5xx, timeout, and connection errors only. retries = 2 ``` `base_url` exists for an HTTPS proxy that speaks xAI's Responses API. A non-HTTPS URL, or one pointing at a cloud metadata endpoint, is rejected and the default is used — the request carries a bearer token. ## Tool parameters | Parameter | Type | Description | | --- | --- | --- | | `query` | string (required) | What to look up on X. | | `allowed_x_handles` | string[] | Include these handles exclusively (max 10). A leading `@` is stripped. | | `excluded_x_handles` | string[] | Exclude these handles (max 10). Cannot be combined with `allowed_x_handles`. | | `from_date` | string | `YYYY-MM-DD` start date. | | `to_date` | string | `YYYY-MM-DD` end date. | | `enable_image_understanding` | boolean | Ask xAI to analyze images attached to matching posts. | | `enable_video_understanding` | boolean | Ask xAI to analyze videos attached to matching posts. | Dates are checked before the HTTP call. A malformed value, an inverted range, or a `from_date` in the future fails immediately rather than spending a billable call that could only return nothing. A future `to_date` is allowed — "from yesterday to tomorrow" is a legitimate way to catch posts as they arrive. ## Result ```json { "success": true, "provider": "xai", "credential_source": "xai", "tool": "x_search", "model": "grok-4.5", "query": "reactions to the new Grok image features", "answer": "...", "citations": ["https://x.com/..."], "inline_citations": [{ "url": "...", "title": "...", "start_index": 0, "end_index": 42 }], "degraded": false, "degraded_reason": null } ``` ### `degraded` is the field that matters xAI answers with HTTP 200 and a fluent, confident answer even when its X index matched nothing for your filters. That answer comes from the model's training data and is indistinguishable from a real one by shape alone. `degraded` is `true` when a narrowing filter (`allowed_x_handles`, `excluded_x_handles`, `from_date`, `to_date`) was active **and** both citation channels came back empty. Treat that answer as unsourced: it is not something found on X. A broad query with no citations is not degraded — it is just an answer. Common causes: - A typo in a handle, or an account that does not exist. - A date range too narrow, or sliding past the posts you wanted. - An index gap. Some active accounts intermittently fail to surface even when they post regularly; retry after a few minutes. ## Policy and limits - Member of `group:web`, so `deny = ["group:web"]` cuts the route to api.x.ai along with the other network tools. - On the cron allowlist, next to `web_fetch` and `web_search` — a scheduled job watching X is the obvious use, and the tool can only read. - Classified `external` for result budgeting, so a long answer is trimmed under the same per-turn ceiling as other network results. - Runs under the `web.fetch` sandbox action kind. ## Troubleshooting **The agent says it has no `x_search` tool.** No credential resolved. Check `agentos auth status`, `agentos env list` for `XAI_API_KEY`, or that `[x_search] api_key` is set, and that `enabled` is not `false`. **`xai_oauth_tier_denied`.** The OAuth grant is valid but xAI will not let the account use the API. Logging in again will not help — upgrade the subscription, or set `XAI_API_KEY` and use the key path. **The tool is offered but every call fails after a long break.** The stored refresh token was revoked or already used. AgentOS clears dead tokens when the refresh returns 400/401 so the next call fails locally instead of over the wire; run `agentos auth login xai` again. **`x_search is not enabled for this model`.** The configured `model` lacks access to xAI's server-side tool. Switch back to `grok-4.5` or another Grok model that documents it. **Timeouts.** `timeout_seconds` bounds one attempt; `total_timeout_seconds` bounds the whole call. Retries stop when the remaining budget cannot fit another attempt, so raising `retries` alone does nothing unless the total goes up too. ## See also - [Web Search](https://useagentos.dev/docs/core/search) — general web search providers. - [Tools, Approvals, and Sandbox](https://useagentos.dev/docs/core/tools-and-sandbox) — the built-in tool catalog. - [Configuration](https://useagentos.dev/docs/core/configuration) — every config key. --- # Artifacts and Media > Source: https://useagentos.dev/docs/core/artifacts-and-media AgentOS can create and deliver files as part of agent work: reports, HTML files, PDFs, slide decks, spreadsheets, generated images, and other artifacts. Use artifacts when the output is too large, visual, structured, or important to leave only in chat text. ## Artifacts Artifacts are user-visible files created during a session. In Web UI chat they appear as artifact cards when the runtime publishes them. In CLI runs, artifact events can include file names, ids, and download URLs. Common use cases: - generate a report; - create a standalone HTML prototype; - build a CSV/XLSX workbook; - create a PDF briefing; - produce a slide deck; - package generated output for channel delivery. Ask directly: ```text Create a one-page HTML dashboard from this data and publish it as an artifact. ``` ```text Generate a PDF briefing with sources and publish the final file. ``` ### Download URLs Clients fetch an artifact or an attached file through a ticketed URL: the `artifacts.download` RPC returns `/api/v1/artifacts/download/<conn_id>/<ticket>`, good for five minutes and for as long as the WebSocket connection that asked for it stays open. The URL needs no header, serves byte ranges and a PNG thumbnail (`?variant=thumbnail`, still images up to 1200 px), and is served with a sandboxing `Content-Security-Policy` and `Content-Disposition: attachment`, so a generated HTML file never runs as a page of the gateway. The older `/api/v1/artifacts/{id}?sessionKey=` and `/api/v1/attachments/{sha256}?sessionKey=` URLs still work for this release (`[artifacts] legacy_session_key_urls`); see [HTTP API → Ticketed downloads](https://useagentos.dev/docs/core/http-api#ticketed-downloads). ## When to Use Artifacts Instead of Chat Use artifacts for: - files the user should download or share; - tables or reports that need layout; - generated apps, dashboards, or prototypes; - long output that would be awkward in chat; - channel delivery where the platform supports file upload. Use chat text for short answers, decisions, and next steps. ## Inline Charts and Cards Most artifacts render in Web UI chat as a download chip; images and audio render inline. Two more mimes render inline: | Mime | Rendered as | |------|-------------| | `application/vnd.agentos.chart+json` | Candlestick chart with a volume histogram | | `application/vnd.agentos.cards+json` | Responsive grid of record cards | There is nothing to register: any skill gets one by publishing a file with that mime. Two steps, and both have a failure mode worth knowing. **`exec_command` publishes these two mimes for you.** When a command's stdout contains a line that is exactly ``` publish_artifact path=<file> mime=application/vnd.agentos.<something>+json nonce=<nonce> ``` where `<nonce>` is the value `exec_command` put in that command's `AGENTOS_INLINE_ARTIFACT_NONCE` environment variable, the artifact is published automatically and the marker is replaced with a note telling the model not to publish it again. Print it with `agentos.skill_stdio.inline_artifact_marker(path, mime)`, which adds the nonce. The nonce is fresh for every command, so a marker-shaped line inside data the command merely prints — a token symbol read off a chain, an API response — cannot trigger a publish; a marker without this command's nonce stays plain text. Before this, any matching line published, which let an attacker-chosen ERC-20 symbol push a workspace file at the user as a rendered card. Auto-publishing is deliberate: leaving the call to the model meant the file got written and the UI never drew, because the model would answer with a hand-written table instead. Only the `application/vnd.agentos.` family auto-publishes — a plain file still needs an explicit `publish_artifact` call, so ordinary command output cannot push a workspace file at the user. Path containment is enforced by `publish_artifact` itself, unchanged. Write the marker on its own line: prose that merely mentions it is ignored. **1. Write the JSON inside the workspace.** Scripts run with the workspace as their working directory, so a bare filename lands in the right place. `publish_artifact` rejects anything outside the workspace, so an absolute path like `/tmp/chart.json` fails *after* the data has already been fetched. **2. Publish it with the mime spelled out.** ``` publish_artifact path=bonk-1h.chart.json mime=application/vnd.agentos.chart+json ``` Passing `mime` is what makes the chart appear. Omit it and the filename guess returns `application/json`, which classifies as a data artifact and renders as an ordinary download chip — no error, just no chart. Tell the model to pass it explicitly in your SKILL.md. The body is: ```json { "type": "candlestick", "title": "BONK · 1h", "subtitle": "SOL · 1h", "candles": [ { "time": 1754380800, "open": 1.2e-6, "high": 1.5e-6, "low": 1.1e-6, "close": 1.4e-6, "volume": 12500.5 } ] } ``` `time` is a Unix timestamp in **seconds** and `volume` is optional; every other candle field is required. Rows may arrive in any order and may repeat a timestamp — the renderer sorts them and keeps the last entry per timestamp. `title` and `subtitle` are display-only text, never markup. ### Card grids Use cards when the answer is a handful of small records rather than a series — a token lookup, a holder list, a search result. They stay readable where a markdown table would not: a 42-character contract address puts a table into a horizontal scroll, while a card gives it its own line and a copy button. ```json { "type": "cards", "title": "Robinhood Chain — Apple", "subtitle": "optional caveat carried under the heading", "cards": [ { "title": "AAPL", "subtitle": "Apple", "logo": "https://assets.example/aapl.png", "badge": "verified", "badgeTone": "positive", "fields": [ { "label": "Address", "value": "0xaf3d…93f9", "copyable": true }, { "label": "Chain", "value": "4663" } ] } ] } ``` Only `cards` and each card's `title` are required. `badgeTone` is one of `positive` / `warning` / `danger` / `neutral`, and anything else falls back to `neutral`, so a skill can ship a new status without waiting on a frontend release. `copyable` renders the value in monospace with a copy button. `logo` must be an `http(s)` URL — other schemes are dropped rather than sanitised. At most 24 cards render; the rest are counted and reported under the grid instead of being dropped silently. Every string is display-only text, never markup — see `frontend/src/views/chat/transcript/cards.ts`. `robinhood-rwa-addresses` is the worked example: `scripts/rwa_cards.py` reads the lookup's JSON on stdin and writes this payload. Hovering a candle reveals its open, high, low, close, volume, and the move from open to close as a percentage, so there is no need to repeat those numbers in the reply. The `gmgn-market` and `gmgn-token` skills each ship `scripts/kline_chart.py`, which converts GMGN kline output into this shape; use it as a worked example when adding charts to another skill. Note that they carry a copy each rather than sharing one: `{baseDir}` resolves to the skill that is running, so a skill cannot reach into another skill's `scripts/` directory — and the skill it pointed at may not even be enabled. Give your skill its own copy. Charts render in the Web UI only. Other surfaces receive the artifact as a normal JSON file, so keep a short text summary in the reply alongside the chart. ## Document Skills AgentOS includes skills for common document formats: - `docx` for Word documents; - `pptx` for PowerPoint decks; - `xlsx` for Excel workbooks; - `pdf-toolkit` for structured PDF work; - `html-to-pdf` for styled PDF rendering. Discover them: ```sh agentos skills search pdf agentos skills view pptx agentos skills view xlsx ``` Some document features require optional native/system dependencies. Use `agentos skills list` and `agentos doctor` to check readiness. ## Image Input and Generation In terminal chat, send an image for analysis: ```text /image /path/to/screenshot.png Describe what is wrong with this UI. ``` Configure image generation: ```sh agentos configure image-generation ``` Then ask for images in chat: ```text Generate a clean product mockup image for this landing page. ``` Image provider support depends on configured provider credentials, optional dependencies, and runtime policy. ## Text to Speech and Media Helpers The media tool family includes image, PDF, and TTS helpers. Availability can depend on provider config, optional dependencies, and runtime policy. Use media helpers when the requested output is naturally a file or asset rather than a plain text answer. ## Channel Delivery Channels differ in file-size limits, threading behavior, and upload APIs. If a channel cannot deliver an artifact directly, use the Web UI artifact card or session export as the recovery surface. For channel setup, see [Channels](https://useagentos.dev/docs/core/channels). ## Troubleshooting If an artifact does not appear: 1. Check the chat or CLI output for artifact events. 2. Open the Web UI session and inspect artifact cards. 3. Export the session if you need durable evidence: ```sh agentos sessions export <session-key> ``` 4. Run `agentos doctor` if a document or media dependency appears missing. --- # Tools, Approvals, and Sandbox > Source: https://useagentos.dev/docs/core/tools-and-sandbox AgentOS tools give the agent useful capabilities. Policy layers, approval surfaces, workspace constraints, and sandbox posture control how those tools are allowed to act. Use this page before running unattended automation, file edits, shell commands, or channel-connected agents. For a focused permissions guide, see [Approvals and Permissions](https://useagentos.dev/docs/core/approvals-and-permissions). ## Built-In Tool Areas | Area | Examples | | --- | --- | | Filesystem | `read_file`, `write_file`, `edit_file`, `list_dir`, `glob_search`, `grep_search`, spreadsheet reads. | | Shell and code | `exec_command`, `background_process`, `process`, `execute_code`. | | Git | `git_status`, `git_diff`, `git_log`, `git_commit`, `apply_patch`. | | Web | `web_search`, `web_fetch`, `http_request`, `x_search` (X/Twitter via xAI — see [X (Twitter) Search](https://useagentos.dev/docs/core/x-search); hidden without an xAI key). | | Browser | `browser` — drive a real Chromium (navigate, snapshot, click, type, fill, wait, eval, dialog, screenshot) via the `agent-browser` engine. Hidden until the binary is installed. **Runs outside the sandbox** (Chromium can't run inside bubblewrap/seatbelt). See [Browser automation](https://useagentos.dev/docs/core/features/browser). | | Memory | `memory_search`, `memory_save`, `memory_get`, `memory_delete`, `memory`. | | Sessions | `sessions_send`, `sessions_spawn`, `sessions_list`, `sessions_history`, `session_status`, `session_rename`, `session_pin`. `sessions_spawn` with `runtime="acp"` delegates to an external coding harness (Claude Code, Codex, ...); see [ACP Coding Harnesses](https://useagentos.dev/docs/core/acp-agents). | | ACP harnesses | `acp` — operator tool (not exposed by default) for harness sessions: `agents`, `sessions`, `status`, `cancel`, `close`, `set_mode`, `set_model`, `doctor`. Harnesses run as the gateway user, **outside the AgentOS sandbox**, with their own tools; their permission prompts follow `[acp] permission_mode`. | | Artifacts | `publish_artifact`. The mime decides the rendering: some draw inline in chat rather than as a download chip — see [Artifacts and Media](https://useagentos.dev/docs/core/artifacts-and-media#inline-charts). | | Media | image generation, PDF, TTS, and media helpers. | | Skills | `skill_list`, `skill_view`, `skill_create`, `skill_edit`, `install_skill_deps`. | | Control | cron scheduling and gateway control operations. | | Channels/platforms | messaging, chat, and media helpers across supported channel adapters. | | User interaction | `ask_user` — structured questions with 2-4 options each. Presenting the question ends the turn; the answer arrives as the next user message. The Web UI renders a clickable card; the CLI and channels render a numbered list you answer by typing. Hidden on surfaces with nobody to reply (cron, subagents, heartbeats); channel DMs count as having a responder. | | Plan mode | `/plan` flips the session into research-only planning: the turn's tool surface narrows to a read/search/analysis allowlist and the agent presents its finished plan via `exit_plan_mode` (which ends the turn, like `ask_user`). Approval is out of band — the Web UI plan card's Approve button or `/plan off` — so the model cannot talk itself out of plan mode. State is per-session gateway memory; a gateway restart clears it. | ## Permission Modes Use stricter modes when running unattended: ```sh agentos agent --permissions restricted -m "Inspect this repo" ``` Use broader modes only when you trust the task and workspace: ```sh agentos agent --permissions full --workspace /path/to/project -m "Run tests and fix failures" ``` For interactive work, the Web UI approvals surface can pause sensitive tool calls for review. For automation, choose a permission mode and workspace policy before the run starts. Read: [Approvals and Permissions](https://useagentos.dev/docs/core/approvals-and-permissions) ## Approval Flow Sensitive actions may pause for human approval depending on permission mode, tool policy, channel surface, and runtime configuration. Approvals are most important for: - filesystem writes; - shell commands; - external channel or webhook delivery; - generated artifacts that will be published; - actions that affect another service. Use the Web UI's Inbox or Settings › Approvals when you want durable review outside the chat scrollback. ## How a Tool Call Is Admitted Before a model's tool call reaches hooks, policy or an approval prompt, it is checked once: - **Name.** An exact name always wins. On a miss, a name the model decorated is resolved to the one tool it clearly means: a `functions.` or `tools.` prefix and a trailing `:<n>` counter are dropped, case is ignored, and `/` reads as `_` (`functions.Read_File:0` and `web/search` run `read_file` and `web_search`). Only tools visible to the session are candidates, and the match must be unique; two tools that differ only by case, or no match at all, still answer `ToolNotFound`. MCP tool names (`mcp_…`) are never matched loosely, only exactly (a namespace prefix or counter around the exact name is still dropped). The name is resolved against the tools offered to the model as soon as the call arrives, so scheduling, timeouts, approvals, stream events and the saved transcript all use the real tool name. - **Arguments.** They are validated against the tool's schema (`type`, `properties`, `required`, `items`, `enum`, `additionalProperties`, `anyOf`/`oneOf`). Lossless mistakes are repaired: `"5"` for an integer or number, `5.0` for an integer, `"true"`/`"false"` for a boolean, and a JSON-encoded string where an array or object is expected. The repaired value is what the transcript keeps and what the model sees on its next request. Nothing is turned into `null`, and arguments the schema does not mention are passed through unchanged. Anything else is rejected without running the tool: the result is an error with `error_class: "ToolArgumentsRejected"` (status reason `invalid_arguments`) that names every failing argument path and the type it expected, marked `retry_allowed: true` because a corrected call should run. A rejected call counts as a failed call, so repeating it unchanged trips the same failure-loop guard as any other failure. A tool whose schema cannot be read is not validated. ## Calling a Tool Directly `POST /api/v1/tools/invoke` runs one tool without a model turn, for scripts, CI and the desktop: `{"tool": "web_search", "args": {...}}`. It applies the same policy an agent's tool call gets — the `[tools]` profile, allow and deny lists, the agent's own entry, the runtime capability surface and the dispatch policy chain — in an unattended, sandboxed context, so a tool that needs an approval refuses (`403` with `details.code = "APPROVAL_REQUIRED"` and the `details.approval_id` when one was queued). The call also goes through the tool hooks configured for agent turns (see [Tool and request hooks](#tool-and-request-hooks-python-api)), once per request. The policy first judges the arguments as you sent them; a call it refuses never reaches a hook. A hook's block is then a `403` like a policy refusal, and a rewrite or a result replacement applies. `dry_run: true` returns the resolved policy without running the tool; the hooks' `before_tool` runs in it too, so a hook's block shows as `allowed: false`. It denies by default: only tools whose registration declares them read-only run. A name floor holds on top, whatever the configuration says: shell, terminal and code execution, file and memory writes (including the `memory` tool, `http_request` downloads, document creation, `publish_artifact`, `env_set`), project and session renames, `sessions_spawn`, `sessions_send`, `subagents`, `acp`, `message`, `cron` and scheduler tools, `gateway`, `browser`, `router_control`, paid media generation and trading tools. Those answer `404`, exactly like a tool that does not exist, and arguments that write a file (`output_path` and the like) are refused for every tool. Lift one tool at a time in `agentos.toml` (config RPC writes cannot add an entry): ```toml [tools.invoke] allow = ["create_pdf_report"] # tool names, never patterns ``` Full status table: [HTTP API → Direct tool calls](https://useagentos.dev/docs/core/http-api#direct-tool-calls). ## Delegated Work and Caller Authority A turn can start work that runs later on another session: `sessions_spawn` children, turns queued with `sessions_send`, and `agent_turn` jobs scheduled with the in-agent `cron` tool. That work never runs with more authority than the turn that started it: - **Subagents and `sessions_send` turns** carry the caller's tool surface as a ceiling. The target agent's own tool policy can narrow it further but cannot widen it, and elevation is capped at the caller's — including a target session's `/elevated` mode. Your own Web or CLI session is unrestricted, so work it starts behaves as before. - **Cross-agent delegation** follows `subagents.allow_agents` when it is set. When it is not, a caller whose tools were narrowed by policy (an agent or channel `tools` policy, a cron allowlist) may not spawn or message another agent. Your own Web or CLI session may still message any session. - **ACP harnesses** run their own shell and file tools, so a caller whose policy withholds `exec_command` or `write_file` can neither start nor drive one. - **Cron jobs** created or edited from a chat channel, or by any other non-operator turn, are stored with `tool_policy.elevated = "off"` plus a `deny` list of every tool their creator could not use, so `permissions.cron_default_mode` never elevates them. Such a turn may pass a `tool_policy` that only denies tools, and may not rewrite the task of an `agent_turn` job that relies on the default elevation. Cron turns never get `sessions_spawn` or `sessions_send`, whatever the tool profile. Group and channel chats, cron turns and subagents may not read private memory (`memory_search`, `memory_get`, `session_search`). They also may not write it (`memory`, `memory_save`, `memory_delete`), and the periodic memory review skips them. `sessions_history`, `sessions_list` and `sessions_send` reach only the calling session and the sessions it spawned. Your main and direct-message sessions keep all of these tools. ## Workspace Controls Read-side restriction: ```sh agentos agent --workspace /path/to/project --workspace-strict -m "Summarize this repo" ``` `--workspace-strict` covers every tool that reads a local file by path: `read_file`, `read_spreadsheet`, `list_dir`, `glob_search`, `grep_search`, and the media tools (`pdf`, `image`, and the audio tools that take a file). Write containment: ```sh agentos agent \ --workspace /path/to/project \ --workspace-lockdown \ --scratch-dir /path/to/project/.scratch \ -m "Investigate and prepare a minimal patch" ``` `--workspace-lockdown` is intended for automation where writes must stay inside the workspace or scratch directory. For shell commands, lockdown inspects the command text for write targets — redirections (`>`, `>>`, `2>`, `&>`, `>&`, `>|`, with or without surrounding whitespace) and `tee` (including pipe-adjacent `|tee` and long options such as `tee --append`). The scan reads text, not shell syntax, so it deliberately fails closed: a command that merely *mentions* a path after `>` inside quotes — say `grep '>/dev/null' script.sh` — is refused under lockdown even though it writes nothing. That is defense in depth, not a security boundary: a command can still reach outside the workspace through an interpreter (`python -c`), a copy (`cp`, `dd of=`), an in-place edit (`sed -i`), or a path built from a shell variable. Use the OS sandbox (`agentos sandbox on`) when you need containment that does not depend on reading the command line. ## Sandbox Commands ```sh agentos sandbox status agentos sandbox on agentos sandbox full agentos sandbox bypass agentos sandbox reset ``` Sandbox behavior is platform-dependent. Treat `sandbox status` and `doctor` as the source of truth for the current machine. With the sandbox on, the configured workspace is what gets mounted writable (at `/workspace` under bubblewrap, as the write-allowed subpath under seatbelt). A tool's `workdir` (`exec_command`, `background_process`, the git tools) only picks where the command starts inside it: a `workdir` outside the workspace and the configured extra mounts is refused with a `policy_denied` result rather than mounted. Add a directory to the extra mounts (`AGENTOS_SANDBOX_EXTRA_RW_MOUNTS` / `AGENTOS_SANDBOX_EXTRA_RO_MOUNTS`) if commands legitimately need to run there. ## Recommended Patterns | Task | Recommended posture | | --- | --- | | Read-only repo summary | `--workspace` plus `--workspace-strict` | | Local patch with tests | `--workspace`, `--workspace-lockdown`, and a scratch dir | | Chat with possible writes | Web UI with approvals visible | | Channel-connected agent | Conservative permissions and explicit channel config | | Provider/debug investigation | Diagnostics on, minimal tool permissions | ## Web Safety AgentOS web tools use provider configuration and guardrails. Use provider diagnostics when web search behaves unexpectedly: ```sh agentos search status agentos search query "test query" agentos diagnostics on ``` Search results and fetched pages are external data. They should inform the answer, not override tool policy or user instructions. `http_request` refuses cloud metadata endpoints (`169.254.169.254`, `metadata.google.internal`) on every configuration; ordinary private addresses stay reachable, so pointing it at a local dev server still works. The one exception is the AgentOS gateway's own listener (its port on loopback, `0.0.0.0` or this host's addresses): the agent never gets to call the Control API from inside a turn. `web_fetch` is stricter and blocks private addresses outright. ## Credentials Authenticated API calls work normally: an API key in an `Authorization` or `x-api-key` header is not refused. What outbound tools refuse is credential *material* with no legitimate destination — a PEM private key, a vendor-prefixed provider key (`sk-ant-…`, `ghp_…`, `AKIA…`), a connection string with an inline password, an `/etc/passwd` line. Prefer referencing a credential over pasting it. In a shell command use `$NAME`; for sandboxed code, have the skill declare it: ```yaml metadata: agentos: requires: env: [CAP_API_KEY] ``` The value is then read at spawn time and never enters the transcript. Command output is masked before the model sees it, and the gateway token never reaches a child process. A secret the gateway holds is also masked **by value**: a skill hot-wallet key or the vault password is replaced wherever it appears in tool output — ``printenv NAME``, ``echo $NAME``, a file read — not only in ``NAME=value`` form. Keystore ``ciphertext``/``mac`` and BIP-39 mnemonics are masked by shape; a wallet address or a transaction hash (also 64 hex) is left readable. Read: [Configuration](https://useagentos.dev/docs/core/configuration#credentials-and-child-processes) ## Tool Compression Large tool results may be compacted before they are shown to the model. This is normal and protects the active context window. See [Tool Compression](https://useagentos.dev/docs/core/features/tool-compression). ## Artifacts and Media Tool calls can publish artifacts and generate media. See [Artifacts and Media](https://useagentos.dev/docs/core/artifacts-and-media) for user-facing artifact, document, image, PDF, and TTS workflows. ## Troubleshooting If a tool does not run: 1. Check permission posture: ```sh agentos sandbox status agentos doctor ``` 2. Check whether the gateway or channel surface requires approval. 3. Confirm the workspace path is correct. 4. Use diagnostics for repeated failures: ```sh agentos diagnostics on ``` ## Tool and request hooks (Python API) Code that embeds AgentOS can hook tool dispatch and provider requests by passing `tool_hooks=[...]` and `request_hooks=[...]` to `TurnRunner`. Hooks are plain objects with a `name`, from `agentos.engine.hooks`: ```python from agentos.engine.hooks import Amend, Block, ReplaceResult, Rewrite, Veto class WorkspaceGuard: name = "workspace-guard" fail_closed = True # a crash in this hook blocks the call instead of allowing it def before_tool(self, call): path = call.tool_call.arguments.get("path", "") if path.startswith("/etc"): return Block("writes outside the workspace are not allowed") if path.startswith("~/"): return Rewrite({**call.tool_call.arguments, "path": path[2:]}) return None # run as is def after_tool(self, call, outcome): text = str(getattr(outcome.result, "content", "") or "") if "sk-" in text: return ReplaceResult(text.replace("sk-", "sk-[redacted]-")) return None class SpendGate: name = "spend-gate" def before_request(self, call): if over_budget(call.session_key): return Veto("The daily spend limit is reached.") return Amend("The user is on a phone; keep answers short.") ``` - **`before_tool`** returns `None`/`Allow`, `Block(reason)` or `Rewrite(arguments)`. - Hooks run in order, and the first block wins. - A blocked call is not run. The model sees an error result with the reason (`error_class: ToolHookBlocked`). - Rewritten arguments are checked against the tool's schema again, and the tool policy and approvals still apply to them. A hook cannot use a rewrite to bypass either. On an approval retry the granted `approval_id` is kept even if the rewrite leaves it out. - Each hook gets its own copy of the arguments: editing `call.tool_call.arguments` in place changes nothing. Return `Rewrite` to change them. - When a rewrite was applied, the result carries the arguments the call ran with in `ToolResult.effective_arguments`. - The transcript keeps the call as the model made it. The tool result tells the model that a hook adjusted it and which arguments, by name only: a trailing note on a text result, a `tool_hook_adjusted_arguments` list on a JSON object result. The note never repeats the new values, and the model's record of the call keeps its own arguments. - Operators see the call that actually runs: an approval prompt for a rewritten call (and the pending-approval result on its tool card) shows the rewritten command, because that is what is being approved. The tool card's argument list stays the model's. - The result itself is the output of the call as it ran, so a tool that echoes its arguments (a written path, the command in an approval denial) echoes the rewritten value to the model too. A hook that puts something into the arguments the model must not see redacts it in `after_tool` with `ReplaceResult`. - Checks that describe the work done (the reminder to verify code changes) use the rewritten arguments. Guards that decide before the call runs use the model's arguments: the repeated-failure and loop guards, the per-call timeout taken from an argument (a hook cannot extend it), and the concurrency key of a keyed tool. - **`after_tool`** runs after the result is settled. `outcome.result` is the `ToolResult` the model and the transcript will see: `content` is a string, and `is_error` and `execution_status` are set. `outcome.raw_result` is what the tool itself returned, and `outcome.exception` is set when it raised. - Every hook whose `before_tool` ran gets `after_tool` once, also when the call was blocked, its rewrite refused, denied by policy or skipped by the run budget; `outcome.result` is then that error result. - It may return `ReplaceResult(content, is_error=None)`. The replacement is what the model sees and what the transcript stores, on every one of those paths. Hooks after it see the replaced result. It is held to the same size cap as a tool's own result, and when it flips `is_error` the execution status is reset to match. - **`before_request`** may return `Amend(context)` or `Veto(reason)`. - An amendment is added after the cached prompt prefix, for that request only, and is not persisted. - A veto ends the turn with error code `request_vetoed` and outcome `blocked`. - **Errors in a hook** are logged and treated as "no decision". With `fail_closed = True`, a failing `before_tool` blocks the call, a failing `after_tool` withholds the result (the model gets an error, `error_class: ToolHookFailed`; the tool itself may already have run), and a failing `before_request` vetoes the request. - **Older hooks** whose methods return nothing keep working unchanged. - The same tool hooks also guard `POST /api/v1/tools/invoke` ([Calling a Tool Directly](#calling-a-tool-directly)). --- # Approvals and Permissions > Source: https://useagentos.dev/docs/core/approvals-and-permissions Approvals and permissions control how AgentOS tools are allowed to act. They matter most when an agent can write files, run shell commands, publish artifacts, post into channels, or call external services. Use this page before running unattended automation or giving a channel-connected agent broad tool access. ## Permission Profiles Single-shot automation accepts an explicit permission profile: ```sh agentos agent --permissions restricted -m "Inspect this repo" agentos agent --permissions on -m "Run with host execution and approvals" agentos agent --permissions bypass -m "Trusted local automation" agentos agent --permissions full -m "Fully trusted local automation" ``` Practical meaning: | Profile | Use when | | --- | --- | | `restricted` / `off` | The task should stay conservative and avoid elevated execution. | | `on` | Host execution is allowed, but approval checks still matter. | | `bypass` | You trust the task enough to auto-grant approvals while keeping sensitive-path checks. | | `full` | You fully trust the task and environment. Use sparingly. | For automation, prefer the narrowest profile that can complete the task. These profiles apply to interactive CLI and Web turns. For cron turns (unattended automation), the default elevated execution posture is controlled by `permissions.cron_default_mode` (which defaults to `bypass`). By default, cron jobs of kind `agent_turn` run elevated (under `bypass`), whereas other job kinds (like reminders and script runs) are never elevated. You can explicitly override this default for any individual job by passing `--no-elevated` (to opt out of elevation) or `--elevated-mode {bypass,full}` (to pick a specific mode) during job creation or update. See [CLI Reference](https://useagentos.dev/docs/core/cli#letting-a-cron-job-run-shell-based-skills) for details and security implications. ## Workspace Containment Set a workspace for file and shell work: ```sh agentos agent \ --workspace /path/to/project \ --workspace-strict \ -m "Summarize this repo" ``` Contain writes to the workspace or scratch directory: ```sh agentos agent \ --workspace /path/to/project \ --workspace-lockdown \ --scratch-dir /path/to/project/.scratch \ -m "Investigate and prepare a minimal patch" ``` Use `--workspace-lockdown` for unattended runs where accidental writes outside the project would be unacceptable. ## Interactive Approvals Interactive chat surfaces can pause sensitive tool calls for a human decision. The terminal chat supports: ```text /approvals /approvals reset /permissions status /permissions on /permissions off /permissions bypass /permissions full /forget ``` Use these commands when you need to inspect or reset cached approval decisions during a chat. ### Only you answer a prompt Answering a prompt, changing how prompts are answered, forgetting remembered answers, raising a session's permission mode and pairing a new channel sender are refused to a connection the gateway recognizes as an agent's (`approvals.operator_required`, HTTP `403`): one that carries an agent token, comes from a process the gateway spawned (Linux), or opened while an agent's shell, background process or `execute_code` run was going. That covers `exec.approval.resolve`, `plugin.approval.resolve`, `exec.approvals.set`, `exec.approvals.node.set`, `exec.approval.forget`, `channels.pairing.approve`, `POST /api/approvals/resolve`, `POST /api/approvals/settings` and `POST /api/elevated-mode`; an `elevated` hint on `chat.send` / `sessions.send` from such a connection is ignored. The desktop app (it holds the operator secret) is never refused. A web console that connected while an agent's shell was running is: reload it once the shell has finished, or answer in the app. The approval queue's database is not a way around this: a decision counts only if the gateway process that asked made it, through one of the surfaces above, on the same parameters. A row approved by writing the database directly is read as a denial. ### Skill Signing Prompts The bundled skills that sign with a hot-wallet key of their own — `senior-unilp-manager` (`UNIV4_LP_PRIVATE_KEY`), `poolsdotfun-token-launcher` (`POOLSFUN_PRIVATE_KEY`) and the GMGN skills (`GMGN_PRIVATE_KEY`) — never get that key in a process the agent drives: not its shell, `execute_code`, a cron script, an MCP server, a coding harness or a lifecycle hook, and an agent's connection cannot `env.reveal` it. AgentOS hands it out only for a *direct* command running that skill's own entry point (one command; no pipe, redirect, substitution or `VAR=` prefix), and runs its own packaged copy of the script — or the pinned `gmgn-cli@1.7.1` — without a shell. When that command moves funds — `lp_write.py`/`pools_write.py --broadcast`, `ratchet.py arm --confirm` or `clear-attention`, `gmgn-cli swap`, `multi-swap`, `order strategy create|cancel`, `cooking create` — it waits for you on an ordinary exec prompt that names the key and, where there is one, the payout recipient. Unlike every other exec prompt, `bypass`, `/elevated full`, auto-approve, a cached intent and "Stop Asking" on another prompt do not answer it, and an unattended run (cron) is refused instead of asked. Approve each one yourself. The unattended `ratchet.py tick --broadcast` is the exception: it needs no prompt, but fires only the mandates whose `arm` you approved, with the bounds you approved. ### Cached Intents Approving a destructive action caches the *intent* — kind plus target path — rather than the literal command, so a paraphrased retry (`rm /tmp/x` followed by `os.remove("/tmp/x")`) proceeds without a second prompt. The kind carries a set of *escalation capabilities*, and a cached approval covers a retry only when its capability set is a superset of the retry's. The capabilities are independent — they are not a single ladder: | Capability | Meaning | Granted by | |---|---|---| | *(none)* | delete this one path | `rm X`, `os.remove`, `os.unlink`, `os.rmdir`, `Path(X).unlink()`, `Path(X).rmdir()` | | `recursive` | delete the whole tree below it | `rm -r`/`-R`/`--recursive`, `shutil.rmtree(X)` | | `parents` | may also delete empty *ancestors* | `os.removedirs(X)` | | `force` | `rm`'s `-f`/`--force` | `rm -f`/`--force` | So a `delete:recursive` approval covers a plain `rm X`, but a `delete:force` approval does **not** cover `shutil.rmtree(X)` — `force` says nothing about recursion. Escalation always re-prompts: approving `rm /tmp/logs` does **not** authorize `rm -rf /tmp/logs`. `/approvals` lists cached entries as `scope kind:target`, and `/forget <path>` drops every grade recorded for that path. The Web UI also provides an approvals surface for reviewing pending actions outside the message scrollback. ### Image Flow Spend Prompts An agent's `flow_run` (docs/flows.md) asks before it spends more than `[flows].agent_cost_limit_usd` on one run, or an amount that cannot be estimated, in its own namespace, `flow`. Every surface offers only **Allow once** and **Deny**: no "Always Allow", no "Bypass" / "Stop Asking", and the gateway ignores both for this namespace if a client sends them, so a spend approval never unlocks further spend or elevates the session. A session-wide bypass (`/elevated`, or "Stop Asking" on a shell prompt) releases pending `exec` prompts only, never a spend. A denial sticks: for 30 minutes every later `flow_run` of that flow in that session asks again, whatever its inputs or cost. ### Coding-Harness (ACP) Prompts Coding harnesses started with `sessions_spawn(runtime="acp")` (Claude Code, Codex, Gemini CLI, ...) ask for permission through the same approval queue, in two extra namespaces: | Namespace | What it is | Approve means | Deny / timeout means | | --- | --- | --- | --- | | `acp` | The harness wants to run a command, edit a file, fetch a URL, ... Shown as `"<harness> wants to <kind>: <title>"`, for example `Codex wants to run: git push`. | Allow this one call. | Reject this call; the harness carries on without it. | | `acp_elicitation` | The harness asks a question (a small form) or asks you to finish a step in the browser (a link). Shown as `"<harness> asks: <message>"` or `"<harness> asks you to open a link: <url>"`. | Answer: forms send their values as the resolve payload `{"content": {"<field>": <value>}}`; a link means "I finished the step". | Decline. | How a harness prompt is answered depends on `[acp].permission_mode`: | `permission_mode` | Behaviour | | --- | --- | | `ask` (default) | Every prompt waits in the approval queue for up to `[acp].approval_timeout_s` (default 900 s); no answer rejects it. | | `approve-reads` | Reads, searches, fetches and thinking are allowed without asking; anything else is asked as above. | | `approve-all` | Everything is allowed without asking. | | `deny-all` | Everything is rejected without asking. | A spawn may pick a stricter mode than the configured one, never a looser one. When nobody can answer (an unattended cron or channel run), `ask` follows `[acp].non_interactive_permissions`: `fail` (default) ends the harness turn with `ACP_PERMISSION_PROMPT_UNAVAILABLE`, `deny` rejects the prompt and lets the harness continue. Questions are always declined when nobody can answer. Choosing **Always** (or **Bypass**) on an `acp` prompt remembers the grant for that harness session only, per tool kind and, for commands, per program and subcommand (`git log`): it never changes the session's elevated mode and is forgotten when the harness session closes. Interpreters, shells, package runners (`npx`, `uvx`, `uv run`), `make`, `docker`, `curl`, `rm`-style programs and `git push`/`reset`/`clean`/`checkout`/`restore` are never remembered and always ask ([ACP agents](https://useagentos.dev/docs/core/acp-agents#permission-modes)). Forms are asked at most three questions at a time, a secret field always on its own; answers are cleared from the queue as soon as the harness has them and are never logged. Questions time out after 15 minutes. Over RPC, `approval.list` lists pending approvals of every namespace with a readable `title` (`params.namespace` narrows it; `params.display: true` answers exactly as `GET /api/approvals` does), and `exec.approval.resolve` (or `POST /api/approvals/resolve`) accepts an optional `payload` object for form answers. A prompt always shows the call that will actually run. When a tool hook rewrote the call's arguments (see "Tool and request hooks" in [Tools and Sandbox](https://useagentos.dev/docs/core/tools-and-sandbox)), the prompt and the pending result on the tool card show the rewritten command; the model is told only which of its arguments were adjusted. ### Where a prompt reaches you Every pending approval is listed in the web console (the approval tray on every page, the Inbox and Settings › Approvals) and in the desktop app's approval dialog. Beyond that: - **Web Push.** In the web console, Settings › Notifications › *Push notifications for approvals* subscribes this browser (it asks for notification permission; it needs HTTPS or `localhost`). Each new approval is pushed with a link that opens it in the console's Inbox; when it is resolved a replacement notice says how — granted, denied, expired, or cancelled because its run was stopped. The push goes out from the same queue write that announces `approval.resolved` to consoles. Messages are encrypted for the subscribed browser, expire with the approval and carry only its title. Turn it off per gateway with `[push] web_enabled = false`. - **Parent sessions.** An approval records `audience_session_keys`: the session that asked, then the sessions that spawned it (a coding harness's or subagent's parent, and that session's parent). The `approval.requested` event and `GET /api/approvals` carry it, and the chat view of any of those sessions shows the turn as *waiting for approval* while the child's prompt is pending. When the nearest such parent is delivered on Telegram, Discord or Slack, the prompt with *Approve* / *Deny* buttons is also sent to that chat. - **Channel custody.** On Telegram, Discord and Slack, *Approve* / *Deny* works only in the chat the approval's session is delivered to — a DM session answers to its own sender, a group or channel session to members of that chat, a child session to its parent's chat, and the shared main DM session to the chat it last delivered to. A paired sender cannot resolve a prompt that belongs to the web console, the desktop or another chat. ## Sandbox Posture Inspect sandbox posture: ```sh agentos sandbox status agentos sandbox status --json ``` Set posture: ```sh agentos sandbox on agentos sandbox bypass agentos sandbox full agentos sandbox reset ``` Restart the gateway after changing global sandbox posture: ```sh agentos gateway restart ``` ## Recommended Defaults | Situation | Recommended approach | | --- | --- | | First run in a repo | `--workspace` plus `--workspace-strict` | | Read-only investigation | `--permissions restricted` | | Local patch with tests | `--workspace-lockdown` plus a scratch directory | | Web UI task with writes | Keep approvals visible and review sensitive actions | | Channel-connected agent | Conservative permissions and explicit channel setup | | Unattended automation | Bound timeout/iterations and choose the narrowest workable permissions | ## Troubleshooting If a tool is denied: ```sh agentos sandbox status agentos doctor ``` Then check: - whether the surface supports live approvals; - whether the workspace path is correct; - whether cached approvals need to be reset; - whether the task should run with a different permission profile. Read next: - [Tools, Approvals, and Sandbox](https://useagentos.dev/docs/core/tools-and-sandbox) - [Web UI](https://useagentos.dev/docs/core/web-ui) - [Channels](https://useagentos.dev/docs/core/channels) --- # Durable Agents > Source: https://useagentos.dev/docs/core/agents AgentOS agents are named runtime profiles. Use them when different work streams need different defaults, such as a research workspace, a writing workspace, or a channel-facing assistant. The built-in `main` agent is always available. Additional agents are configured with `agentos agents`. ## When to Create an Agent Create a durable agent when you want a stable identity for: - a dedicated workspace; - a default model choice; - a separate channel or automation target; - a recurring task profile; - a specialized assistant name and description. Do not create a new agent for every conversation. Use sessions for ordinary conversation continuity. ## List Agents ```sh agentos agents list agentos agents list --json ``` ## Add an Agent ```sh agentos agents add research \ --name Research \ --description "Research and synthesis workspace" \ --workspace /path/to/research \ --model gpt-5.4-mini ``` Agent changes are written to configuration. Restart the gateway before relying on the updated agent list: ```sh agentos gateway restart ``` ## Use an Agent With Sessions Filter sessions by agent: ```sh agentos sessions list --agent research ``` Create scheduled work for an agent: ```sh agentos cron add \ --agent research \ --every 1h \ --job-kind agent_turn \ --text "Summarize new research notes" \ --name research-hourly-summary ``` Channel configuration can also route incoming messages to configured agents depending on the channel setup. ## Delete an Agent ```sh agentos agents delete research agentos agents delete research --force ``` Deleting an agent entry leaves workspace files and state untouched. Clean those up separately only when you are sure they are no longer needed. ## Agents vs Sessions vs Skills | Concept | Use for | | --- | --- | | Agent | Durable identity and defaults for a work stream. | | Session | Conversation history and active task continuity. | | Skill | Reusable workflow instructions or tool routines. | Read next: - [Sessions and History](https://useagentos.dev/docs/core/sessions) - [Skills](https://useagentos.dev/docs/core/features/skills) - [Channels](https://useagentos.dev/docs/core/channels) --- # Scheduling > Source: https://useagentos.dev/docs/core/scheduling AgentOS scheduling lets you run recurring or one-time agent work from the gateway. Use it for reminders, periodic summaries, status checks, channel updates, and webhook-delivered automation. Scheduling is managed with the `agentos cron` command group. ## Requirements Scheduled jobs run through the gateway: ```sh agentos gateway run ``` For long-lived local use, start the managed gateway: ```sh agentos gateway start --json agentos gateway status ``` ## List Jobs ```sh agentos cron list agentos cron list --agent main agentos cron list --json ``` Job visibility is scoped to the selected profile, not to the session that created each job. Calls from the Control UI, CLI, or a paired channel therefore see the same profile-wide schedule list. The creation session is retained as delivery metadata and shown as **Created from** when available. ## Add an Interval Job Run a prompt every hour: ```sh agentos cron add \ --every 1h \ --job-kind agent_turn \ --text "Summarize important project updates" \ --name hourly-project-check ``` Intervals accept values such as `30s`, `5m`, and `1h`. ## Add a Cron Expression Run on weekdays at 09:00 in a named timezone: ```sh agentos cron add \ --cron "0 9 * * 1-5" \ --tz "America/Los_Angeles" \ --job-kind agent_turn \ --text "Prepare a short morning brief" \ --name weekday-morning-brief ``` Use `--exact` when you do not want the default stagger. Day-of-month and day-of-week follow the POSIX rule: when **both** fields are restricted (neither is a bare `*`), the job fires when *either* matches. So `0 0 1,15 * 5` runs on the 1st, the 15th, **or** any Friday. When one of the two is `*`, the fields are ANDed as usual — `0 0 1 * *` is the 1st only, and `0 0 * * 5` is Fridays only. ## Add a One-Time Job ```sh agentos cron add \ --at "2026-06-01T09:00:00+00:00" \ --text "Remind me to review the launch checklist" \ --name launch-checklist-reminder ``` ## Job Kinds `--job-kind` decides what actually happens when a job fires. It defaults to `auto`, which resolves to `reminder` for normal targets, `system_event` for `--session-target main`, and `script` when you pass `--script`. | Kind | What fires | Spends tokens | | --- | --- | --- | | `reminder` | Your `--text` is delivered verbatim. Nothing else runs. | No | | `script` | A file in `~/.agentos/scripts/` runs; its stdout is delivered. | No | | `agent_turn` | The agent runs `--text` as a prompt and its reply is delivered. | Yes | | `system_event` | The text is written into the main session and wakes the heartbeat. | Yes | An `agent_turn` job can also carry a `--script`, which then runs *before* the turn as a data collector — see [Pre-run scripts](#pre-run-scripts). The default matters: `agentos cron add --every 1h --text "Summarize updates"` creates a **reminder**, so it repeats that sentence every hour rather than summarizing anything. Add `--job-kind agent_turn` when you want the agent to do the work. ## Run a Script Instead of a Model A `script` job is the watchdog shape — poll something on a timer, deliver a line when it matters, stay quiet otherwise — with no LLM in the loop: ```sh mkdir -p ~/.agentos/scripts cat > ~/.agentos/scripts/watch-memory.sh <<'EOF' #!/usr/bin/env bash used=$(ps -A -o %mem | awk '{s+=$1} END {printf "%d", s}') [ "$used" -gt 90 ] && echo "⚠ memory at ${used}%" EOF agentos cron add --every 5m --script watch-memory.sh --name memory-watchdog agentos cron update <job-id> --script watch-disk.sh ``` The script path is **relative to `~/.agentos/scripts/`**. Absolute paths, `~`, and `..` are refused, and a symlink that leaves the directory is refused at run time — the directory is the trust boundary. `.sh` and `.bash` run under bash; every other extension runs under the same Python interpreter as the gateway. Pass `--workdir` to run somewhere other than the script's own directory; a relative value is resolved against the script's directory, not the gateway's, so `--workdir data` means `~/.agentos/scripts/data`. A workdir that does not exist falls back to the script's directory with a warning in the gateway log. Subdirectories under `~/.agentos/scripts/` are allowed, and `{job_id}` anywhere in the path is replaced with the created job's own id: ```sh agentos cron add --every 10m --script 'lp-monitor/{job_id}/tick.sh' --name lp-ratchet ``` That gives a job a directory named after itself in a single `add` — the id does not exist until the job does, so the alternative is to create the job against a staging path and repoint it afterwards, leaving a live job pointing at a path it will not keep. The job it prints back carries the resolved path in its `script` field; write the file there. A job whose stored path somehow still holds `{job_id}` refuses to run rather than creating a directory by that name. Arguments go through `--script-arg`, repeated once per argument: ```sh agentos cron add --every 15m --script watch_rss.py --name hn-watch \ --script-arg --name --script-arg hn \ --script-arg --url --script-arg https://news.ycombinator.com/rss ``` They are passed to the script as argv with no shell in between, so a value containing spaces or `;` stays one argument and cannot start a second command. The Web UI takes them as one line and splits it the way a shell would. The bundled **cron-watchers** skill ships ready-made scripts for the common sources (RSS/Atom, a JSON endpoint, a GitHub repo) that already follow this contract — ask the agent for it, or see `agentos skills view cron-watchers`. What the job does with the result: - **stdout** → delivered verbatim, exactly as printed (capped at 16k characters). - **no stdout** → silent run. Nothing is delivered and the run counts as a success, so a watchdog that prints only on trouble stays quiet. - **a final line of `{"wakeAgent": false}`** → also treated as silence, so watchdog scripts written for other runtimes work unchanged. Nothing is delivered, but what the script printed stays on the run record, where `agentos cron output <job-id>` shows it. - **non-zero exit or timeout** → the error is delivered *and* the job fails, so a broken watchdog cannot be mistaken for a quiet one. `--timeout` bounds the run (default 600s). Secrets are masked in both stdout and stderr before delivery, and AgentOS's own controls (`AGENTOS_GATEWAY_TOKEN` and the redaction/sensitive-path switches) are withheld from the child process. Provider credentials are *not* — a script inherits `OPENAI_API_KEY` and friends exactly like every other AgentOS child process, which is what lets a watcher call a model API of its own. Set `AGENTOS_STRIP_PROVIDER_ENV=1` to withhold those too. **What you are accepting.** The script runs on this host as you, on schedule, with nobody watching and no approval prompt — there is no LLM deciding what to run, but also nothing reviewing it. Treat `~/.agentos/scripts/` as trusted as your shell profile, and remember that anything with write access to that directory can schedule itself. For that reason a script job can only be created by an interactive CLI or Web caller: the in-agent `cron` tool refuses `job_kind='script'` from a channel, which keeps a chat message from scheduling unattended execution. For the same reason an `agent_turn` job the tool creates from a channel is stored with `tool_policy.elevated = "off"`, so `cron_default_mode` never hands it a shell its creator did not have (see [Tools, Approvals, and Sandbox](https://useagentos.dev/docs/core/tools-and-sandbox#delegated-work-and-caller-authority)). Script jobs never take `--elevated` — elevation only means something for a job that runs an agent turn. ## Pre-run Scripts The other half of the same idea: keep the script, but let an agent read what it found instead of the user. Add `--script` to an `agent_turn` job and it runs first, as a data collector: ```sh agentos cron add --every 10m --name repo-triage \ --job-kind agent_turn \ --script watch_github.py \ --script-arg --repo --script-arg owner/name \ --script-arg --scope --script-arg issues \ --text "Summarize anything here that looks urgent. Stay brief." ``` Per tick: - **stdout** → prepended to the prompt as `## Script output`, then the turn runs with your `--text` after it. - **no stdout** (or a `{"wakeAgent": false}` final line) → the turn is skipped entirely. No LLM call, no session, no transcript line, no delivery. This is what makes the pattern cheap: the agent only wakes on ticks with news. - **non-zero exit** → the error is prepended as `## Script error` and the turn runs anyway, so the agent can tell the user the collector broke. Same directory rule, same argv handling, and the same operator gate as a script job. The script's stdout is untrusted input arriving inside a prompt — the header says so to the model, but the turn still runs elevated by default (`cron_default_mode="bypass"`), so that output can drive real shell-based skill calls with no approval prompt. Pass `--no-elevated` to drop a job back to a read-only tool surface, and prefer that whenever a pre-run script reads the open internet. ## Choose the Session Target The default target is an isolated session. For most scheduled work, that is the least surprising option. Useful targets: | Target | Use when | | --- | --- | | `isolated` | Each scheduled run should stand alone. | | `session` | You want to deliver into a specific session configured by the runtime surface. | | `current` | The job should continue in the session that created it (requires a bound session). | | `main` | You want a system event for the main session. | Example: ```sh agentos cron add \ --every 30m \ --session-target isolated \ --text "Check for urgent channel updates" \ --name urgent-update-check ``` ## Delivery Disable delivery: ```sh agentos cron add \ --every 1h \ --text "Create a private summary" \ --no-deliver \ --name private-hourly-summary ``` Deliver through a webhook: ```sh agentos cron add \ --every 1h \ --text "Post a compact status summary" \ --webhook-url https://example.com/hooks/agentos \ --webhook-token-env AGENTOS_WEBHOOK_TOKEN \ --name webhook-status-summary ``` Prefer `--webhook-token-env` or `--webhook-token-file` over inline tokens so secrets do not land in shell history. ### Naming a channel recipient Channel delivery is configured from the Web UI, the RPC API, or the in-agent `cron` tool (below), and its **Recipient** is the id the *provider* uses — a Telegram chat id (`1245463966`, negative for a group) or `@username`, a Slack channel id. It is not an AgentOS session key: `agent:main:telegram:direct:1245463966` names a conversation inside AgentOS, and Telegram answers `chat not found` for it. Both are visible in the UI and the two are easy to confuse, so a save that carries a session key is rejected outright, and the gateway asks the channel whether the chat exists before storing it. Where the recipients are known — Telegram, whose pairing store lists every chat the bot may talk to — the Web UI offers them as a dropdown, with an `Enter manually…` escape hatch for a group chat that is not in `group_chat_ids`. ### Asking the agent for a specific destination The in-agent `cron` tool takes an optional `delivery` object, so a job created in conversation can announce somewhere other than the chat it was asked for: ```json { "mode": "channel", "channel_name": "telegram", "channel_id": "-1001234567890", "best_effort": false } ``` `delivery` is accepted on `add` and on `update`, so an existing job can be moved without being re-created. `mode` is `origin` (the calling conversation — identical to omitting `delivery` on `add`), `channel`, or `none`. `channel_id` follows the same recipient rules as above and is validated when the job is saved, so a session key or a non-numeric Telegram target fails immediately rather than at the next fire; an empty `channel_id` uses the channel's configured default chat. `channel_name` is checked against the configured channels, so a typo cannot be saved — note that it is the entry's *name*, which is the adapter type unless the operator renamed it. A destination field paired with `mode='origin'` or `mode='none'` is rejected rather than quietly falling back to the caller. `best_effort` applies to any mode. Unlike the Web UI, the tool does not probe the adapter to confirm the chat exists, and `account_id` is accepted and binds the job to a specific account instance in multi-account setups. Webhook delivery and failure destinations are refused outright here — they stay CLI/Web/RPC-only, so an agent cannot be talked into POSTing job output at an arbitrary URL. `mode='channel'` needs an interactive CLI or Web caller and a `sessionTarget` other than `main`. Asked from a chat channel it is refused and the job keeps delivering to that same conversation, so a participant in one room cannot aim scheduled output at another. Note that this gate is the same strength as the one on `--elevated` and script jobs: `callerKind` says the request entered through the gateway, not that a human approved it. Inside a Web or CLI session the agent can set it without a confirmation step, so untrusted content the agent reads can in principle steer the destination — the `delivery` block echoed in the `add` response is there to be checked. ## Inspect and Run Jobs ```sh agentos cron status <job-id> agentos cron runs <job-id> agentos cron runs <job-id> --limit 50 ``` Run a job immediately: ```sh agentos cron run <job-id> --yes ``` `cron runs` shows each run's `Output` (the reply, or a script job's stdout) and `Delivery` (where that output went). Use `--json` for untruncated output. ### Asking the agent what a job did The in-agent `cron` tool reads the same history through `action="runs"`, so you can ask in chat — "what did the memory watchdog report today?" — and the model answers from the recorded runs instead of guessing what the schedule produced: ```json {"action": "runs", "job_id": "<job-id>", "limit": 5} ``` It returns each run's `started_at`, `success`, `output`, and `delivery`, plus `error` on a failure. `limit` defaults to 5 and is clamped to 20, and output longer than 2000 characters comes back with `output_truncated: true` — the full text is always available from `agentos cron runs <job-id> --json`. The action is scoped to the caller's own profile, the same boundary `remove` and `run` use. A script job's stdout can contain whatever the script fetched (an RSS item, an API response), and `action="runs"` puts that text in the model's context. That is the same content a delivered job already mirrors into the chat, but a job that reports nowhere is now readable too, so treat script output as untrusted input the same way you would any fetched content. ## Update or Remove Jobs ```sh agentos cron update <job-id> --enabled agentos cron update <job-id> --disabled agentos cron update <job-id> --every 2h agentos cron remove <job-id> --yes ``` Primary delivery destinations are not patched in place from the CLI. Remove and re-add a job when the primary channel or webhook destination needs to change. ### Editing and cloning a job from chat The in-agent `cron` tool edits jobs the same way, so "change that reminder to 7:30" does not have to become a delete-and-recreate — which would reset the job's kind, timezone, tool policy, and delivery target to defaults: ```json {"action": "get", "job_id": "<job-id>"} {"action": "update", "job_id": "<job-id>", "task": "Summarize yesterday's PRs"} {"action": "update", "job_id": "<job-id>", "schedule": {"kind": "cron", "expr": "30 7 * * 1-5"}} {"action": "update", "job_id": "<job-id>", "enabled": false} ``` `action="get"` returns the full record — kind, timezone, schedule, session target, delivery, tool policy, wake mode, timeout, script fields — which `action="list"` does not. `action="update"` patches only the keys it is given and keeps the job's id and everything else. Deriving a second job from an existing one is `clone_from` on `add`. The clone inherits every setting of the source and overrides only what is passed alongside; the source keeps running: ```json {"action": "add", "clone_from": "<job-id>", "task": "Summarize yesterday's incidents"} ``` Delivery is one of the settings a clone inherits, so a clone announces wherever its source did unless it is given a `delivery` of its own — passing one redirects the clone and leaves the source alone. To move the existing job rather than derive a second one, pass `delivery` to `update`: ```json {"action": "update", "job_id": "<job-id>", "delivery": {"mode": "channel", "channel_name": "telegram", "channel_id": "-1001234567890"}} ``` A repoint keeps the job's id, its run history, and its websocket topic, so subscribers watching the job stay attached. The gates are the same ones `add` applies: `mode='channel'` needs an interactive CLI or Web caller and a session target other than `main`, the recipient is validated at save time, and a chat caller cannot repoint a job that already answers somewhere that chat cannot address. Webhook destinations and failure destinations remain CLI/Web/RPC-only. Both paths keep the operator gates. A job carrying a script or `tool_policy.elevated` can only be cloned or updated by an interactive CLI or Web caller, and so can the task of an `agent_turn` job that runs elevated through `cron_default_mode`; a chat's edit of its own job keeps it at `elevated = "off"`. So can a job whose delivery points somewhere the calling session cannot post — another channel, or a webhook — because rewriting its text or cloning it would put the caller's words on somebody else's destination. A webhook's URL and token are never disclosed by `action="get"`: it reports the host plus `webhook_url_set` / `webhook_token_set`. Cloning a one-shot `at` job requires an explicit new schedule, and a clone always starts enabled. ## Overlapping Runs A job's next run can come due while its previous run is still going — a long agent turn on a short interval, or a run that hangs until its timeout. `--concurrency` decides what happens then: | Policy | When the next run comes due during a run | |---|---| | `forbid` (default) | Skip it. The next run is scheduled from when the running one finishes. | | `replace` | Cancel the running run and start the new one. The cancelled run is kept in `cron runs` as `replaced by a newer run`; it is not counted as a failure. | | `allow` | Start the new run alongside. The newest run owns the job's schedule and counters; the earlier one is kept in run history only. Runs still count against the scheduler's concurrent-run limit. | ```sh agentos cron add --every 5m --job-kind agent_turn \ --text "Check the deploy queue" --concurrency replace agentos cron update <job-id> --concurrency allow ``` `replace` can only cancel a run the scheduler itself started; a run started by `agentos cron run` is left to finish, but its result no longer updates the job. One-shot `--at` jobs have no next run, so the policy never applies to them. ## Job Health `agentos cron list --json` (the `cron.list` RPC) and `cron status` report each job's `concurrency` and a `health` block: ```json "health": {"consecutive_failures": 3, "last_error": "Timeout after 600.0s", "degraded": true} ``` `consecutive_failures` is the job's current failure streak; one successful run resets it to 0. `last_error` is the error of the most recent finished run and is `null` after a success — a run in progress does not clear it, so a degraded job keeps showing why. `degraded` turns on at 3 consecutive failures. A recurring job is marked `failed` and stops after 5, and an authentication-class error (401/403, invalid key) disables it on the first failure. A WebSocket client subscribed to a job (`cron:<id>`, or `cron:*`) gets `cron.run.finished` once the run is on record: the run's history entry and the job's new `health` are already saved, so a re-read agrees with it. The event carries `runId`, `status` (`ok`/`error`), `error`, `durationMs`, the job's `health`, `lastStatus`, `nextRun`, and the job as `cron.list` renders it (`job`), so no re-read is needed. For a one-shot job its run deleted, `jobDeleted` is true and `health` is `null`. ## Sleep, Restarts, and Clock Changes The scheduler plans its next wake against both the wall clock and the system's monotonic clock and wakes at whichever says the time has come first, re-checking at least once a minute. Whether a job is due is always decided by the wall clock, because schedules are wall-clock times. - **Laptop sleep.** The monotonic clock stops while the machine sleeps. On the first wake after the lid opens the scheduler sees that the wall clock moved on and runs every job that came due in the meantime — once each, however many runs were missed (a five-minute job asleep for an hour runs once, not twelve times). The gateway also notices the thaw on its own maintenance tick and wakes the scheduler at once. - **Clock set back** (an NTP correction, a manual change). Nothing fires early and nothing fires twice: a run's next slot is always computed after the moment that run started, so a job never repeats the slot it just ran. - **Gateway restart.** Jobs missed while the gateway was down are caught up at boot: at most 5, staggered over 10 seconds; any further missed recurring jobs skip ahead to their next slot. Missed *agent* jobs (an agent turn, or a main session system event) wait 2 minutes after boot so they do not compete with channel start-up for the model; reminders and script jobs run straight away. The wait shows as the job's next run time, so `agentos cron list` is accurate meanwhile, and a crash during the wait does not lose the job. Change the post-boot wait for agent jobs (seconds; `0` runs them at boot like every other job), then restart the gateway: ```sh agentos config set scheduler.startup_agent_delay_seconds 300 ``` ```toml [scheduler] startup_agent_delay_seconds = 300 ``` The gateway log records `scheduler_wake_gap` (a sleep or a clock moved forward), `scheduler_clock_back`, and `scheduler_late_wake` (the scheduler woke more than twice as late as planned) when they happen. - **Safe mode.** A gateway that crashed three times in five minutes boots in safe mode and does not start the scheduler: no job runs on its own until safe mode clears (after five quiet minutes, or `agentos channels start --yes`), and the startup catch-up runs then. `agentos cron run <id>` still works meanwhile, except for a job the crash left marked running. See [Gateway](https://useagentos.dev/docs/core/gateway#crash-loop-breaker-safe-mode). ## Automation From Outside Something outside AgentOS — CI, a repository webhook, a no-code workflow — can start agent work without a chat channel through the inbound webhooks: ```sh curl -X POST -H "Authorization: Bearer $AGENTOS_HOOKS_TOKEN" \ -H "Content-Type: application/json" \ -d '{"message": "Nightly build failed: summarize the log", "idempotency_key": "build-4211"}' \ http://127.0.0.1:18791/api/v1/hooks/agent ``` - `/api/v1/hooks/agent` enqueues the message into `agent:main:hook:agent` (or another `agent:<agent>:hook:...` key you pass as `session_key`). - `/api/v1/hooks/wake` asks the heartbeat loop to run its next tick now (a disabled heartbeat or quiet hours still skip it). - `/api/v1/hooks/<name>` maps any JSON body to an agent, a session and a message template set in `[hooks.routes.<name>]` — point a repository's webhook straight at it. They use their own `[hooks] token`, never the gateway token. Retried deliveries are deduplicated by `idempotency_key` (or the `Idempotency-Key` header) for five minutes; each hook is limited to `rate_limit_per_minute` calls and `max_sessions_per_hook` sessions per hour; reusing an idempotency key for a different body is `409`. Setup: [Configuration → Inbound webhooks](https://useagentos.dev/docs/core/configuration#inbound-webhooks); responses: [HTTP API → Inbound webhooks](https://useagentos.dev/docs/core/http-api#inbound-webhooks). ## Troubleshooting Check the gateway and job state: ```sh agentos gateway status agentos cron list agentos cron status <job-id> agentos cron runs <job-id> ``` If a job posts to a channel, also check: ```sh agentos channels status ``` A `script` job that appears to do nothing is usually working as designed: empty stdout, or a final `{"wakeAgent": false}` line, means silence. `agentos cron runs <job-id>` distinguishes the two — a silent run is recorded with a `silent: …` summary (followed by whatever the script printed above its gate, which `agentos cron output <job-id>` shows in full), while a broken script is recorded as a failure with the exit code and stderr. Read next: - [Channels](https://useagentos.dev/docs/core/channels) - [Operations](https://useagentos.dev/docs/core/operations) - [Troubleshooting](https://useagentos.dev/docs/core/troubleshooting) --- # HTTP API > Source: https://useagentos.dev/docs/core/http-api The AgentOS gateway is a [Starlette](https://www.starlette.io/) ASGI application that exposes a **REST HTTP API** alongside its streaming WebSocket. Every AgentOS surface — CLI, Web UI, channels, and external clients — talks to this same gateway, so the HTTP endpoints below are a stable integration point for your own applications and automation. Use this page when you want to call AgentOS from an external app, script, or service instead of the CLI. ## Base URL and Auth The gateway binds to loopback by default: ```text http://127.0.0.1:18791 ``` **On the default loopback bind, no token is required.** The gateway ships with `auth.mode = "none"`, and a loopback peer is admitted as a Control connection, so `curl http://127.0.0.1:18791/api/...` works with no credentials. A token is only enforced when `auth.mode = "token"`. A public address (`0.0.0.0` / LAN) needs that mode or `trusted-proxy`: the startup guard refuses to serve an unauthenticated public bind, and a token is auto-generated when unset. See [Gateway](https://useagentos.dev/docs/core/gateway) for bind safety and [Remote Access](https://useagentos.dev/docs/core/remote-access) for tunnels and reverse proxies. When auth is enabled, send the token via HTTP headers (checked in order): ```text Authorization: Bearer <token> X-Agentos-Token: <token> ``` > **Note:** Query-string tokens (`?token=<token>`) are rejected (`401 Unauthorized`). Passing tokens in URL query parameters is not supported to prevent token leaks in access logs, browser history, and HTTP referrers. The gateway implements exactly three auth modes — `none`, `token`, and `trusted-proxy`. Any other value (including the never-implemented `"password"`, or a typo like `"tokenn"`) is refused when the config loads rather than silently admitting every request; the startup error names the supported modes. `trusted-proxy` admits a request only when the transport peer is listed in `auth.trusted_proxy` (IP literals or CIDR blocks such as `10.0.0.0/8`, comma-separated). `X-Forwarded-For` is read only from such a peer and walked right to left, skipping trusted hops; an address naming the gateway host itself is ignored as spoofed. ### Failed-auth rate limiting A *wrong* token counts against a budget per client address, shared by HTTP and the WebSocket: ten failures within 60 seconds lock that address out for five minutes, whatever `Origin` header its attempts carry. A locked-out client gets `429` with `Retry-After` (seconds) and ```json {"error": "Too many failed authentication attempts", "code": "RATE_LIMITED", "details": {"code": "AUTH_RATE_LIMITED", "retry_after_ms": 299000}} ``` even when it presents the right token. A request with no token is a plain `401` and never counts. A loopback address is never locked out (each failure is answered after a delay growing from 250 ms to 5 s), but browser requests (those carrying `Origin`) are also counted in a second budget per address, shared by every `Origin` value and never exempt, so a page in the operator's browser cannot guess the token from loopback, and rotating `Origin` gains nothing. Behind a proxy on the same host every client looks like loopback: list the proxy in `auth.trusted_proxy` (its `X-Forwarded-For` then names the client) or set `exempt_loopback = false`. Settings: ```toml [auth.rate_limit] enabled = true max_failures = 10 window_seconds = 60 lockout_seconds = 300 exempt_loopback = true ``` `/health`, `/ready` and `/startupz` never require a token. Browser requests that carry an `Origin` header follow the gateway's origin policy on every bind — declared origins, a private address opened as itself, or a loopback origin on this machine — and CORS reflects only those origins, never `*`; see [Gateway → Browser origins](https://useagentos.dev/docs/core/gateway#browser-origins). Two route families authenticate themselves instead of with the gateway token: ticketed downloads (`/api/v1/artifacts/download/...`, the ticket is the credential) and inbound webhooks (`/api/v1/hooks/...`, their own `[hooks] token`). ## Liveness and Readiness | Method | Path | Purpose | | --- | --- | --- | | `GET` | `/health`, `/healthz` | Liveness probe — `{"ok": true, "status": "live"}`. | | `GET` | `/ready`, `/readyz` | Readiness probe — `{ready, state, failing, startup, safe_mode, drain_budget_ms, uptime_ms}`; `state` is `starting`, `ready`, `draining` or `safe_mode`. `503` while starting or draining, `200` when ready and in safe mode. `failing` also lists down channels as `channel:<name>` without making the gateway unready. The older `status` field mirrors `state`. | | `GET` | `/startupz` | Startup probe — `200` once every boot sidecar settled (channels started, router preloaded), `503` with the `pending` list before. | These require no auth and are safe for load balancers and container probes. The full supervisor contract (WebSocket refusal during boot, the `shutdown` event, exit code `78`) is in [Gateway](https://useagentos.dev/docs/core/gateway#supervisor-contract). ## Core Endpoints | Method | Path | Purpose | | --- | --- | --- | | `GET` | `/api/config` | Effective gateway configuration. | | `GET` | `/api/system/status` | Version, uptime, active provider, auth mode, plus `circuitBreaker` (the active provider's breaker) and `circuitBreakers` (every tracked provider). | | `GET` | `/api/sessions` | List sessions. | | `POST` | `/api/chat` | Send a chat turn. Body: `message` (required), `sessionKey` (optional). | | `GET` | `/api/chat/history?sessionKey=<key>` | Fetch a session transcript. | | `GET` | `/api/agents` | List durable agents. | | `GET` | `/api/cron` | List scheduled jobs. | | `GET` | `/api/usage` | Token usage and cost breakdown. | | `GET` | `/metrics` | Prometheus metrics exposition (`observability.metrics_path`). | | `POST` | `/api/v1/rpc` | Call an allowlisted RPC method: `{id?, method, params?}` → `{id, ok, payload \| error}`. See [RPC over HTTP](#rpc-over-http). | ## Channels | Method | Path | Purpose | | --- | --- | --- | | `GET` | `/api/channels/status` | Channel connection status. | | `POST` | `/api/channels/logout` | Log a channel out. | ## Approvals and Permissions | Method | Path | Purpose | | --- | --- | --- | | `GET` | `/api/approvals` | Pending approvals + current mode/patterns. | | `POST` | `/api/approvals/settings` | Set mode (`prompt` / `auto-approve` / `auto-deny`). | | `POST` | `/api/approvals/resolve` | Approve or deny a pending item (optional `payload` object carries ACP form answers). | | `POST` | `/api/elevated-mode` | Set per-session elevated mode (admitted Control connection only). | `GET /api/approvals` serializes every pending command and its arguments, so it is rate limited per client IP like the rest of `/api/*` — just in its own bucket, because consoles read it on every reconnect, window focus and resolve (older consoles still poll it every 1.5s). The cap is `AGENTOS_RATE_APPROVALS_MAX_REQUESTS` (default 300 per `AGENTOS_RATE_WINDOW_SECONDS`, i.e. 300/min), which clears several open tabs. Raise it only if you run more consoles than that against one gateway. Queue changes are also pushed over the WebSocket to Control connections (never to channel or node connections, nor to a connection holding an agent token), for every namespace (`exec`, `plugin`, `acp`, `acp_elicitation`): - `approval.requested` — `{id, namespace, session_key, audience_session_keys, created_at, expires_at, summary, tool, command, approval}` (fields that do not apply are omitted; `approval` is the item exactly as `GET /api/approvals` lists it, with the same audience as `audienceSessionKeys`). `audience_session_keys` is the requesting session followed by the sessions that spawned it, so a parent session's view can match a child's prompt. - `approval.resolved` — `{id, namespace, decision, resolved_by, resolved_at}`, `decision` being `approved`, `denied`, `expired` or `cancelled` (its run was aborted); `resolved_by` is `operator`, `policy`, `session_elevation`, `timeout`, `abort` or `system`. The gateway sweeps the queue every 30 s, so an expiry is announced even when nothing waits on the prompt. A row an `auto-approve` / `auto-deny` policy settles in the same call that queued it is not announced at all. Use the REST list once per (re)connect to catch up on what happened while the socket was down. ## Files and Media | Method | Path | Purpose | | --- | --- | --- | | `POST` | `/api/v1/files/upload` | Upload a file; returns an opaque id for `chat.send`. | | `GET`, `HEAD` | `/api/v1/artifacts/download/{conn_id}/{ticket}` | Fetch an artifact or attachment through a ticket minted with the `artifacts.download` RPC. No `Authorization` header. | | `GET` | `/api/v1/attachments/{sha256}?sessionKey=` | Deprecated: fetch an attachment by content hash. | | `GET` | `/api/v1/artifacts/{artifact_id}?sessionKey=` | Deprecated: fetch a generated artifact. | | `POST` | `/api/audio/transcribe` | Transcribe audio to text. | ### Ticketed downloads Over the WebSocket, ask for a download URL: ```json {"type": "req", "id": "1", "method": "artifacts.download", "params": {"session_key": "agent:main:webchat:default", "artifact_id": "art-…", "transport": "http"}} ``` Use `attachment_sha256` (plus the display `name` and `mime`) instead of `artifact_id` for a file a user attached. The answer carries `url` (`/api/v1/artifacts/download/<conn_id>/<ticket>`), `expiresAt` (epoch ms), `ttlSeconds`, `name`, `mime` and `size`. The ticket is 32 random bytes, lives five minutes, is bound to the WebSocket connection that minted it and dies when that connection closes; a connection holds at most 128 live tickets (the oldest goes first). The URL works for `<img>`, `<audio>`, `fetch()` and plain links without a header. The route answers `HEAD`, one byte range (`Range: bytes=0-1023` → `206`; several ranges get the whole file), and `?variant=thumbnail` for a PNG, JPEG or WebP still image: a PNG no larger than 1200 px on its longest side. Every response carries `Content-Security-Policy: default-src 'none'; sandbox`, `Content-Disposition: attachment`, `Cache-Control: no-store` and `X-Content-Type-Options: nosniff`, so an HTML or SVG file opened directly cannot run script. An unknown, expired, revoked or foreign ticket is `404`; a file that no longer matches its recorded hash is `409` with `details.code = "INTEGRITY_ERROR"` (the RPC answers `INTERNAL_ERROR` with the same reason), and a thumbnail of anything else `415` with `details.code = "UNSUPPORTED_MEDIA_TYPE"`. The `?sessionKey=` routes keep working for this release, with a deprecation line in the log the first time each is used, and go away in the next. Turn them off now with `[artifacts] legacy_session_key_urls = false`. ## RPC over HTTP `POST /api/v1/rpc` calls one gateway RPC method without a WebSocket, behind the same bearer auth, origin guard and rate limits as the other `/api/*` routes: ```sh curl -X POST -H "Authorization: Bearer $AGENTOS_TOKEN" \ -H "Content-Type: application/json" \ -d '{"id": "1", "method": "sessions.list", "params": {"limit": 5}}' \ http://127.0.0.1:18791/api/v1/rpc ``` The body is `{id?, method, params?}` (`id` a string or integer, echoed back; `params` an object). The answer is the WebSocket `res` frame without its `type`: `{"id", "ok": true, "payload"}` with `200`, or `{"id", "ok": false, "error": {code, message, details, retryable, retry_after_ms}}` with a status from the error's category: | Category | Status | | --- | --- | | `INVALID_REQUEST` | `400` | | `UNAUTHORIZED`, `FORBIDDEN` | `403` | | `NOT_FOUND`, `METHOD_NOT_FOUND` | `404` | | `RATE_LIMITED` | `429` | | `UNAVAILABLE` | `503` | | `INTERNAL_ERROR` and anything else | `500` | Only an allowlist is reachable: reads (`health`, `status`, `config.get`, `sessions.list`/`get`/`preview`/`resolve`, `chat.history`, `models.list`, `usage.*`, `agents.list`, `projects.list`/`get`, `skills.list`, `cron.list`, `channels.status`, `doctor.status`, `acp.*` status, ...) and mutations that create, rename or send without deleting anything (`chat.send`, `sessions.send`, `sessions.create`, `sessions.rename`, `sessions.pin`, `projects.create`/`update`, `*.abort`, `plan.mode.set`; turning plan mode off is refused for a caller the gateway recognizes as an agent's: its token, a process the gateway spawned, or an open agent shell). `chat.send` and `sessions.send` start an agent turn with the same options as over the WebSocket, including an elevated execution mode the request asks for, so the token must be treated as full operator access either way. Configuration writes, secrets and environment variables, trading and wallets, restarts, deletes and approval decisions stay on the WebSocket. Any other method answers `403` with `error.code = "FORBIDDEN"` and `details.code = "METHOD_NOT_ALLOWED_OVER_HTTP"`. The full list is `HTTP_RPC_METHODS` in [`src/agentos/gateway/http_rpc.py`](../src/agentos/gateway/http_rpc.py). ## Direct tool calls `POST /api/v1/tools/invoke` runs one tool without an LLM turn (bearer auth, Control surface): ```sh curl -X POST -H "Authorization: Bearer $AGENTOS_TOKEN" \ -H "Content-Type: application/json" \ -d '{"tool": "web_search", "args": {"query": "agentos release notes"}}' \ http://127.0.0.1:18791/api/v1/tools/invoke ``` Body: `tool` (required), `args` (object), `action` (merged into `args` for tools that take one), `session_key` (runs the tool in that session's context and agent), `idempotency_key`, `dry_run`. Errors have the typed shape `{"ok": false, "error", "code", "details"}`: `code` is a category (`INVALID_REQUEST`, `FORBIDDEN`, `NOT_FOUND`, …) and `details.code` the specific reason. | Status | Meaning | | --- | --- | | `200` `{"ok": true, "result": …}` | The tool ran. A tool that ran and failed answers `200` with `ok: false` and the tool's error class. | | `200` `{"dryRun": true, "allowed": …, "policy": {…}}` | `dry_run`: the resolved policy (profile, caller, sandboxed, read-only, may-require-approval); the tool did not run. The configured tool hooks' `before_tool` runs, so a hook's block shows as `allowed: false` (`errorClass: "ToolHookBlocked"`). | | `403` `FORBIDDEN` / `POLICY_DENIED` | The configured tool policy (`[tools]` profile/allow/deny, the agent's own entry) or a configured tool hook refuses it; `details.error_class` names the refusal (`ToolHookBlocked` for a hook). | | `403` `FORBIDDEN` / `APPROVAL_REQUIRED` | The tool needs a human approval. HTTP calls run unattended, so the tool refuses as on any unattended run; `details.approval_id` is included when it queued one. | | `400` `INVALID_REQUEST` | Bad body, an argument that writes a file (`output_path`, `save_path`, `output_file`, `destination`, …), refused for every tool, or arguments that do not match the tool's schema (`details.error_class = "ToolArgumentsRejected"`, the message names each failing argument). | | `404` `NOT_FOUND` | Unknown tool **or** one the endpoint does not run — the two look the same. | | `409` `INVALID_REQUEST` / `REQUEST_CONFLICT` | The `idempotency_key` was used for a different request in the last ten minutes (a repeat of the same request replays its first answer with `idempotentReplay: true`). | | `504` `UNAVAILABLE` / `TOOL_TIMEOUT` | The tool did not finish within the tool timeout. | **Tool hooks.** The call runs through the gateway's configured tool hooks, the same ones agent turns run, once per request. The policy is checked on the arguments as you sent them before any hook runs: a call it refuses is answered `403 POLICY_DENIED` and no hook sees it, even if a hook would have rewritten it. A call that passes then goes through the hooks: a hook's block is `403 POLICY_DENIED` with `details.error_class = "ToolHookBlocked"`, a rewrite is validated against the tool's schema and checked by the policy again before the tool runs, and an `after_tool` replacement is what `result` returns. With `dry_run: true` the hooks' `before_tool` runs first, as in a turn, so `allowed` reflects a hook's block. See [Tool and request hooks](https://useagentos.dev/docs/core/tools-and-sandbox#tool-and-request-hooks-python-api). The endpoint denies by default: it runs only tools whose registration declares them read-only (`read_file`, `list_dir`, `grep_search`, `web_search`, `web_fetch`, `memory_search`, `sessions_list`, …). Every other tool — anything that may write, send, spend or change state, every MCP tool, and anything registered later without the read-only flag — answers `404`. On top of that, a name floor holds even if a flag changes: shell, terminal and code execution, file writes, deletes and moves (including `memory`, memory and skill writes, document creation, `publish_artifact`, `env_set`, `http_request`), project and session renames, `sessions_spawn`, `sessions_send`, `subagents`, `acp`, `message`, `cron` and scheduler tools, `gateway`, `browser`, `router_control`, the paid media generators (`image_generate`, `tts`, `music_generate`, `song_generate`, `voice_clone`, `voice_convert`, `dubbing_*`), and any `trade*`/`trading*` tool. Lift a single tool with `[tools.invoke] allow = ["create_pdf_report"]` — in `agentos.toml` only: config RPC writes refuse to add an entry, and a connection the gateway recognizes as an agent's cannot touch the setting at all. Tools run sandboxed in an unattended context; an agent's connection (an agent token or an open exec window) is refused with `403`. ## Inbound webhooks External automation can reach the agent without a chat channel. These routes take their own bearer, `[hooks] token`, sent as `Authorization: Bearer <token>` or `X-AgentOS-Hook-Token`; the gateway token is refused there. Without a hooks token they answer `404`. | Method | Path | Body | Effect | | --- | --- | --- | --- | | `POST` | `/api/v1/hooks/agent` | `{message, agent?, session_key?}` | Enqueues `message` as a user message in `agent:<agent>:hook:agent`, or in `session_key` when it is under `agent:<agent>:hook:`. | | `POST` | `/api/v1/hooks/wake` | `{reason?}` | Asks the heartbeat to run now (`503` when there is none). | | `POST` | `/api/v1/hooks/<name>` | any JSON | Delivers to the agent and session of `[hooks.routes.<name>]`, message rendered from its `template`. | Delivery answers `202` with `sessionKey`. Per hook name: `429` past `rate_limit_per_minute` (default 60, with `Retry-After`); an `idempotency_key` in the body or an `Idempotency-Key` header replays the first answer for five minutes (`duplicate: true`), and the same key with a different body is `409` with `details.code = "REQUEST_CONFLICT"`; and `409` with `details.code = "FANOUT_LIMIT"` once the hook has delivered into `max_sessions_per_hook` (default 1) distinct sessions within the last hour. A malformed or wrong token is `401`, never an error page. Wrong tokens (the gateway token presented here included) count against `[auth.rate_limit]` like wrong gateway tokens, in a budget of their own: past it the address gets `429` with `details.code = "AUTH_RATE_LIMITED"` on the hooks, while the rest of the API is unaffected. Errors have the same typed shape as above. See [Configuration → Inbound webhooks](https://useagentos.dev/docs/core/configuration#inbound-webhooks) and [Scheduling → Automation](https://useagentos.dev/docs/core/scheduling#automation-from-outside). ## Streaming (WebSocket) For streaming turns and live events, connect to the WebSocket route: ```text ws://127.0.0.1:18791/ws ``` The WebSocket carries the same JSON-RPC methods the HTTP endpoints dispatch to, plus server-pushed events. It is one route on the same app — the REST surface above sits alongside it. See [MCP Server Bridge](https://useagentos.dev/docs/core/mcp-server) for a bridge that uses this transport. ### Handshake 1. The server sends `connect.challenge` with `{nonce, ts}` (`ts` in ms since the epoch). 2. The client answers with a `req` whose `method` is `connect` and whose `params` are `{minProtocol, maxProtocol, clientKind, client, auth?}`. The current protocol is `3`; send `minProtocol = maxProtocol = 3`. `client` is informational, `{id, version, platform, mode}`, every field optional. `auth.token` carries the gateway token. While the gateway is still booting, `connect` is answered with a retryable `UNAVAILABLE` (`details.code: "STARTUP_SIDECARS"`, `retry_after_ms`) and the socket closes `1013`; retry after `retry_after_ms`. 3. The server answers with a bare `hello-ok` frame (not a `res`) carrying `features.methods`, `features.events`, `features.capabilities` (additive feature names such as `typed-errors`, `challenge-ts`, `auth-rate-limit`, `rpc-http`, `supervisor-contract`; treat an unknown one as absent), `policy` and `auth.nonce` (the challenge nonce, so a client can check it answered its own challenge). Messages before `hello-ok` are capped at 64 KiB: a larger one (plain, fragmented or compressed) closes the socket with `1009` before it is read. After it the cap is `policy.max_payload` (25 MiB). One address may hold at most 128 sockets in the handshake; the next upgrade is refused with HTTP 403. Malformed frames answer `INVALID_REQUEST` with `details.code` `INVALID_FRAME` or `INVALID_CONNECT_PARAMS` and an `errors` list. A protocol range the server cannot meet answers `INVALID_REQUEST` with `details {code: "PROTOCOL_MISMATCH", client_min, client_max, server_min, server_max, reload_required}`; `reload_required` is true when the client is the older side (a stale web console bundle). ### Errors `error.code` is one of `INVALID_REQUEST`, `UNAUTHORIZED`, `FORBIDDEN`, `NOT_FOUND`, `METHOD_NOT_FOUND`, `UNAVAILABLE`, `RATE_LIMITED`, `INTERNAL_ERROR`, a long-standing code kept for existing clients (`QUEUE_FULL`, `GATEWAY_RESTARTING`, ...), or a namespaced domain code (`project.conflict`, `trading.operator_required`). The specific reason of a new error is in `details.code` (`PROTOCOL_MISMATCH`, `AUTH_RATE_LIMITED`, `REQUEST_START_TIMEOUT`, `QUEUE_FULL`, ...). `retryable: true` says trying again later can succeed. ### Concurrency and backpressure Up to four requests per connection run at once. Requests naming the same session (`sessionKey`, or `key` on `sessions.*`) run in order, and a request naming no session waits for every earlier one, so a client can still rely on `chat.send` before `sessions.abort` or `subscribe` before a history read. Session-less reads (`sessions.list`, `status`, `config.get`, `models.list`, `usage.*`, ...) wait only for earlier session-less writes, so a poll is not held back by another session's slow history. A request that cannot start within 30 seconds answers `UNAVAILABLE` with `details.code = "REQUEST_START_TIMEOUT"` (retryable). Event frames carry a per-connection `seq`. When more than `policy.max_buffered_bytes` (50 MiB) is waiting for a client that is not reading, periodic refreshes (`tick`, `presence`, `health`) are dropped and their `seq` still consumed, so the client sees a gap and resynchronizes; anything else closes the socket with `1008` `slow consumer`. Projects (session groups with shared knowledge) have no REST route of their own: `projects.create` / `projects.list` / `projects.get` / `projects.update` are RPC methods (WebSocket, or `POST /api/v1/rpc`), `projects.delete` is WebSocket-only (params use `projectId`, `agentId`, `name`, `knowledge`; delete responds with `sessionsCleared` — sessions are detached, not deleted). `projects.update` writes only the fields you pass and accepts an optional `expectedUpdatedAt` (the `updatedAt` you last read): when the row changed in between, the call fails with code `project.conflict` instead of silently overwriting the other writer's edit. `sessions.create` accepts an optional `projectId`, `sessions.patch` moves a session with `projectId` (explicit `null` detaches), and `sessions.list` accepts a `projectId` filter and emits `project_id`/`projectId` on every row. Its answer carries `count` (rows returned) and `total` (sessions matching the `projectId` filter regardless of `limit`; equal to `count` when the page is not full). `sessions.patch` and `sessions.rename` on an ephemeral WebChat key (`agent:<id>:webchat:<suffix>`) that has no row yet create it first — the WebUI mints that key client-side and only sends it on the first message; every other key shape still fails with `NOT_FOUND`. Project CRUD broadcasts a `projects.changed` event to connected clients. ### Run lifecycle `hello-ok.features.capabilities` names the behaviours below; check for a name before relying on it. - **`terminal-replay`** — every run ends with exactly one `session.event.done` or `session.event.error`, whichever path ends it (a normal end, a cancel, a crash, `sessions.abort`). The frame carries `state` (`done`, `error` or `aborted`) and `task_id`; an aborted one also carries `partial_text`. A run that failed always ends with `session.event.error`, even when it had already used tokens. A `done` frame also carries `outcome` (`{kind, reason, ...}`, with `kind` one of `completed`, `partial`, `budgetLimited`, `blocked`, `failed` or `interrupted`): the same record the task stores as `details.turn_outcome`. It is published after the task's terminal status is stored, before `task.<status>`. `task.*` and `sessions.changed` frames are kept in the session's replay buffer with a `stream_seq`, so `sessions.messages.subscribe {key, since_stream_seq}` replays them (with `meta.replayed: true`) to a client that reconnects late. Coding-agent and subagent child sessions get `sessions.changed` with their `run_status` too. - **`inflight-snapshot`** — `sessions.messages.subscribe` and `chat.history` (unless paging with `before`) return `in_flight_run`: `null` when nothing runs (drop any live view), or `{run_id, task_id, status, started_at, through_stream_seq, text, text_truncated?, plan?, events?}` for the running turn. It is capped at 256 KiB, filled in that order of priority; text is cut from the front. `through_stream_seq` is the stream position it covers. A run whose terminal frame (`done` / `error` / `task.*`) was already sent is never reported, even while its task is being settled. - **`sessions.questions {limit?}`** — the unanswered `ask_user` questions the most recently updated sessions end on (default 100 sessions, at most 500): `{questions: [{key, questions, toolUseId, askedAt}]}`. - **`mid-turn-steering`** — a `chat.send` / `sessions.send` with an explicit `queueMode: "steer"` while the session's turn runs joins that turn instead of cancelling it (without `queueMode` the session's default still replaces the running turn, as before). The turn takes one waiting message per checkpoint: before starting the next call of an ordered tool sequence (calls not started get a "skipped" tool result), after a tool batch (the message follows the tool results), and when the model would end the turn (it continues instead). The user row is written when the turn takes the message; until then it is not in the transcript. A message no checkpoint takes runs as the next turn. When the running turn does not check (a coding-harness turn, a turn still starting) `steer` still replaces it. A `noMemoryCapture` message steers too; the turn it joins then skips memory capture. The send answer carries `task_id` and the effective `queue_mode` (`steer`, `interrupt`, `followup`, `collect`); an explicit `steer` that fell back to interrupt also carries `steer_fallback`: `attachments` (a message with attachments always starts its own turn) or `no_steerable_turn` (nothing running takes steering messages). `chat.history` (unless paging with `before`) returns `pending_inputs`: the session's queued messages, oldest first, as `{task_id, queue_mode, text, text_truncated?, queued_at, attachments, steer, message_id?}`; `message_id` is set when the user row is already in the transcript (a follow-up), so a client does not show it twice. `chat.abort {sessionKey, taskId}` (and `sessions.abort {key, taskId}`) withdraws a queued message — `{withdrawn: true, aborted: [], removed_message_id?}`, the task ends `cancelled` / `withdrawn` — stops just that run when it is the running one, and answers `delivered: true` when a running turn already took it. When a turn takes the message it emits `session.event.steering {text, message_id, task_id}` and adds a `{"type": "steer", "message_id"}` segment to its row's `tool_calls`. `chat.history` cuts such an assistant message at each `steer` segment and moves the steered user message between the parts (work before, message, work after); the last part keeps the row's ids, usage and artifacts, earlier parts get `<message_id>#partN` ids and `split_from`. While the turn runs, its part up to the newest steer is listed and `in_flight_run.text` holds only the text after it. A `delta_cursor` read whose turn would move a steered message the client already has answers `kind: "reset"`. - **`idempotency-keys`** — `chat.send`, `sessions.send`, `sessions.create`, `cron.add`, `exec.approval.resolve` and `plugin.approval.resolve` accept an optional `idempotency_key`. The same key within five minutes returns the first answer; the same key with a different request fails with `INVALID_REQUEST` and `details.code: "REQUEST_CONFLICT"`. A `chat.send` / `sessions.send` key is also stored on the turn's task, so a retry after a gateway restart finds the turn instead of starting another. `sessions.abort` stops the session's run and every child run it spawned (coding-agent and subagent sessions, any depth), withdraws the approval prompts they were waiting on, waits up to 10 s for them to end, and answers `{aborted: [<run ids>], children_aborted: [<session keys>], key}`. If some are still running after that, it fails with `UNAVAILABLE` and `details: {code: "ABORT_INCOMPLETE", still_running: [...]}`. It waits in its session's lane, so other sessions' requests on the same socket go ahead; the runs it stops are the ones active when it started. A second `sessions.abort` / `chat.abort` for the same session, sent on the same socket while the first is still waiting, does not queue behind it: it starts at once, cancels the turn without waiting out `turn_cancel_grace_seconds`, and both answer with the stopped run ids. Requests sent after the stops still wait for both. A session's `stream_seq` keeps counting for as long as the session exists (a follow-up turn on a finished child continues it); it restarts only with the gateway, which a subscribe answer shows as a `current_stream_seq` below the client's cursor or `replay_gap_reason: "cursor_ahead_of_stream"`. `chat.history` answers stay under 6 MiB. A message over 128 KiB arrives as a placeholder (`placeholder: true`, `byte_size`, `entry_id`, the tool calls' identity, a short text preview); `chat.entry {sessionKey, entryId}` returns the full row (over 20 MiB it answers `INVALID_REQUEST` with `PAYLOAD_TOO_LARGE`). `delta_cursor` (a `newest_cursor` from an earlier answer) returns only the rows after it (`kind: "delta"`, at most 200 rows / 1 MiB, `has_more` when there are more), or `kind: "reset"` with the latest page when the cursor no longer names a row. Assistant text, in history and in `text_delta` frames, is display-ready: reply directives, generated-artifact markers and leaked tool-protocol text are removed by the gateway. ### Environment variables (`env.*`) Control-surface only. Values never appear in a listing. | Method | Purpose | | --- | --- | | `env.list` | Every known variable: name, set/unset, source, description, owner, and a **masked** value. | | `env.set` | Write one variable. Returns its new state without echoing the value. | | `env.unset` | Remove one variable from `~/.agentos/.env`. | | `env.reveal` | Return one real value. Rate limited to 5 per 30s and written to the audit log. | Writes are refused for names that steer subprocess execution or AgentOS runtime posture; see [Configuration](https://useagentos.dev/docs/core/configuration#what-cannot-be-written-through-agentos). `env.set` and `env.unset` report `restartRequired` per variable — provider clients are built at boot with the key they had then, while other variables are picked up by the next process AgentOS spawns. ## Example On the default loopback bind these work as-is, no token needed: ```sh # Liveness curl http://127.0.0.1:18791/health # System status curl http://127.0.0.1:18791/api/system/status # Send a chat turn (message is required; sessionKey is optional) curl -X POST \ -H "Content-Type: application/json" \ -d '{"sessionKey": "agent:main:webchat:default", "message": "hello"}' \ http://127.0.0.1:18791/api/chat ``` When the gateway runs with `auth.mode = "token"` (any public bind), add the token to each `/api/*` call: ```sh curl -H "Authorization: Bearer $AGENTOS_TOKEN" \ https://gateway.example.com/api/system/status ``` ## Source The full route table is defined in `create_gateway_app`: [`src/agentos/gateway/app.py`](../src/agentos/gateway/app.py) (the `routes` list). File-and-media routes are registered just below it via `register_upload_routes`, `register_attachment_routes`, `register_artifact_routes`, `register_download_routes` and `register_audio_transcription_routes`; then `register_inbound_hook_routes` and `register_tools_invoke_route`. Read next: - [Gateway](https://useagentos.dev/docs/core/gateway) - [MCP Server Bridge](https://useagentos.dev/docs/core/mcp-server) - [Web UI](https://useagentos.dev/docs/core/web-ui) --- # Remote Access > Source: https://useagentos.dev/docs/core/remote-access The gateway controls chat, tools, sessions, channels, approvals and configuration, all with your provider credentials. It therefore listens on loopback (`127.0.0.1:18791`) by default, and the safest way to reach it from another machine is to keep it there and bring the connection to it. Use this page when you want the Web UI, the desktop app, the CLI or an MCP client on one machine to drive a gateway running on another. For a gateway in a container, follow [Run the gateway in a container](https://useagentos.dev/docs/core/container-gateway): the steps start from the published image and differ in a few places. ## Pick a Path | Path | Gateway bind | Who authenticates | Good for | | --- | --- | --- | --- | | [SSH tunnel](#ssh-tunnel) | loopback | your SSH key | any host you can SSH into; nothing to install | | [Tailscale Serve](#tailscale-serve) | loopback | your tailnet identity, plus the gateway token | your own devices, from anywhere, over HTTPS | | [Reverse proxy](#reverse-proxy-with-trusted-proxy-mode) | loopback or LAN | the proxy (SSO, mTLS, basic auth) | a team entry point you already run | | [Token on a LAN bind](#token-on-a-lan-or-public-bind) | `0.0.0.0` or a LAN IP | the gateway token | a trusted home or lab network | Whatever you choose, run `agentos doctor` afterwards: it reports the risky combinations (`gateway.bind_no_auth`, `gateway.allowed_origins_wildcard`, `gateway.cors_wildcard_with_credentials`, `gateway.trusted_proxy_unset`, `gateway.auth_rate_limit_off`, `gateway.rate_limit_loopback_exempt_behind_proxy`, `gateway.token_short`) with the command that fixes each. It finds the token on its own (`AGENTOS_GATEWAY_TOKEN`, then `auth.token` in the config, or `--token`), and when no gateway answers it checks the config file instead. ## Writing the Config Every recipe below changes settings in the gateway's config file. Use `agentos config set <key> <value> --config <file>`: **without `--config` the command only prints an `export AGENTOS_GATEWAY_…` line and changes nothing** for a gateway started anywhere else. The examples write `~/.agentos/config.toml`, the file a gateway reads by default (under `AGENTOS_STATE_DIR` when that is set); if your gateway was started with `--config <file>` or from a directory with an `agentos.toml`, use that file instead (`agentos doctor` names it). Editing the TOML by hand works just as well. The gateway reads the file at startup, so restart it afterwards: ```sh agentos gateway restart ``` Configure authentication **before** you expose the gateway, never after: until the restart the old settings are live. ## SSH Tunnel The universal path. The gateway stays on loopback on the remote host; SSH forwards a local port to it: ```sh ssh -N -L 18791:127.0.0.1:18791 user@host ``` Then use the gateway as if it were local: ```text http://127.0.0.1:18791/control/ ``` ```sh agentos gateway status --gateway ws://127.0.0.1:18791/ws ``` `-N` opens no shell; leave the command running for as long as you need the tunnel. To keep it up across drops, use your SSH client's keep-alive options or a tool such as `autossh`. If port 18791 is taken locally, forward another one (`-L 18800:127.0.0.1:18791`) and open `http://127.0.0.1:18800/control/`. No AgentOS configuration changes: to the gateway the browser is a loopback peer, so the default `auth.mode = "none"` keeps working. Set a token anyway if other people have accounts on the remote host. The desktop app works through the tunnel as well: Settings › Gateway › Connection, **Run mode** External, **Protocol** HTTP, host `127.0.0.1`, port `18791` (or the local port you forwarded), plus the token if one is set. See [Desktop app → Using a gateway on another machine](https://useagentos.dev/docs/core/desktop-app#using-a-gateway-on-another-machine). ## Tailscale Serve [Tailscale Serve](https://tailscale.com/kb/1312/serve) publishes a loopback service to your tailnet over HTTPS with a `*.ts.net` certificate. The gateway keeps its loopback bind. Serve connects to it from loopback, so the gateway must enforce a token first; without one every device on your tailnet would be admitted as if it sat at the keyboard. 1. Enforce a token, allow the tailnet origin, and let the rate limiter see the real client. On a loopback bind the gateway accepts browser requests only from loopback origins (the guard against cross-site WebSocket hijacking and DNS rebinding), so the Serve origin must be listed. Serve adds `X-Forwarded-For`; trusting it as a local proxy makes failed-token lockouts apply per tailnet device instead of exempting everything that arrives from 127.0.0.1: ```sh CFG=~/.agentos/config.toml agentos config set auth.mode token --config "$CFG" agentos config set auth.token "$(python3 -c 'import secrets; print(secrets.token_hex(32))')" --config "$CFG" agentos config set control_ui.allowed_origins '["https://<machine>.<tailnet>.ts.net"]' --config "$CFG" agentos config set auth.trusted_proxy 127.0.0.1 --config "$CFG" agentos gateway restart ``` Check it took effect before going further: `agentos doctor` must not report `gateway.rate_limit_loopback_exempt_behind_proxy`, and `curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:18791/api/sessions` must print `401`. 2. Only now publish it: ```sh tailscale serve --bg --https=443 http://127.0.0.1:18791 ``` Open `https://<machine>.<tailnet>.ts.net/control/`, enter the token on the Connect screen (or in Settings › Gateway) and press Connect. The desktop app connects the same way: **Run mode** External, **Protocol** HTTPS, host `<machine>.<tailnet>.ts.net`, port `443`, and the token. The same settings reach a gateway behind a [reverse proxy](#reverse-proxy-with-trusted-proxy-mode), with that proxy's hostname; whichever path you take, the origin the app presents is the gateway's own, so it must be declared on the gateway as above (`control_ui.allowed_origins` or `[gateway] public_origin`). `tailscale serve status` shows what is published; `tailscale serve --https=443 off` takes it down. Do not use Tailscale **Funnel** for the gateway: it publishes the port to the whole internet. If you would rather not trust the proxy's header, lock out loopback too instead (`agentos config set auth.rate_limit.exempt_loopback false --config "$CFG"`); a local script with a stale token is then locked out like anyone else. ## Reverse Proxy with Trusted-Proxy Mode When a reverse proxy already authenticates your users (SSO, mTLS, basic auth), let it be the only thing that can reach the gateway and tell the gateway to trust it: ```toml host = "127.0.0.1" # or the interface the proxy connects from [auth] mode = "trusted-proxy" trusted_proxy = "127.0.0.1" # IPs or CIDR blocks, comma-separated [control_ui] allowed_origins = ["https://agent.example.com"] ``` Write those keys with `agentos config set … --config <file>` or edit the file, then restart. In this mode a request is admitted only when the *transport peer* (the address the TCP connection comes from, never a header) is listed in `auth.trusted_proxy`. Anything else gets `401`. The mode is accepted on a non-loopback bind for that reason; with an empty `trusted_proxy` nothing is admitted and `doctor` reports `gateway.trusted_proxy_unset`. The proxy must forward WebSocket upgrades on `/ws` and should append the client address to `X-Forwarded-For`. The origin you list in `control_ui.allowed_origins` (or `[gateway] public_origin`) is also the hostname the gateway answers to: a request whose `Host` names anything else gets `400` (the DNS-rebinding guard), so a proxy that forwards the public `Host` needs that origin declared. The gateway reads that header only from a trusted peer and walks it right to left, skipping trusted hops, so the first address your proxies did not add is the client used for rate limiting. An address that names the gateway host itself (loopback or one of its own interfaces) is treated as spoofed and ignored. List every proxy hop, for example `trusted_proxy = "10.0.0.0/8"` behind a load balancer. `agentos gateway run` turns uvicorn's own proxy-header handling off, so the `FORWARDED_ALLOW_IPS` environment variable has no effect: `X-Forwarded-For` never changes which peer admission sees. If the proxy instead forwards to a gateway in `token` mode on the same host, set `auth.trusted_proxy` to the proxy's address anyway: otherwise every client it forwards looks like a loopback peer, and loopback is exempt from the failed-token lockout (`doctor` reports `gateway.rate_limit_loopback_exempt_behind_proxy`). A minimal Caddy site: ```text agent.example.com { forward_auth ... # your authentication reverse_proxy 127.0.0.1:18791 } ``` A minimal nginx location: ```nginx location / { proxy_pass http://127.0.0.1:18791; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } ``` ## Token on a LAN or Public Bind Binding beyond loopback requires an enforced auth mode; the gateway refuses to start with `auth.mode = "none"` on `0.0.0.0` or a LAN address. Set the mode in the file first, then start on the wider bind: ```sh agentos config set auth.mode token --config ~/.agentos/config.toml agentos gateway run --bind-mode lan # same as --listen 0.0.0.0 ``` `--bind-mode tailnet` listens on the machine's `tailscale ip -4` address and on `127.0.0.1` only, and refuses to start when Tailscale is not up instead of falling back to every interface. Browsers are admitted from the address you opened the console at when it is a private one (`http://192.168.1.20:18791`), from the gateway's own localhost, and from declared origins; anything else is refused before auth. To open it under a DNS name, declare that origin: `agentos config set gateway.public_origin https://agent.example.com --config ~/.agentos/config.toml`. See [Gateway → Browser origins](https://useagentos.dev/docs/core/gateway#browser-origins). A token is generated at startup when none is set. Clients send it as `Authorization: Bearer <token>` (HTTP) or in the WebSocket `connect` request; it is never accepted in a query string. Wrong tokens are throttled per client address: ten failures in a minute lock that address out for five minutes (`429` with `Retry-After` over HTTP, `AUTH_RATE_LIMITED` over the WebSocket), whatever `Origin` header the attempts carry. Tune it under `[auth.rate_limit]`; keep it on for any non-loopback bind. An address that already holds 128 sockets in the handshake gets `HTTP 403` for the next one until some of them finish. Only do this on a network you trust. The traffic is plain HTTP unless you also set `[tls] certfile` and `keyfile`. ## Rotating the Token Generate a new token, restart, then update every client: ```sh agentos config set auth.token "$(python3 -c 'import secrets; print(secrets.token_hex(32))')" --config ~/.agentos/config.toml agentos gateway restart ``` Use at least 24 random characters (`doctor` warns below that as `gateway.token_short`). Clients holding the old token start getting `UNAUTHORIZED`, and repeated attempts count against the failed-auth limit, so update scripts and the desktop app's gateway settings promptly. ## What Never to Do - Do not bind `0.0.0.0` with `auth.mode = "none"`. The startup guard refuses it; do not work around the guard. - Do not forward the gateway port to the internet from your router, or publish it with a public tunnel, without an authenticating proxy in front. - Do not put `"*"` in `control_ui.allowed_origins`, and do not combine `cors.allowed_origins = ["*"]` with `cors.allow_credentials = true` on a non-loopback bind. - Do not use `trusted-proxy` mode unless the listed addresses really are your proxies, and the gateway port is reachable only through them. - Do not put the token in a URL; use the header. Read next: - [Gateway](https://useagentos.dev/docs/core/gateway) - [HTTP API](https://useagentos.dev/docs/core/http-api) - [Configuration](https://useagentos.dev/docs/core/configuration) - [Troubleshooting](https://useagentos.dev/docs/core/troubleshooting) --- # Run the Gateway in a Container > Source: https://useagentos.dev/docs/core/container-gateway Run the AgentOS gateway from the published container image on a server, a VPS or a home box, then use it from the [desktop app](https://useagentos.dev/docs/core/desktop-app), the [Web UI](https://useagentos.dev/docs/core/web-ui) or the [CLI](https://useagentos.dev/docs/core/cli) on your own machine. Use this page when the gateway should keep running while your laptop is closed: channels and scheduled jobs stay up, and sessions, memory, provider keys and wallets live on the server. If you only want AgentOS on one Mac, the desktop app runs a gateway for you and you do not need any of this. The setup has four steps: start the container, give it a provider, choose how your machine reaches it, and point the desktop app at it. ## Before You Start - A Linux host (`amd64` or `arm64`) with Docker Engine and Compose v2. Check with `docker compose version`. - About 1.4 GB of disk for the image, plus room for your state. The gateway idles around 200 to 250 MiB of memory and uses more during turns. - An API key for an LLM provider. - SSH access to the host. The first connection below uses nothing else. ## 1. Start the Gateway Create a directory for the deployment and download the Compose file: ```sh mkdir -p ~/agentos && cd ~/agentos curl -fsSLO https://raw.githubusercontent.com/use-agent-os/agent-os/main/compose.yaml ``` Create a `.env` next to it with the image and a fresh token: ```sh umask 077 cat > .env <<EOF AGENTOS_GATEWAY_IMAGE=ghcr.io/use-agent-os/agent-os:latest AGENTOS_AUTH_TOKEN=$(openssl rand -hex 32) EOF ``` Start it and check that it answers: ```sh docker compose up -d docker compose ps curl -s http://127.0.0.1:18791/ready ``` `/ready` answers with `"state":"ready"` within a few seconds. `docker compose ps` reports `healthy` after the first health check, about 30 seconds in. Clients need the token, so note where it lives: `grep AGENTOS_AUTH_TOKEN .env`. Two things are worth knowing about this setup: - **The gateway is not on the network yet.** Inside the container it binds `0.0.0.0`, because Docker port publishing needs that, but Compose publishes the port on the host's `127.0.0.1` only. Step 3 decides who else can reach it. - **The token is required.** The gateway refuses to serve a wildcard bind without enforced auth, so `compose.yaml` turns token auth on and will not start without `AGENTOS_AUTH_TOKEN`. Replace `latest` with a release version (`ghcr.io/use-agent-os/agent-os:2026.11.12.post1`) to choose when you upgrade. See [Upgrade](#upgrade). ## 2. Configure a Provider A new gateway has no provider, so `agentos doctor` reports `Active provider is not configured` until you set one. Pick whichever of these suits you. **OpenRouter, from `.env`.** Add the key and recreate the container: ```sh echo 'OPENROUTER_API_KEY=YOUR_API_KEY' >> .env docker compose up -d ``` `compose.yaml` forwards only `OPENROUTER_API_KEY` and `BRAVE_SEARCH_API_KEY` from `.env`. Any other name you add there stays out of the container unless you also add it to the `environment:` block. **Any provider, with the CLI in the container.** Store the key at a hidden prompt, which keeps it out of your shell history, then select the provider: ```sh docker compose exec gateway agentos env set OPENAI_API_KEY docker compose exec gateway agentos configure provider --provider openai --api-key-env OPENAI_API_KEY --model YOUR_MODEL docker compose exec gateway agentos gateway restart ``` Run `docker compose exec gateway agentos providers list` to see the provider names. **From the desktop app or the Web UI**, once you have connected in step 4: Settings › Providers works as it does locally. Restart the gateway on its host afterwards if the pane asks for it. Provider settings and stored keys persist on the volume. Check the result: ```sh docker compose exec gateway agentos doctor ``` The first line should start with `AgentOS Doctor - Ready`. ## 3. Choose How to Reach It | Path | Who can reach the gateway | What you change | Good for | | --- | --- | --- | --- | | [SSH tunnel](#ssh-tunnel) | anyone with your SSH key | nothing | getting started; any host | | [Tailscale Serve](#tailscale-serve) | your tailnet, plus the token | one command on the host | your own devices, from anywhere | | [HTTPS reverse proxy](#https-reverse-proxy) | the internet, plus the token | a Compose override and a DNS name | a stable address, phones, teammates | | [LAN port](#lan-port) | your network, plus the token | the `ports:` line | a trusted home or lab network | Start with the SSH tunnel. It proves the whole chain with no exposure, and you can move to another path later without touching your data. ### SSH Tunnel Run this on your own machine and leave it running: ```sh ssh -N -L 18791:127.0.0.1:18791 user@your-server ``` The gateway now answers on `http://127.0.0.1:18791` on your machine. If that port is taken locally, forward another one (`-L 18800:127.0.0.1:18791`) and use it in the next step. To survive network drops, use your SSH client's keep-alive options or `autossh`. ### Tailscale Serve With Tailscale installed on the host, publish the loopback port to your tailnet: ```sh tailscale serve --bg --https=443 http://127.0.0.1:18791 ``` The gateway accepts `*.ts.net` names without further configuration. Do not use Tailscale **Funnel**, which publishes the port to the whole internet. ### HTTPS Reverse Proxy Point a DNS name at the host and open ports 80 and 443. Next to `compose.yaml`, create a `compose.override.yaml`, which Compose merges in automatically. This one adds [Caddy](https://caddyserver.com/), which obtains and renews the certificate on its own: ```yaml services: gateway: environment: AGENTOS_GATEWAY_GATEWAY__PUBLIC_ORIGIN: https://agent.example.com AGENTOS_AUTH_TRUSTED_PROXY: 172.30.0.0/24 caddy: image: caddy:2 command: caddy reverse-proxy --from agent.example.com --to gateway:18791 ports: - "80:80" - "443:443" volumes: - caddy-data:/data restart: unless-stopped networks: default: ipam: config: - subnet: 172.30.0.0/24 volumes: caddy-data: ``` Replace `agent.example.com` in both places, then recreate the stack. The network settings changed, so take it down first. Leave off `-v`, which would delete your data: ```sh docker compose down docker compose up -d ``` Check it from your own machine. The first command should print `200`, and the second `401`, which proves the token is enforced: ```sh curl -s -o /dev/null -w '%{http_code}\n' https://agent.example.com/healthz curl -s -o /dev/null -w '%{http_code}\n' https://agent.example.com/api/sessions ``` What the two settings do: - `AGENTOS_GATEWAY_GATEWAY__PUBLIC_ORIGIN` declares the address clients use. The gateway refuses any hostname it does not know (`400`) and any browser or app origin it does not know (`403`). It must match exactly, so a proxy on a port other than 443 needs that port in the origin as well. - `AGENTOS_AUTH_TRUSTED_PROXY` lets the gateway read the real client address from `X-Forwarded-For`. Without it every client looks like the proxy, so ten wrong tokens from anyone lock everyone out for five minutes. The fixed subnet is what makes this setting possible; choose another one if `172.30.0.0/24` is in use on your host. Already running a proxy? Send it to `127.0.0.1:18791` or attach it to the same Docker network, and keep the two settings above, with the subnet the proxy connects from. It must forward WebSocket upgrades on `/ws` and pass the public `Host` header. A health probe has to send that `Host` too, or it gets `400` and the proxy marks the gateway down. See [Remote access](https://useagentos.dev/docs/core/remote-access#reverse-proxy-with-trusted-proxy-mode). ### LAN Port To publish the port on your network, edit the `ports:` line in `compose.yaml`: ```yaml ports: - "192.168.1.20:18791:18791" ``` Then run `docker compose up -d`. Traffic, including the token, is plain HTTP, so do this only on a network you trust, and never on a public IP: use the reverse proxy for that. Private addresses work with no other configuration. Docker's published ports also bypass host firewalls such as `ufw`, so do not count on those to restrict the port. ## 4. Connect the Desktop App In the app, open Settings › Gateway › Connection. On a first launch you can get there from the setup screen with **Connect to an existing gateway instead**, with no engine install. Set **Run mode** to **External**, fill in the values for your path, and press **Save**: | Path | Protocol | Host | Port | | --- | --- | --- | --- | | SSH tunnel | HTTP | `127.0.0.1` | `18791` (or the local port you forwarded) | | Tailscale Serve | HTTPS | `your-machine.your-tailnet.ts.net` | `443` | | HTTPS reverse proxy | HTTPS | `agent.example.com` | `443` | | LAN port | HTTP | `192.168.1.20` | `18791` | **Auth token** is the value of `AGENTOS_AUTH_TOKEN` from your `.env`, on every path. The light in the sidebar footer and the Process row in Settings › Gateway show whether the gateway is reachable. Send a message to confirm that the provider works too. What changes once the app is on an external gateway: - **The container owns the data.** Sessions, memory, skills and wallets are the gateway's, on the server. Nothing in the app's local `~/.agentos` moves over or is deleted; switching back to **Managed** brings it back. - **The app no longer runs the gateway.** It stops a gateway it had been running for itself. It cannot start or stop this one, and offers **Retry connection** when the gateway is unreachable. - **Updates are separate.** The app still updates itself. For the gateway, the toolbar shows **Gateway outdated** when a newer release exists, and you [upgrade it on the host](#upgrade). - **Wallets work.** A connection that authenticates with the gateway token from another machine counts as the operator, so you can create, import and unlock wallets and approve orders from the app. See [Trading](https://useagentos.dev/docs/core/features/trading). Anyone holding the token can do the same, so guard it like a wallet password. More on this mode is in [Desktop app](https://useagentos.dev/docs/core/desktop-app#using-a-gateway-on-another-machine). ### Web UI and CLI The same address and token work for the other clients. Open the Web UI at the gateway's address (`http://127.0.0.1:18791/control/` through the tunnel) and enter the token on the Connect screen (or in Settings › Gateway). For the CLI on your own machine: ```sh export AGENTOS_GATEWAY_TOKEN=YOUR_TOKEN agentos gateway status --gateway ws://127.0.0.1:18791/ws ``` Use `wss://agent.example.com/ws` behind HTTPS. ## Day-to-Day Operations Run these on the host, from the directory that holds `compose.yaml`. | Task | Command | | --- | --- | | Follow the logs | `docker compose logs -f gateway` | | Check health | `docker compose exec gateway agentos doctor` | | Restart, letting turns finish | `docker compose exec gateway agentos gateway restart` | | Run any CLI command | `docker compose exec gateway agentos ...` | | Stop, keeping your data | `docker compose stop` | ### Changing Settings `.env` and `compose.yaml` are read when the container is created, so changes there need `docker compose up -d`. `docker compose restart` keeps the old values, which is a common surprise after rotating a token. Settings in the gateway's own config file persist on the volume. Name the file explicitly, because `agentos config set` without `--config` only prints an `export` line and changes nothing: ```sh docker compose exec gateway agentos config set gateway.public_origin https://agent.example.com --config /var/lib/agentos/config.toml docker compose exec gateway agentos gateway restart ``` ### Rotating the Token Put a new value in `.env`, recreate the container, and update every client, including the desktop app's **Auth token**: ```sh sed -i "s/^AGENTOS_AUTH_TOKEN=.*/AGENTOS_AUTH_TOKEN=$(openssl rand -hex 32)/" .env docker compose up -d ``` ### Upgrade Do not run `agentos upgrade` in the container: the next recreate would throw that away. Replace the image instead. Point `AGENTOS_GATEWAY_IMAGE` in `.env` at the new release if you pinned one, then: ```sh docker compose pull docker compose up -d ``` State on the volume carries over. Docker gives a stopping container 10 seconds by default, which can cut off turns still running; they are [resumed on the next boot](https://useagentos.dev/docs/core/gateway#interrupted-turns) where that is safe. To give them the full drain window, add this to `compose.override.yaml`: ```yaml services: gateway: stop_grace_period: 60s ``` Take a backup before a large version jump. A newer gateway may migrate the database, so restoring the backup is the reliable way back to an older release. ### Back Up and Restore Everything except one key lives in the named volume mounted at `/var/lib/agentos`: config, the database, sessions, memory, the workspace, logs, wallets and the home directory with any tools you installed. The second volume, `agentos-vault-keys`, holds only the key that seals the wallet vault's auto-unlock password, and is deliberately left out of the archive. Stop the gateway so the database is consistent, then archive the state volume: ```sh docker compose stop gateway docker compose run --rm --no-deps -u root -v "$PWD:/backup" --entrypoint sh gateway -c 'umask 077; tar czf /backup/agentos-state.tgz -C /var/lib/agentos .' docker compose start gateway ``` The archive holds provider keys and encrypted wallets, so store it accordingly. Keep your wallet password separately: the archive does not open the wallets on its own, and after a restore onto a new host the vault stays locked until you unlock it once with the password (`agentos wallet unlock`), which also turns auto unlock back on. A wallet password you no longer have cannot be recovered from the archive, so export each wallet's keystore or keep the password where you will find it. A container started without the second volume and without `AGENTOS_VAULT_KEK_DIR` (an older `compose.yaml`, a plain `docker run`) keeps that key under the home directory inside the state volume. Auto unlock works the same, but an archive of that volume then carries the sealed password and its key together and opens the wallets by itself; treat it like the wallet password. Adopting the two-volume layout needs nothing else: the gateway finds the old key at the next start, seals the password again under a key on the new volume and deletes the old one. To restore, on a new host or into an empty volume: ```sh docker compose run --rm --no-deps -u root -v "$PWD:/backup:ro" --entrypoint sh gateway -c 'tar xzf /backup/agentos-state.tgz -C /var/lib/agentos' docker compose up -d ``` `docker compose down` keeps the volumes. `docker compose down -v` deletes them, along with any wallets inside that you have not backed up. ## What Is in the Image The image runs as the non-root user `agentos` (uid `10001`), and holds the gateway, the Web UI, the bundled router and embedding models, and the tools most agent work reaches for: Python, a C toolchain, Node.js with `npm` and `npx`, `uv`, `git`, `gh`, `curl`, `jq`, `ripgrep` and `tmux`. **Anything else that installs without root goes on the volume.** The user's home is `/var/lib/agentos/home`, so a tool installed with `npm install -g` or `uv tool install`, and the login or config it keeps in its home directory, survives an upgrade. Skills offer these installs from Settings › Skills. To install one yourself: ```sh docker compose exec gateway npm install -g gmgn-cli docker compose exec gateway agentos gateway restart ``` The restart is what makes the agent's prompt list a newly installed tool. These tools count towards your backup, and they are yours to update: replacing the image does not touch them. The image does **not** include `ffmpeg`, LibreOffice, Chromium or bubblewrap, which has consequences: - **No operating-system sandbox.** With bubblewrap missing, the container itself is the boundary around the agent's shell and file tools. Check your posture with `docker compose exec gateway agentos sandbox status`, and read [Tools and sandbox](https://useagentos.dev/docs/core/tools-and-sandbox). Do not mount the Docker socket or host directories you would not hand to the agent. A bind-mounted directory must be writable by uid `10001`. - **Skills that need `ffmpeg` or LibreOffice stay unavailable.** They need system packages, which only a custom image can add. - **The `browser` tool stays hidden.** See [Browser](https://useagentos.dev/docs/core/features/browser). To add what needs root, build on the published image and point `AGENTOS_GATEWAY_IMAGE` at the result: ```dockerfile FROM ghcr.io/use-agent-os/agent-os:latest USER root RUN apt-get update && apt-get install -y --no-install-recommends ffmpeg && rm -rf /var/lib/apt/lists/* USER agentos ``` ```sh docker build -t agentos-custom:local . ``` You can also build the base image from a source checkout with `docker build -t agentos:local .`, after `git lfs pull` fetches the model files. See [Install from source](https://github.com/use-agent-os/agent-os#install-from-source). ## Troubleshooting | Symptom | Cause | Fix | | --- | --- | --- | | Compose stops with an error naming `AGENTOS_AUTH_TOKEN` | no `.env`, or you are in another directory | run from the directory holding `.env`, and set the token | | Container restarts forever; logs say `Refusing to serve: auth.mode='none'` | a wildcard bind without auth, usually an older or custom Compose file | set `AGENTOS_AUTH_MODE: token` and `AGENTOS_AUTH_TOKEN` in `environment:` | | `port is already allocated` | something else holds 18791 on the host | publish another host port, such as `127.0.0.1:18800:18791`, and use it in your clients | | `401` or `UNAUTHORIZED` | the client's token differs from the running one | compare with `.env`; after editing `.env`, run `docker compose up -d` | | `429` or `AUTH_RATE_LIMITED` | ten wrong tokens in a minute locked the address for five minutes | fix the token and wait; behind a proxy, set `AGENTOS_AUTH_TRUSTED_PROXY` so one client cannot lock out the rest | | `400`, `Rejected Host header` | the gateway does not know that hostname | declare it with `AGENTOS_GATEWAY_GATEWAY__PUBLIC_ORIGIN`; make proxy health probes send the public `Host` | | App stays disconnected, WebSocket gets `403` | the origin is not declared, or its port differs | make the public origin match the app's Protocol, Host and Port exactly | | Proxy reaches `/healthz`, chat never connects | WebSocket upgrades are not forwarded | forward `Upgrade` and `Connection` on `/ws` | | `doctor` reports `Active provider is not configured` | no key reached the gateway | [configure a provider](#2-configure-a-provider) and restart | | A key in `.env` has no effect | `compose.yaml` forwards only the names it lists | add it to `environment:`, or store it with `agentos env set` in the container | | Provider or channel change has not applied | those settings load at startup | `docker compose exec gateway agentos gateway restart` | For anything else, start with `docker compose logs --tail 100 gateway` and `docker compose exec gateway agentos doctor`, then see [Troubleshooting](https://useagentos.dev/docs/core/troubleshooting). Read next: - [Remote Access](https://useagentos.dev/docs/core/remote-access) - [Desktop App (macOS)](https://useagentos.dev/docs/core/desktop-app) - [Gateway](https://useagentos.dev/docs/core/gateway) - [Configuration](https://useagentos.dev/docs/core/configuration) --- # MCP Client Guide > Source: https://useagentos.dev/docs/core/mcp AgentOS connects to external [Model Context Protocol](https://modelcontextprotocol.io) servers and offers their tools to the agent. This page is about that *client* side. To expose AgentOS itself to other MCP clients, see [MCP Server Bridge](https://useagentos.dev/docs/core/mcp-server). ## Quick start ```sh # A local stdio server, only its read tools agentos mcp add fs --command npx \ --arg -y --arg @modelcontextprotocol/server-filesystem --arg /srv/data \ --include 'read_*,list_*' # Check it before the gateway uses it agentos mcp doctor fs --probe # Apply agentos gateway restart ``` Or use **Settings › MCP** in the Web UI, which also handles OAuth sign-in for Streamable HTTP servers. ## Configuration Servers live in `[[mcp.servers]]` in the active config file. The client as a whole is switched by `mcp.enabled`; `agentos mcp add` turns it on when it adds the first server (an explicit `mcp.enabled = false` next to existing servers is left alone). ```toml [mcp] enabled = true connect_timeout_seconds = 5.0 # default for every server defer_tool_threshold = 8 # defer_loading = "auto": per-server limit defer_total_tool_threshold = 20 # ... and the limit across all servers instructions_max_chars = 2000 # server text quoted in the system prompt [[mcp.servers]] name = "fs" transport = "stdio" # stdio | sse | streamable_http command = "npx" args = ["-y", "@modelcontextprotocol/server-filesystem", "/srv/data"] cwd = "/srv" # stdio only env = { LOG_LEVEL = "warn" } # stdio only; merged over the gateway's env enabled = true connect_timeout_seconds = 20.0 # overrides [mcp].connect_timeout_seconds tool_timeout_seconds = 30.0 # per tool call tool_filter.include = ["read_*", "list_*"] tool_filter.exclude = ["read_secret"] defer_loading = "auto" # "auto" | true | false [[mcp.servers]] name = "docs" transport = "streamable_http" url = "https://mcp.example.com/mcp" headers = { "X-Team" = "platform" } oauth = false ``` | Key | Transports | Default | Notes | |---|---|---|---| | `name` | all | — | Unique; used in `mcp.status`, the CLI, and long tool names. | | `enabled` | all | `true` | `false` keeps the definition but never connects it. | | `transport` | — | `stdio` | `stdio`, `sse` (legacy), or `streamable_http`. | | `command`, `args` | stdio | — | The server process. Resolved on the gateway's `PATH` (or the `PATH` in `env`). | | `cwd` | stdio | gateway's | Working directory; `~` expands; must exist. | | `env` | stdio | `{}` | Extra environment. Skill signing keys are never passed on. | | `url`, `headers` | sse, streamable_http | — | `http(s)://` only, through the SSRF guard. | | `oauth` | streamable_http | `false` | Sign in from Settings › MCP. | | `connect_timeout_seconds` | all | global | Time allowed to connect and list tools. | | `tool_timeout_seconds` | all | `30` | Per tool call. | | `tool_filter.include` / `.exclude` | all | `[]` | See below. | | `defer_loading` | all | `"auto"` | Keep this server's tool schemas behind `tool_search`. See [Deferred tools](#deferred-tools). | All of these keys are optional, and configs written before they existed keep working unchanged. `agentos migrate openclaw` carries OpenClaw's `enabled`, `cwd`, `connectionTimeoutMs` and `toolFilter` over. ### Tool filters `tool_filter.include` and `tool_filter.exclude` are lists of `fnmatch` globs (`*`, `?`, `[abc]`) matched case-sensitively against the tool names the *server* uses (`read_file`, not `mcp_read_file`). An empty `include` admits every tool; a tool matching any `exclude` pattern is dropped even if `include` matched it. Filtering happens before registration, so a filtered tool never reaches the model or the tool registry. `agentos mcp probe <name>` shows every tool the server offers and which the filter registers; `agentos mcp doctor <name> --probe` also warns about a pattern that matches no tool, or a filter that leaves nothing. ### Tool names Tools register as `mcp_<tool>`. When two servers offer the same tool name, the first configured server keeps the short name and later ones get `mcp_<server>_<tool>`. `mcp.status` returns a `toolMap` of registered name to server tool name. ## How the agent sees MCP servers A tool schema says how to call a tool, not when. Three things tell the agent the rest. **A "Connected MCP Servers" section in the system prompt.** One entry per connected server the session can use: its name, tool count, the `instructions` the server returned from `initialize` (its own account of what it is for and how to use it), and its tool names — or, for a deferred server, a pointer to `tool_search`: ```text ## Connected MCP Servers External tool servers connected over MCP. Their tools are named `mcp_*` ... - **fetch** (2 tools): <untrusted source='mcp:fetch/instructions'>Fetches web pages. Prefer fetch_url for a single page.</untrusted> - Tools: mcp_fetch_feed, mcp_fetch_url - **github** (41 tools): <untrusted source='mcp:github/instructions'>GitHub issues, pull requests and code search.</untrusted> - 41 not loaded yet (e.g. mcp_add_comment, mcp_create_issue, ...): call `tool_search` with keywords or exact names — its list marks them `[MCP server "github"]` — then call the tool. ``` Server instructions are written by the server, so they are quoted in the same untrusted envelope as tool results, with whitespace collapsed, and capped: `mcp.instructions_max_chars` (default 2000) is shared evenly between the servers that sent any; `0` leaves the text out and keeps the list. The section is part of the cached system prompt. It is sorted by server and tool name and does not depend on what a session has loaded, so it changes only when a server connects, disconnects or changes its tools. A session whose tool policy hides a server's tools is not told about that server. **A server prefix on every tool description.** `[MCP server "fetch"] Fetch a URL…`, so a tool can be tied back to its server from the schema alone and in the `tool_search` catalog. A tool's `title` is added when the description does not already say it. **Tool annotations.** The hints a server declares (`readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint`) are appended to the description as `Server hints: read-only, idempotent.` — only the ones the server actually set. A tool declared read-only may also run alongside other tool calls of the same model turn; every other MCP tool runs alone, as before. Annotations are a server's word about itself: they affect scheduling and what the model reads, never authorization. In particular a read-only hint does not exempt a tool from `[tools.invoke] allow` or from any tool policy. ### Deferred tools Every loaded tool costs its full schema on every request. A deferred server's tools are left out of the request and listed, one line each, in the `tool_search` tool's catalog; the agent loads the ones it needs by name or keyword, and they stay loaded for the session (see [deferred tool loading](https://useagentos.dev/docs/core/configuration)). | `defer_loading` | Effect | |---|---| | `"auto"` (default) | Deferred when the server registers more than `mcp.defer_tool_threshold` tools (8), or when all MCP servers together register more than `mcp.defer_total_tool_threshold` (20). | | `true` | Always deferred. | | `false` | Never deferred; every schema rides on every request. | The total is taken across all servers that connected at boot, so they all get the same answer; a server that connects later (`mcp.connect`, a background reconnect, a `tools/list_changed`) is judged against what is registered then, and the others are not re-judged. Nothing is deferred for a session that cannot use `tool_search` (an agent with a tool allowlist, a cron surface), or when `tools.defer_loading = false`: those sessions get the schemas up front. Use `tool_filter` to cut a server down rather than deferral when most of its tools are never wanted. ### Resources and prompts When a server has resources or prompts to offer, AgentOS registers generic access tools for it: | Tool | Does | |---|---| | `mcp_<server>_resources_list` | Resources and resource templates, with URIs. | | `mcp_<server>_resources_read` | Read one resource by `uri`. Binary content is described, not returned. | | `mcp_<server>_prompts_list` | Prompt templates and their arguments. | | `mcp_<server>_prompts_get` | Render a prompt (`name`, `arguments`) as a message list. | They are registered only if the server advertises the capability *and* lists at least one resource (or template) or prompt when it connects — many servers advertise both and have neither. They are deferred unless the server sets `defer_loading = false`, return server text in the untrusted envelope, and pass through `tool_filter` under their short names (`resources_read`), so `tool_filter.exclude = ["resources_*", "prompts_*"]` turns them off. A server that gains its first resource after connecting gets them at its next reconnect. ## Speed - **Boot.** All enabled servers connect at the same time, each under its own connect timeout, so the gateway waits for the slowest server instead of the sum of all of them. A server that fails or times out does not hold up or affect the others; it goes to the background retry below. Tools are registered in config order once the connects finish, so which server keeps a short `mcp_<tool>` name does not depend on connect speed. - **Boot still waits for MCP.** The gateway does not start serving until the connects have finished or timed out. Letting tools appear a moment after startup would change the system prompt and tool list of sessions already running (a prompt-cache miss mid-conversation) and let a cron or channel turn that fires at startup run without its tools. The wait is bounded by the largest connect timeout. - **Concurrent calls.** A stdio server's requests are multiplexed on its pipe by JSON-RPC id: a slow tool call no longer blocks other calls to the same server. The HTTP transports already worked this way. - **Timeouts and cancellation.** A call that exceeds `tool_timeout_seconds` fails with a message naming the server and telling the agent it may retry once; a stdio server is also sent `notifications/cancelled` so it can stop working. The timeout costs that one call, not the connection. - **Catalog changes.** On `notifications/tools/list_changed` AgentOS lists the server's tools again (after a 250 ms quiet period, so a burst is one refresh) and registers the new catalog, with `tool_filter` and the deferral rule applied as at connect. Logged as `mcp.tools_refreshed`. - **A server dying mid-call.** Every call in flight fails at once with a "disconnected" error rather than waiting out its timeout, and the reconnect below starts. `scripts/mcp_client_bench.py` measures boot and call overlap against the test fixture server. ## The `agentos mcp` command | Command | What it does | |---|---| | `list [--json]` | Configured servers, from the config file. | | `status [--json]` | Same, plus counts and the `mcp.enabled` switch. | | `add <name> …` | `--command C [--arg A]… [--cwd D] [--env K=V]…`, or `--url U [--transport sse\|streamable_http] [--header K=V]… [--oauth]`; `--include` / `--exclude` (repeatable or comma-separated), `--tool-timeout`, `--connect-timeout`, `--disabled`, `--replace`. | | `remove <name>` | Delete the definition. | | `enable <name>` / `disable <name>` | Toggle `enabled`. | | `probe <name> [--timeout S]` | Connect, list tools, close. Exit 1 if unreachable. | | `doctor <name> [--probe]` | Validate (command on `PATH`, `cwd` exists, URL shape, fields that do not apply to the transport), then optionally probe. Exit 1 on any error. | Every command takes `--config PATH` (default: the active config) and `--json`. None needs a running gateway. `probe` runs from the CLI process: a stdio server is spawned as a child of your shell, with your environment, not the gateway's. Writes validate the whole config, keep a backup, and rewrite the file — comments in it are not preserved. `mcp` is an operator-only setting, so with a gateway running a write is held until you run `agentos config reload` from your own terminal; MCP servers are connected at gateway start, so restart it to pick the change up. ## Reconnects - **At boot.** A server that fails or times out is logged once (`build_services.mcp_server_failed` / `…_timeout`) and retried in the background after 30 s, then 60 s, 120 s, … capped at 10 minutes. Each failed retry logs one `mcp.reconnect_failed` line with the next delay; success logs `mcp.reconnected` and registers the server's tools. - **When a stdio server dies.** If the process exits on its own, AgentOS logs `mcp.server_exited`, unregisters that server's tools (so the model is not offered tools that can only fail), and reconnects on the same schedule, registering the tools again when it is back. - **When an HTTP transport drops.** One failed request (an auth error, a 5xx, a dropped connection) can close a Streamable HTTP or SSE session for good. The server's tools stay registered, `mcp.status` reports it as `connected: false`, and the next tool call reconnects first (`mcp.transport_reconnecting`). A call that was in flight when it dropped fails and is not resent; one that never left is sent again after the reconnect. - **OAuth tokens.** The saved access token is refreshed with the saved refresh token before it expires, so short-lived tokens need no new sign-in. If the server refuses the refresh, the saved tokens are dropped and the server waits for the user (`build_services.mcp_server_authentication_required` at boot, `mcp.reconnect_needs_sign_in` from a background retry, which then stops). - **What is left alone.** OAuth servers that are not signed in wait for the user. Disabled servers are never retried. `mcp.connect`, `mcp.disconnect` and `mcp.oauth.clear` take a server over from the background retry, and a deliberate disconnect is never revived. While a retry is pending, `mcp.status` reports it on the server's row: ```json "retry": {"reason": "boot", "attempts": 2, "lastError": "timed out", "nextRetryAt": 1763300000.0} ``` `reason` is `boot` or `exited`; `nextRetryAt` is a Unix timestamp. ## Troubleshooting - **Expected tools are missing.** `agentos mcp probe <name>` — look at the *Registered* column, then adjust `tool_filter`. - **The agent does not use a server's tools.** Check the server's row in `mcp.status`: `deferred: true` means its tools sit behind `tool_search` (set `defer_loading = false` for a server the agent should always have at hand), and `hasInstructions: false` means the server gave the agent no description of itself beyond its tool names. - **A stdio server will not start.** `agentos mcp doctor <name>` checks that `command` resolves and `cwd` exists. Arguments belong in `args`, not in `command`. - **Nothing connects.** `mcp.enabled` must be `true`, and the server's own `enabled` too; `agentos mcp status` shows both. - **An edit has no effect.** It is probably held: run `agentos config reload`, then restart the gateway. See [Configuration](https://useagentos.dev/docs/core/configuration#mcp-configuration) for the transport details (stdio framing, SSE endpoint handling, SSRF guard, result envelopes). --- # MCP Server Bridge > Source: https://useagentos.dev/docs/core/mcp-server AgentOS can run as a stdio MCP server bridge for MCP-capable clients. Use this when another local AI client should call into AgentOS session workflows through the Model Context Protocol. The MCP bridge is an integration surface. It is separate from AgentOS's Web UI, CLI, channels, and gateway control console. ## Requirements The MCP SDK the bridge needs is a core AgentOS dependency, so there is no extra to add: any install from the [Installation](https://useagentos.dev/docs/core#installation) section of the README (for example `use-agent-os[recommended]`) includes it. Start the AgentOS gateway: ```sh agentos gateway run ``` Or use the managed gateway: ```sh agentos gateway start --json agentos gateway status ``` ## Run the Bridge ```sh agentos mcp-server run ``` By default, the bridge connects to: ```text ws://localhost:18791/ws ``` Use a different gateway: ```sh agentos mcp-server run --gateway ws://localhost:18792/ws ``` The command runs a stdio MCP server. Configure your MCP-capable client to launch that command as the server process. ## Safety Notes - Keep the gateway bound to `127.0.0.1` unless you intentionally expose it. - Do not put provider keys or channel secrets in MCP client config examples. - Treat the MCP client as another tool-calling surface. The same AgentOS permissions, tools, sessions, and gateway state still matter. ## Troubleshooting If the bridge cannot start: ```sh agentos gateway status agentos doctor ``` If the command reports that the MCP SDK is missing, reinstall or upgrade AgentOS. If the bridge starts but cannot reach AgentOS, check that the gateway is running at the `--gateway` address (default `ws://localhost:18791/ws`, or `AGENTOS_GATEWAY_URL` when set). Read next: - [Configuration](https://useagentos.dev/docs/core/configuration) - [Tools, Approvals, and Sandbox](https://useagentos.dev/docs/core/tools-and-sandbox) - [Operations](https://useagentos.dev/docs/core/operations) --- # Usage and Cost > Source: https://useagentos.dev/docs/core/usage-and-cost AgentOS records token usage and estimated cost from the running gateway. Use the cost view after routed, tool-heavy, channel, or long-context work to understand where model spend is going. ## Requirements Cost inspection uses the gateway: ```sh agentos gateway status ``` If the gateway is not running: ```sh agentos gateway run ``` ## Show Cost ```sh agentos cost ``` The default view lists session/model rows with input tokens, output tokens, and estimated cost. ## Group by Model ```sh agentos cost --by-model ``` Use this when Pilot Router is enabled and you want to see which models carried the recent workload. ## Use JSON Output ```sh agentos cost --json agentos cost --by-model --json ``` JSON output is useful for local dashboards, regression checks, and automated reports. ## Report What Routing Saved ```sh agentos cost savings agentos cost savings --start-date 2026-08-01 --end-date 2026-08-31 agentos cost savings --pdf ~/pilot-router-savings.pdf ``` `agentos cost` shows what you spent; `agentos cost savings` shows what the [Pilot Router](https://useagentos.dev/docs/core/features/pilot-router) avoided spending. It reads the local decision log instead of the gateway, so it works with the gateway stopped, and `--pdf` writes a branded one-page report you can send on. The baseline is the most expensive model configured in `[router.tiers]` — what every routed turn would have cost on your top tier — priced on input tokens only at list rates. That makes the figure a floor, not a full-turn saving, and it covers routing alone: tool-result projection, short-reply enforcement, prompt-cache hits and thinking mode are excluded. See [CLI Reference](https://useagentos.dev/docs/core/cli#agentos-cost-savings) for the full option list. ## What to Check First | Signal | What it can mean | | --- | --- | | Many rows for premium models | Router policy or task shape may be escalating more often than expected. | | High input tokens | Long history, large tool results, or large prompt/tool schema surfaces may dominate cost. | | High output tokens | The task may need tighter instructions or a smaller response format. | | Cost concentrated in one session | Inspect that session before changing global configuration. | ## Lower Cost Safely Start with router and diagnostics: ```sh agentos configure router --router recommended agentos diagnostics on agentos cost --by-model ``` For large tool results, read: - [Tool Compression](https://useagentos.dev/docs/core/features/tool-compression) - [Compaction and Cache Continuity](https://useagentos.dev/docs/core/features/compaction-and-cache) For simple one-shot automation, bound the run: ```sh agentos agent --max-iterations 20 --timeout 600 -m "Bounded task" ``` ## Cap Spend with a Hard Stop Cost views are after the fact. To bound spend while it happens, set ceilings in `[budgets]`: ```toml [budgets] session_limit = 5.0 daily_limit = 50.0 daily_warn = 40.0 ``` A turn that starts at or above a hard limit is refused before any provider call with a `budget_exceeded` error (turn outcome `budgetLimited`), and ceilings are re-checked between iterations so a long tool loop stops at the ceiling too. A `*_warn` threshold raises a one-shot warning without stopping the turn. Spend is persisted to `~/.agentos/state/spend_ledger.db`, so a ceiling survives a gateway restart. Per-agent and per-channel ceilings use `[budgets.agent_daily_limit]` and `[budgets.channel_daily_limit]`. Each admitted turn also holds `budgets.turn_reservation` dollars (default `0.25`) of headroom until it ends, so a concurrent subagent fan-out cannot clear one ceiling several times over against the same snapshot. See [Configuration](https://useagentos.dev/docs/core/configuration#spend-budgets) for the full key list. ## Notes and Limits - Cost is an estimate based on recorded runtime usage and configured pricing. - Provider bills remain the source of truth for actual charges. - Tool compression and routing can reduce model context cost, but they should be checked against task success, not only token totals. - Diagnostics can explain why a turn routed, compacted, retried, or produced unusually large outputs. Read next: - [Pilot Router](https://useagentos.dev/docs/core/features/pilot-router) - [Tool Compression](https://useagentos.dev/docs/core/features/tool-compression) - [Diagnostics and Replay](https://useagentos.dev/docs/core/diagnostics-and-replay) --- # Diagnostics and Replay > Source: https://useagentos.dev/docs/core/diagnostics-and-replay Diagnostics and replay help explain what happened during an AgentOS turn. Use them when a result was surprising, slow, expensive, interrupted, or hard to reproduce from the chat transcript alone. ## Diagnostics Diagnostics are runtime logging controls exposed through the gateway. Check status: ```sh agentos diagnostics status agentos diagnostics status --json ``` Enable diagnostics: ```sh agentos diagnostics on ``` Enable raw turn-call capture when a maintainer asks for deeper provider request evidence: ```sh agentos diagnostics on --raw ``` Turn diagnostics off after collecting enough evidence: ```sh agentos diagnostics off ``` ## When to Use Diagnostics Use diagnostics for: - provider retries, timeouts, or empty responses; - Pilot Router model decisions; - prompt-cache or cache-break investigation; - compaction lifecycle events; - large tool-result compression; - channel delivery failures; - unusually high cost or latency. Avoid leaving raw diagnostics on longer than needed. Raw captures may contain private prompts, tool outputs, local paths, or provider-visible content. ## Replay a Recorded Turn Replay reads a recorded turn from the decision log and prints a human-readable transcript. It is read-only: it does not re-run tools. ```sh agentos replay --session <session-key> --turn <turn-id> ``` Use replay when: - a chat has moved on but you need to inspect an earlier turn; - a bug report needs concise reproduction evidence; - you want to compare transcript output with diagnostics and cost data. ## Where a Turn's Time Goes Every turn records a wall-clock breakdown. The gateway log gets one `turn.timing` line per turn, and the decision log row carries the same data under `timing` (schema 16), which `agentos replay` prints: - `total_ms`: the whole turn; `pre_provider_ms`: turn start to the first provider request; `first_text_ms`: turn start to the first streamed text. - `provider_ms`, `tool_ms`, `approval_wait_ms` (time with at least one approval outstanding), `finalize_ms`, and `iterations` (provider calls). - per stage (`input`, `provider_and_tools`, `prompt_assembler`, `agent_bootstrap`, `compaction_and_history`, `attachment`, `stream_consumer`, `turn_finalizer`; in the log line as `stage_<name>_ms`); - per provider call: start offset, then time to first event, first text and end of stream, with input/output tokens; per tool batch: duration, number of calls and approval wait. - `retries`: model calls the engine repeated, by category (in the log line as `retry_<category>`). `text_tool_call` counts replies that wrote a tool call out as text instead of calling the tool; the engine drops such a reply and asks once more, and the turn-call log records it as a `turn_policy_decision` with `action: retry_text_tool_call`. Rows written before schema 16 have no `timing`; replay shows only the total latency for them. ## Pair Replay With Sessions Find the session first: ```sh agentos sessions list agentos sessions show <session-key> ``` Export the full session if exact context matters: ```sh agentos sessions export <session-key> --output session.md ``` ## Safe Sharing Before sharing diagnostics, replay output, or exported sessions publicly, remove: - provider keys and bearer tokens; - private local paths; - private channel identifiers; - customer, project, or account names that should not be public; - raw provider prompts or tool outputs that include confidential content. Read next: - [Sessions and History](https://useagentos.dev/docs/core/sessions) - [Usage and Cost](https://useagentos.dev/docs/core/usage-and-cost) - [Troubleshooting](https://useagentos.dev/docs/core/troubleshooting) --- # Operations > Source: https://useagentos.dev/docs/core/operations This guide covers day-two commands: sessions, cron, cost, diagnostics, replay, migration, durable agents, MCP, and install inventory. Use it after the first successful chat or gateway run. To operate a gateway on another machine, see [Remote Access](https://useagentos.dev/docs/core/remote-access). ## Sessions Sessions are durable chat/task histories. Use them to resume, inspect, export, or clean up prior work. ```sh agentos sessions list agentos sessions show <session-key> agentos sessions resume <session-key> agentos sessions export <session-key> agentos sessions abort <session-key> agentos sessions delete <session-key> ``` Use session export when exact old context matters or when you want to debug a long-running task outside the chat UI. For resume, abort, export, and cleanup workflows, see [Sessions and History](https://useagentos.dev/docs/core/sessions). ## Durable Agents AgentOS supports durable agent entries, including the built-in `main` agent. ```sh agentos agents list agentos agents add research --name Research --workspace /path/to/research agentos agents delete research ``` Use durable agents when you want separate workspaces, instructions, or tool profiles for recurring roles. Restart the gateway after agent config changes. Keep each durable agent's instructions focused on that role instead of turning every agent into a copy of `main`. For agent examples and concepts, see [Durable Agents](https://useagentos.dev/docs/core/agents). ## Cron and Scheduled Runs Cron jobs run AgentOS tasks on a schedule. Inspect jobs: ```sh agentos cron list agentos cron status <job-id> agentos cron runs <job-id> ``` Add a simple recurring reminder: ```sh agentos cron add \ --every 1h \ --text "Check for urgent project updates and summarize them" \ --name hourly-project-check ``` Add a daily cron-style task: ```sh agentos cron add \ --cron "0 9 * * 1-5" \ --tz "America/Los_Angeles" \ --text "Prepare my weekday morning briefing" \ --name weekday-briefing ``` Manage jobs: ```sh agentos cron update <job-id> --enabled agentos cron remove <job-id> agentos cron run <job-id> ``` Good uses: - morning briefings; - recurring research digests; - PR or CI checks; - channel-delivered reminders; - scheduled memory consolidation or reporting tasks. Pair cron with channels when the output should be delivered somewhere other than the local Web UI. For scheduling examples, delivery options, and troubleshooting, see [Scheduling](https://useagentos.dev/docs/core/scheduling). ## Cost and Usage Inspect usage and estimated cost: ```sh agentos cost agentos cost --by-model agentos cost --json ``` Use cost inspection after tool-heavy, routed, or long-context tasks to understand actual runtime behavior. For cost investigation workflow, see [Usage and Cost](https://useagentos.dev/docs/core/usage-and-cost). ## Always-On Gateway For a gateway that should keep running unattended (a home server, a laptop that sleeps), install it as a user service and let it watch itself: ```sh agentos gateway install --port 18791 agentos gateway status --deep --json curl -s http://127.0.0.1:18791/ready agentos channels status --json ``` - **Restarts.** launchd (macOS) or systemd (Linux) restarts the gateway when it dies; a configuration error (exit `78`) is not restarted into a loop by systemd. See [Run as a service](https://useagentos.dev/docs/core/gateway#run-as-a-service). - **Crash loops.** Three unclean boots in five minutes start the gateway in safe mode: channels, cron and heartbeat are held back, `/ready` reports `state: "safe_mode"`, and `agentos doctor` names the way out. Fix the cause, then `agentos channels start --yes`, or let it clear by itself after five quiet minutes. - **Sleep.** After the machine wakes, the gateway restarts idle channels (`gateway.thaw` in the log; a restart that fails while the network comes back is retried with backoff) and runs each overdue cron job once. A 5-minute health sweep restarts channels that are `disconnected`, `stuck`, `start_failed` or `stale-socket`; one stopped on bad credentials (`terminal`) waits for you — doctor shows the fix. - **Missed jobs.** Agent jobs missed while the gateway was down run `[scheduler] startup_agent_delay_seconds` (default 120) after boot; see [Scheduling](https://useagentos.dev/docs/core/scheduling). - **Stopping.** A stop drains active turns for up to 30 s, then cancels the rest (`drain_budget_ms` in `agentos gateway status --json`); the service units allow 54 s (the worst-case stop plus a margin) before they kill. Stop a service-run gateway through the service (`agentos gateway stop` tells you how) or remove it with `agentos gateway uninstall`. ## Diagnostics Diagnostics help explain runtime behavior without changing the core task. ```sh agentos diagnostics status agentos diagnostics on agentos diagnostics off ``` Use diagnostics when investigating: - provider retry behavior; - router decisions; - cache breaks; - compaction events; - tool-result compression; - channel delivery failures. Turn diagnostics off after collecting the needed evidence. For diagnostics guidance and safe sharing notes, see [Diagnostics and Replay](https://useagentos.dev/docs/core/diagnostics-and-replay). ## Replay Replay a recorded turn from the decision log: ```sh agentos replay --session <session-key> --turn <turn-id> ``` Replay is useful for reproducing an agent turn, reviewing decision metadata, or debugging behavior after the original chat has moved on. ## Migration Preview first: ```sh agentos migrate openclaw --json agentos migrate hermes --json ``` Apply after reviewing the report: ```sh agentos migrate openclaw --apply agentos migrate hermes --apply ``` See [MIGRATION.md](https://github.com/use-agent-os/agent-os/blob/main/MIGRATION.md) for custom paths and conflict handling. ## MCP Server AgentOS can run an MCP server bridge: ```sh agentos mcp-server run ``` The MCP SDK is a core dependency, so a standard install from the [Installation](https://useagentos.dev/docs/core#installation) section of the README is enough; there is no `mcp` extra. Use this when another MCP-capable client should access AgentOS-managed tools or runtime surfaces. For setup details, see [MCP Server Bridge](https://useagentos.dev/docs/core/mcp-server). ## Install Inventory Emit a reproducible workspace-state inventory: ```sh agentos dist agentos dist --output workspace-state.json agentos dist -o ./support/workspace-state.json ``` With no flags the payload prints to stdout. `--output` (`-o`) writes the payload to the given file instead (creating parent directories) and prints the resolved path so shell pipelines can capture it. The payload is a versioned JSON document: ```jsonc { "schema_version": 1, "agentos_version": "<installed version>", "python_requires": ">=3.12", "bundled_channels": ["discord", "email", "slack", "telegram", ...], "bundled_tools": ["agents", "code_exec", "filesystem", "git", ...], "gateway_defaults": {"listen": "127.0.0.1", "port": 18791} } ``` It is built only from installed package metadata plus hard-coded constants, so two calls from the same install produce byte-identical JSON (sorted keys, stable indent). It carries no environment values, file paths, timestamps, or secrets — safe to attach to support requests. Use this for support, release QA, or environment comparison. ## Models Inspect available models: ```sh agentos models list ``` In this build, model inspection can be runtime-backed. If it cannot connect, start the gateway first: ```sh agentos gateway run ``` For provider catalog inspection that does not require a live gateway, use: ```sh agentos providers list ``` Read: [Providers and Models](https://useagentos.dev/docs/core/providers-and-models) ## Health Checklist For a confusing install or runtime: ```sh agentos doctor agentos gateway status agentos gateway status --deep --json agentos providers list agentos search list agentos channels types agentos sandbox status ``` Then turn on diagnostics only if the basic health surfaces are not enough. --- # Troubleshooting > Source: https://useagentos.dev/docs/core/troubleshooting Start with: ```sh agentos doctor agentos doctor --json agentos gateway status ``` The Web UI's Settings › Health at [http://127.0.0.1:18791/control/settings/health](http://127.0.0.1:18791/control/settings/health) also reports readiness and recovery steps when the gateway is running. ## `agentos` Command Not Found After `uv tool install`, open a new terminal or run: ```sh uv tool update-shell ``` Check the executable: ```sh command -v agentos ``` On Windows PowerShell: ```powershell where.exe agentos ``` ## Gateway Is Not Running Start it: ```sh agentos gateway run ``` Or use the managed background process: ```sh agentos gateway start --json agentos gateway status ``` Open: ```text http://127.0.0.1:18791/control/ ``` For a focused gateway guide, see [Gateway](https://useagentos.dev/docs/core/gateway). ## Port Already In Use Use another port: ```sh agentos gateway run --port 18792 ``` Or stop the managed gateway: ```sh agentos gateway stop ``` ## Provider Not Configured Run: ```sh agentos onboard agentos providers list agentos providers configure openrouter ``` Use environment-variable secrets: ```sh export OPENAI_API_KEY="sk-..." agentos configure provider --provider openai --api-key-env OPENAI_API_KEY ``` ## Router Dependency Problems If Pilot Router cannot load, AgentOS can still run with direct model routing. To disable the router: ```sh agentos configure router --router disabled agentos gateway restart ``` On Windows, ONNX Runtime may need the Visual C++ Redistributable for Visual Studio 2015-2022 x64. The portable installer and the PowerShell source installer install it via `winget`; the `uv tool install` path does not. If logs show `DLL load failed`: 1. Install the [Visual C++ Redistributable](https://learn.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist) (2015-2022 x64). 2. Restart the shell and gateway. ### Router Degraded or Pinned to One Tier A missing or incomplete ONNX model bundle is the usual cause. From a source checkout: ```sh git lfs pull --include="src/agentos/agentos_router/models/**" ``` Then rebuild and reinstall. Release installs ship the bundle in the wheel. To use the `llm_judge` strategy instead (no local model files), pick it during onboarding or set: ```toml [agentos_router] strategy = "llm_judge" ``` Restart the gateway after changing the file. See [Configuration](https://useagentos.dev/docs/core/configuration#router-strategy). ## Search Does Not Work Inspect search providers: ```sh agentos search list agentos search status ``` Use DuckDuckGo for a no-key path: ```sh agentos configure search --search-provider duckduckgo ``` Use Brave with a key: ```sh export BRAVE_SEARCH_API_KEY="..." agentos configure search --search-provider brave --api-key-env BRAVE_SEARCH_API_KEY ``` ## Browser Tool Not Found or Not Working The browser tool stays hidden until the `agent-browser` binary is installed: ```sh npm install -g agent-browser agent-browser install # downloads Chromium ``` On Debian, Ubuntu, or Docker, also install system libraries: ```sh agent-browser install --with-deps ``` `agentos doctor` reports whether the binary and Chromium are present. A gateway started by the desktop app, launchd or systemd does not inherit your shell's `PATH`, so AgentOS also looks in the usual npm global directories: the newest nvm and fnm Node versions, Volta, pnpm, Bun, Homebrew (`/opt/homebrew/bin`, `/usr/local/bin`) and `~/.npm-global/bin`. If your install lives somewhere else, set the path explicitly: ```toml [browser] binary_path = "/path/to/agent-browser" # output of `which agent-browser` ``` ### Headless Chromium Gets Blocked Some sites detect headless Chromium and serve CAPTCHAs or refuse to load. Do not try to solve CAPTCHAs. Switch to `web_search` / `web_fetch`, or use [attach mode](https://useagentos.dev/docs/core/features/browser#attach-consent) with a signed-in Chrome. ### Attach Mode Will Not Connect Start Chrome with a debug port on localhost: ```sh # macOS /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome \ --remote-debugging-port=9222 # Linux google-chrome --remote-debugging-port=9222 ``` Then set both the port and the consent flag: ```toml [browser] cdp_port = 9222 attach_confirmed = true ``` The port alone is not enough. `attach_confirmed = true` is required because attach mode can drive whatever the Chrome session is logged into. ## Channel Config Saved but Channel Is Offline Restart the gateway after editing channel config: ```sh agentos gateway restart agentos channels status <name> --json ``` For webhook channels, confirm the gateway is reachable from the provider and that callback secrets match. ## A Tool Was Denied Check sandbox and permission state: ```sh agentos sandbox status agentos doctor ``` For one-shot runs, choose an explicit permission posture: ```sh agentos agent --permissions restricted -m "Read only" agentos agent --permissions full -m "Trusted local automation" ``` ## The Agent Seems to Forget Old Context Long sessions may compact old history. This is expected under context pressure. Inspect sessions: ```sh agentos sessions show <session-key> agentos sessions export <session-key> ``` If exact old text matters, keep it in a file, memory note, or exported session. ## A Turn Is Too Expensive or Too Slow Try: ```sh agentos configure router --router recommended agentos diagnostics on agentos cost ``` For automation: ```sh agentos agent --max-iterations 20 --timeout 600 -m "Bounded task" ``` For large tool outputs, see [Tool Compression](https://useagentos.dev/docs/core/features/tool-compression). ## Memory or Embeddings Not Working Memory search uses local ONNX embeddings by default. Inspect: ```sh agentos memory status ``` If the embedding model is not loaded, the `recommended` extra may be missing: ```sh uv tool install --force "use-agent-os[recommended]" ``` For source installs, pull the Git LFS weights: ```sh git lfs pull --include="src/agentos/memory/models/**" ``` If the model files are pointer stubs instead of real weights, embeddings will not load. `agentos doctor` will report memory embeddings as FTS-only. ## Docker-Specific Issues The shipped `Dockerfile` already sets `AGENTOS_LISTEN=0.0.0.0`. Custom images must bind `0.0.0.0` (`--listen 0.0.0.0` or `AGENTOS_LISTEN=0.0.0.0`) so the port mapping reaches the gateway. Binding `127.0.0.1` inside the container is valid, but the process is then unreachable from the host. - A wildcard bind needs enforced auth: without it the gateway logs `Refusing to serve: auth.mode='none'`, exits `78`, and a restart policy loops it. The shipped `compose.yaml` requires `AGENTOS_AUTH_TOKEN` for this reason. - ONNX Runtime and Pilot Router may need extra system packages depending on the base image. The repo Dockerfile handles this; a custom image may not. - State lives under `AGENTOS_STATE_DIR`, `/var/lib/agentos` in the shipped image. Mount a volume there if config and sessions should persist across restarts. More symptoms and fixes are in [Run the gateway in a container](https://useagentos.dev/docs/core/container-gateway#troubleshooting). ## Still Stuck? 1. Run `agentos doctor` and read the findings. 2. Check the [docs index](https://useagentos.dev/docs/core) for the feature you are using. 3. Open a [documentation issue](https://github.com/use-agent-os/agent-os/issues/new?template=docs_report.yml) or a [bug report](https://github.com/use-agent-os/agent-os/issues/new?template=bug_report.yml) on GitHub. --- # DEX API > Source: https://useagentos.dev/docs/dex/api The AgentOS DEX API is a keyless HTTP API that lets an agent swap tokens. You ask for a price or a quote and get JSON back; a quote carries unsigned transaction calldata that your own wallet signs and sends. - **Base URL:** `https://agg.useagentos.dev` - **No API key, no auth header.** Swap endpoints are plain `GET` requests. - **Non-custodial.** The service holds no private key. It never signs and never broadcasts; a swap happens only when your signer sends the transaction. ## Chains | Chain | `chain` value | Chain ID | |---|---|---| | Base | `base` | 8453 | | Robinhood Chain | `robinhood` | 4663 | `GET /v1/chains` is the live list, including which liquidity sources each chain offers. ## Endpoints | Endpoint | What it returns | |---|---| | `GET /v1/chains` | Supported chains and their liquidity sources | | `GET /v1/tokens` | The token symbol list for one chain | | `GET /v1/price` | An indicative price. No wallet needed; cached for about 5 seconds | | `GET /v1/quote` | An executable quote with unsigned calldata. Requires `taker` | | `POST /v1/limit-orders/sign-message` | A limit order for the maker to sign (EIP-712) | | `POST /v1/limit-orders` | Submits the signed limit order | | `GET /v1/limit-orders` | A maker's limit orders on one chain | | `POST /v1/limit-orders/cancel-sign`, `/cancel` | Gasless cancel: typed data to sign, then submit | | `POST /v1/limit-orders/hard-cancel` | Unsigned calldata for an on-chain cancel | | `GET /health` | Liveness | The full reference is served by the API itself: [`/llms.txt`](https://agg.useagentos.dev/llms.txt) for agents and [`/openapi.json`](https://agg.useagentos.dev/openapi.json) for tooling. ## Swap in three calls ```bash # 1. Find symbols and check both sides are tradeable curl "https://agg.useagentos.dev/v1/tokens?chain=base" # 2. (Optional) check the rate curl "https://agg.useagentos.dev/v1/price?chain=base&sell=WETH&buy=USDC&sellAmount=1" # 3. Get calldata built for your wallet curl "https://agg.useagentos.dev/v1/quote?chain=base&sell=WETH&buy=USDC&sellAmount=1&taker=0xYourWallet" ``` Then, from the wallet you passed as `taker`: 1. If `approval` is not `null`, sign and send `approval.transaction` first and wait for it to be mined. It approves exactly the amount this swap needs. 2. Sign and send `transaction` (`to`, `data`, `value`, `gas`, `gasPrice`). 3. If `expiresAt` has passed (about 30 seconds), discard the quote and ask again. Never sign stale calldata. Selling native ETH needs no approval: `approval` is `null` and `transaction.value` carries the ETH. ## Request parameters Shared by `/v1/price` and `/v1/quote`: | Parameter | Required | Meaning | |---|---|---| | `chain` | yes | `base`, `robinhood`, or the chain ID | | `sell`, `buy` | yes | A symbol from `/v1/tokens`, a token contract address, or `ETH` | | `sellAmount` or `sellAmountRaw` | exactly one | Human units (`0.25`) or base units. The API always sells an exact input | | `slippageBps` | no | 1 to 500. Default 50 (0.5%) | | `source` | no | `0x` (default) or `uniswap`, where the chain offers it | | `taker` | `/v1/quote` only | The wallet that will sign and send | | `recipient` | no, `/v1/quote` only | Where the bought token is delivered. Defaults to `taker` | Every amount in a response comes as `raw` (base units, authoritative) and `formatted` (for display). When there is no route, the answer is still HTTP 200 with `liquidityAvailable: false`. ## Fees A 20 bps (0.2%) fee applies to swaps that execute. It is reported in the `fee` field and already deducted from `buyAmount`. A quote you never broadcast costs nothing. Wrapping ETH to WETH, or back, is free. Each response also carries an `execution` block that says which contract you approve and call. On the contract path that is the AgentOS Router, which takes the fee on-chain. See [DEX Contracts](https://useagentos.dev/docs/dex/contracts). ## Limit orders Limit orders are placed in an off-chain order book and filled on-chain once your price is reached. Both sides must be ERC-20 tokens, so wrap ETH first. Creating an order and cancelling it gaslessly cost no gas, and the API charges no fee on limit orders. ## Rate limits | Route | Limit | |---|---| | `/v1/price` | 60 requests per minute per IP | | `/v1/quote` | 120 per minute per IP, and 30 per minute per taker | | `/v1/limit-orders` (all routes) | 60 per minute per IP | Do not poll. Ask for a price once, reuse it for its few seconds of life, and request a quote only when you intend to sign. ## Errors Every failure uses one envelope: ```json { "error": { "code": "UNKNOWN_TOKEN", "message": "human-readable, safe to show a user", "retryAfterSeconds": 60, "details": { "chain": "base" } } } ``` `retryAfterSeconds` and `details` are optional. Common codes are `INVALID_REQUEST`, `UNKNOWN_TOKEN`, `TOKEN_NOT_TRADEABLE`, `UNSUPPORTED_CHAIN` and `RATE_LIMITED`; the complete list is in [`/llms.txt`](https://agg.useagentos.dev/llms.txt). --- # DEX Contracts > Source: https://useagentos.dev/docs/dex/contracts The AgentOS DEX contracts are the on-chain layer behind the [DEX API](https://useagentos.dev/docs/dex/api). A quote from the API is a transaction that calls the Router; the Router takes the AgentOS fee in the sell token and hands the rest to the Executor, which runs the liquidity source's calldata. The contracts are immutable (no proxy, no upgrade) and verified on the block explorers. They have not had a formal third-party audit. ## Contracts | Contract | Role | |---|---| | `AgentOSRouter` | What users approve and call. Takes the fee, passes the rest to the Executor, and reverts unless the recipient received at least `minAmountOut`. It only ever moves tokens from the caller of that swap. | | `AgentOSExecutor` | Runs the liquidity source's calldata. Callable only by the Router, holds no approvals, and clears every allowance it grants before returning. Keeps the registry of sources. | | `AgentOSWrapAdapter` | The `wrap` source: wraps ETH to WETH and back. | ## Deployments The Router and Executor are at the same address on both chains. | Contract | Base (8453) | Robinhood Chain (4663) | |---|---|---| | `AgentOSRouter` | [`0x4Cf93bac8920b1EFc92B0d2C84dcbE56802E530c`](https://basescan.org/address/0x4Cf93bac8920b1EFc92B0d2C84dcbE56802E530c) | [`0x4Cf93bac8920b1EFc92B0d2C84dcbE56802E530c`](https://robin.etherscan.io/address/0x4Cf93bac8920b1EFc92B0d2C84dcbE56802E530c) | | `AgentOSExecutor` | [`0x5118B3959192a6f79B05c8b2A50b58B0DA192FA6`](https://basescan.org/address/0x5118B3959192a6f79B05c8b2A50b58B0DA192FA6) | [`0x5118B3959192a6f79B05c8b2A50b58B0DA192FA6`](https://robin.etherscan.io/address/0x5118B3959192a6f79B05c8b2A50b58B0DA192FA6) | | `AgentOSWrapAdapter` | [`0x46b4f62A68F2Ee289215735F19d4f0e09802Cf66`](https://basescan.org/address/0x46b4f62A68F2Ee289215735F19d4f0e09802Cf66) | [`0x4695326b3B2012b0BBF50843D97F1D5A325A912d`](https://robin.etherscan.io/address/0x4695326b3B2012b0BBF50843D97F1D5A325A912d) | The owner is a 2-of-3 Safe. The fee is 20 bps. ## How a swap runs 1. The caller approves the Router for `amountIn` of the sell token. Selling native ETH needs no approval; the ETH is sent as the transaction value. 2. The caller calls `Router.swap(params, callData)` with the calldata from the API quote. 3. The Router takes the fee, `floor(amountIn * feeBps / 10000)`, in the sell token and sends the rest to the Executor. 4. The Executor runs the calldata against the registered source named by `sourceId`. 5. The Router checks the recipient's balance grew by at least `minAmountOut`, or the whole transaction reverts. ```solidity struct SwapParams { bytes32 sourceId; // which registered source runs the swap address tokenIn; // NATIVE (0xEeee…EEeE) for the chain's coin address tokenOut; uint256 amountIn; // gross amount taken from the caller, fee included uint256 minAmountOut; // checked against what the recipient received address recipient; uint256 deadline; bytes32 quoteId; // reference to the off-chain quote; emitted, never read } function swap(SwapParams calldata p, bytes calldata callData) external payable returns (uint256 amountOut); ``` You normally do not build these arguments yourself: sign the `transaction` the API returns. ## Liquidity sources A source is an entry point the Executor is allowed to call, registered by the owner. Registered today on both chains: `0x`, `uniswap`, `uniswap-native` and `wrap`. A source id is written once: it can be disabled, re-enabled or removed, but never edited or reused. ## What the owner can change | Change | Limit | |---|---| | Fee | 0 to 100 bps, a hard cap in the contract | | Fee recipient | Set by the owner | | Sources | Add, disable, re-enable or remove | | Pause | The owner or a guardian can pause swaps; only the owner can unpause | | Ownership | Two-step transfer | Nobody can upgrade the contracts or move a user's tokens outside that user's own swap. ## Known limits - Tokens that tax every transfer revert when sold through the Router. - Tokens sent to the Router by mistake cannot be recovered; it has no rescue function by design. - Below `10000 / feeBps` base units, the fee rounds down to zero. - `Swapped` events are not proof of volume: anyone can emit one with a token of their own making.