> ## Documentation Index
> Fetch the complete documentation index at: https://docs.runmaestro.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# CLI

> Send messages to agents, list sessions, run playbooks, and manage Maestro settings from the command line.

Maestro includes a CLI tool (`maestro-cli`) for sending messages to agents, browsing sessions, running playbooks, managing settings, and controlling resources from the command line, cron jobs, or CI/CD pipelines. It runs on the Electron runtime that ships inside Maestro, so it needs no separate Node.js.

## Installation

The CLI is bundled with Maestro as a JavaScript file, `maestro-cli.js`, in the app's resources folder. It must run under the app's own executable with `ELECTRON_RUN_AS_NODE=1` set, not under a system `node`: its SQLite module (used by Cue, `maestro-cli host`, and `cue activity`) is built for the app's Electron and does not load in a system Node.js, so there `host start` reports Cue as failed and `cue activity` cannot read `cue.db`.

The simplest way is to let the app write the wrapper: **Settings → General → Maestro CLI → Install / Update CLI**. It writes `~/.local/bin/maestro-cli` (`maestro-cli.cmd` on Windows) in exactly that form and adds `~/.local/bin` to your `PATH`. Run it again after moving or updating the app.

To write the wrapper by hand, use the line for your install:

```bash theme={"theme":"dracula"}
# macOS (Maestro.app in /Applications)
printf '#!/bin/bash\nELECTRON_RUN_AS_NODE=1 "/Applications/Maestro.app/Contents/MacOS/Maestro" "/Applications/Maestro.app/Contents/Resources/maestro-cli.js" "$@"\n' | sudo tee /usr/local/bin/maestro-cli && sudo chmod +x /usr/local/bin/maestro-cli

# Linux (deb or rpm, installed to /opt/Maestro)
printf '#!/bin/bash\nELECTRON_RUN_AS_NODE=1 "/opt/Maestro/maestro" "/opt/Maestro/resources/maestro-cli.js" "$@"\n' | sudo tee /usr/local/bin/maestro-cli && sudo chmod +x /usr/local/bin/maestro-cli
```

**Linux AppImage.** A running AppImage lives in a temporary mount (`/tmp/.mount_*`) that gets a new name on every launch, so a hand-written wrapper cannot point into it. Use **Settings > Install / Update CLI**: it writes a shim that re-enters the AppImage in node mode, plus a bootstrap beside it that resolves the bundled CLI from the mount that run creates. The shim keeps working after a restart and while the desktop app is closed. After an AppImage update that renames the file, launch the new AppImage once so Maestro can repair the shim. Maestro also repairs an older shim that pointed at a `/tmp/.mount_*` path at the next launch.

For a mount-free wrapper, extract the AppImage once to a directory that stays, and point the wrapper there:

```bash theme={"theme":"dracula"}
# Extracts to ./squashfs-root; repeat after each AppImage update
./maestro-<version>-x86_64.AppImage --appimage-extract
rm -rf "$HOME/maestro-app"               # replace the previous extraction
mv squashfs-root "$HOME/maestro-app"     # any directory you keep
printf '#!/bin/bash\nELECTRON_RUN_AS_NODE=1 "%s/maestro-app/maestro" "%s/maestro-app/resources/maestro-cli.js" "$@"\n' "$HOME" "$HOME" | sudo tee /usr/local/bin/maestro-cli && sudo chmod +x /usr/local/bin/maestro-cli
```

If a Settings-installed shim at `~/.local/bin/maestro-cli` takes precedence in `PATH`, remove it and its bootstrap with `rm -f "$HOME/.local/bin/maestro-cli" "$HOME/.local/bin/maestro-cli-bootstrap.js"`. Then check that `command -v maestro-cli` resolves to `/usr/local/bin/maestro-cli`.

**Windows.** The installer puts Maestro in `%LOCALAPPDATA%\Programs\Maestro` when installed for the current user (the default), or in `%ProgramFiles%\Maestro` when installed for all users; you may also have picked another folder. Set `$MaestroDir` to yours, then run in PowerShell (no Administrator needed):

```powershell theme={"theme":"dracula"}
$MaestroDir = "$env:LOCALAPPDATA\Programs\Maestro"   # or "$env:ProgramFiles\Maestro"
New-Item -ItemType Directory -Force "$env:USERPROFILE\.local\bin" | Out-Null
@"
@echo off
set "ELECTRON_RUN_AS_NODE=1"
"$MaestroDir\Maestro.exe" "$MaestroDir\resources\maestro-cli.js" %*
"@ | Out-File -FilePath "$env:USERPROFILE\.local\bin\maestro-cli.cmd" -Encoding ASCII
```

Then add `%USERPROFILE%\.local\bin` to your user `PATH`. The portable build (`Maestro-Portable-*.exe`) unpacks itself to a temporary folder on each launch and deletes it on exit, so it cannot back a wrapper; use the installer build for the CLI.

To run a single command without a wrapper, use the same form directly:

```bash theme={"theme":"dracula"}
ELECTRON_RUN_AS_NODE=1 "/Applications/Maestro.app/Contents/MacOS/Maestro" "/Applications/Maestro.app/Contents/Resources/maestro-cli.js" list groups
```

## Usage

### Global Flags and Exit Codes

Two flags work on every command:

| Flag | Description |
| - | - |
| `-q, --quiet` | Suppress incidental success output (errors still print). Never gates `--json`. |
| `--verbose` | Print extra detail where available |

Commands exit with a standardized code so scripts and CI can branch on the failure class:

| Code | Meaning |
| - | - |
| `0` | Success |
| `1` | Generic / uncategorized failure |
| `2` | Invalid usage (unknown flag, bad argument, nothing to do) |
| `3` | The Maestro desktop app is not running or not reachable |
| `4` | The running app does not support the command (older build) |
| `5` | The app was reachable but did not respond in time |

Almost every verb that needs the desktop app reports its absence the same way: the message `Maestro desktop app is not running or not reachable`, exit code `3`, and with `--json` (or on verbs that always print JSON) the code `MAESTRO_NOT_RUNNING`:

```json theme={"theme":"dracula"}
{
	"success": false,
	"error": "Maestro desktop app is not running or not reachable",
	"code": "MAESTRO_NOT_RUNNING"
}
```

This covers a missing or stale discovery file, a connection that never opens, and one refused at the network level. An app that answers but refuses the connection (for example the Web Login gate) is running, so it reports its own error instead.

A few verbs do not follow this yet: `steer-auto-run`, `quick-chat`, `window`, `maestro-run` and `plugin list|update` print the same message but exit `1` with no `code`, and the `computer-history` writes exit `1` with the message wrapped in `Could not reach the Maestro app (...)`. In a script, treat exit `1` from these as possibly meaning the app is not running.

### Who Moves the View (`--background` / `--focus`)

Focus belongs to whoever is at the keyboard. An agent may create a surface; it should not decide you ought to be looking at it. Every verb that can move the Maestro view or raise a notice therefore accepts `--background`, which means exactly two things: the active agent does not change, and the active tab inside any agent does not change. The surface is still created and still addressable - it lands in the tab bar the way a browser opens a background tab.

Maestro's own system prompt tells agents to **pass `--background` by default** and to drop it only when you asked to be shown something. What follows describes what each verb does when the flag is absent, which is unchanged.

`--focus` is the opposite ask, and it ships on every one of these verbs even where it only names the current default. If both are passed, `--focus` wins.

**The flag is additive: one verb's default changed.** An unflagged call behaves exactly as it always has, except `refresh-auto-run`, which is now background by default because its old focusing default only ever pulled you away from the agent you were looking at.

| Command | Default when neither flag is passed |
| - | - |
| `open-file` | switches to the file |
| `open-terminal` | switches to the new terminal |
| `open-browser` | switches to the new browser tab |
| `tab new` | switches to the new tab |
| `tab reopen` | switches to the restored tab |
| `tab compact` | switches to the compacted tab |
| `tab merge` | switches to the receiving tab, which sends the context |
| `tab transfer` | switches to the new tab in the target agent |
| `dispatch --new-tab` | **background** (as it always was) |
| `dispatch` (no `--new-tab`) | selects the target agent |
| `create-agent` | selects the new agent |
| `duplicate-agent` | selects the new agent |
| `create-worktree` | selects the new agent |
| `switch-mode` | switches the mode |
| `refresh-auto-run` | **background** (`--focus` to switch) |
| `refresh-files` | **already quiet**; flag accepted, no effect |

`focus-agent`, `send --tab`, `open`, and `open-graph` exist *to* move the view - you named that intent - so they take no placement flag. The graph in particular is a full-window overlay whose only effect is being looked at, so a background one would do nothing at all.

`switch-mode` is the one verb here that creates nothing: changing an agent's rendered surface is its entire effect, so there is no background surface to leave behind. `--background` there means "skip it rather than move me", and it only refuses when the target is the agent already on screen. Switching an off-screen agent changes no pixels and goes through normally.

`dispatch` is two verbs wearing one name. With `--new-tab` it creates a tab you will address by the id it prints, so it is background by default. Without it, it writes into an existing conversation and selects that agent, as it always has. `create-worktree --message` uses the same write path, and carries whatever placement you asked `create-worktree` for - so `--background` no longer creates the agent quietly and then yanks you onto it one message later.

`refresh-files` accepts `--background` and ignores it, because it never moved the view or said anything in the first place: the Files panel it refreshes is only drawn for the agent already on screen. That is deliberate rather than an oversight. The advice given to agents is "pass `--background` unless the user asked to be taken there", and an unknown option is a hard error - so one verb that refused the flag would turn a good habit into a failed command.

Errors ignore placement. A command that fails still raises its toast with `--background` set: the flag decides where a surface goes, not whether you get to hear that something broke.

### Sending Messages to Agents

Send a message to an agent and receive a structured JSON response. Supports creating new sessions or resuming existing ones for multi-turn conversations.

```bash theme={"theme":"dracula"}
# Send a message to an agent (creates a new session)
maestro-cli send <agent-id> "describe the authentication flow"

# Resume an existing session for follow-up
maestro-cli send <agent-id> "now add rate limiting" -s <session-id>

# Send in read-only mode (agent can read but not modify files)
maestro-cli send <agent-id> "analyze the code structure" -r
```

The response is always JSON:

```json theme={"theme":"dracula"}
{
	"agentId": "a1b2c3d4-...",
	"agentName": "My Agent",
	"sessionId": "abc123def456",
	"response": "The authentication flow works by...",
	"success": true,
	"outcome": "completed",
	"usage": {
		"inputTokens": 1000,
		"outputTokens": 500,
		"cacheReadInputTokens": 200,
		"cacheCreationInputTokens": 100,
		"totalCostUsd": 0.05,
		"contextWindow": 200000,
		"contextUsagePercent": 1
	}
}
```

`outcome` says how the turn ended:

| `outcome` | `success` | Meaning |
| - | - | - |
| `completed` | `true` | Clean exit with the provider's explicit done signal. |
| `completed-with-warning` | `true` | An answer was captured, but the process exited non-zero or never sent a done signal. |
| `interrupted` | `false` | The send was stopped (Ctrl+C or SIGTERM). Never reported as a crash, even if the agent wrote to stderr. |
| `crashed` | `false` | No usable answer, a classified provider error (auth, rate limit, ...), or the process failed to start. |

For providers that stream JSON lines (everything except Claude Code), a captured answer outranks a bare non-zero exit, but not a specific provider error: a turn whose stderr says the login expired fails even if some text was produced. Claude Code keeps requiring a clean exit. A process killed by a signal nobody requested is always `crashed`.

The first Ctrl+C stops the agent gracefully (SIGTERM, then SIGKILL after 5 seconds if it ignores it) and exits with code `130`; a second Ctrl+C exits immediately. Other failures exit with `1`. Over an SSH remote this stops the local `ssh` client, and the remote process is not guaranteed to receive the hangup.

On failure, `success` is `false` and an `error` field is included:

```json theme={"theme":"dracula"}
{
	"success": false,
	"error": "Agent not found: bad-id",
	"code": "AGENT_NOT_FOUND"
}
```

| Flag | Description |
| - | - |
| `-s, --session <id>` | Resume a provider session (the `sessionId` a previous `send` returned, or one from `list sessions`) instead of creating a new one |
| `-r, --read-only` | Run in read-only/plan mode (agent cannot modify files) |
| `-t, --tab` | Open/focus the agent's session tab in the Maestro desktop app |
| `--no-history` | Do not write a History entry for this turn |
| `--no-synopsis` | Skip the synopsis turn; the History entry carries the response text |

`send` runs headless, beside the desktop: it never writes into a desktop tab. `--session` takes a **provider** session id, not a Maestro tab id. A tab id is refused with `SESSION_IS_TAB_ID`, and the provider session of a tab that is mid-turn is refused with `TAB_BUSY` (resuming it would put a second writer on one conversation). Both errors name the command that does what you meant: to deliver a message into a live tab, waiting behind a busy turn, use `maestro-cli dispatch <agent-id> "<message>" --tab <tab-id> --queue`.

Every `send` writes an entry to the agent's History, the same file the desktop History panel reads, whether or not the desktop app is running (an open app picks it up live). Who started the send decides the kind of entry. A send Maestro Cue started (a `command` action that runs `maestro-cli send`, or an agent Cue woke that runs it) is a `CUE` entry, and the turn it runs is marked `MAESTRO_QUERY_SOURCE=cue`. A send run from another agent's shell is an `AGENT` entry whose summary opens with `Sent by <agent>:`. Both carry a pass/fail indicator. A send from your own shell or a script is a `USER` entry. A successful turn is summarized by a short synopsis turn resumed on the same provider session at the cheapest model and effort, unless that would shrink the context window, in which case the agent's own model is kept. If the synopsis reports nothing to record, fails, or prints a provider error, the first line of the response is used instead. After a `--read-only` send the synopsis turn is read-only too. Failed and interrupted turns are recorded without a synopsis turn. A History write that fails prints a warning on stderr and never fails the send; the JSON on stdout is unchanged either way. Use `--no-synopsis` to skip the extra turn, or `--no-history` to record nothing.

For desktop-handoff workflows (route the message through a desktop tab, return an addressable tab id, etc.) use [`maestro-cli dispatch`](#dispatching-to-a-desktop-tab) instead.

Error codes: `AGENT_NOT_FOUND`, `AGENT_UNSUPPORTED`, `<AGENT>_NOT_FOUND` (e.g. `CLAUDE_CODE_NOT_FOUND`, `CODEX_NOT_FOUND`), `SESSION_IS_TAB_ID`, `TAB_BUSY`, `MAESTRO_NOT_RUNNING`, `COMMAND_FAILED`.

Supported agent types: any installed provider - `claude-code`, `codex`, `opencode`, `factory-droid`, `copilot-cli`, `hermes`, `pi`, `qwen3-coder`, `omp`.

#### Messages that start with a dash

Messages whose first character is a Unicode dash (U+2014 em dash or U+2013 en dash), a double hyphen (`--`), or an ASCII hyphen/minus (`-`) collide with option parsing and will be rejected as unknown flags. Use the standard `--` end-of-options separator so the message is passed verbatim:

```bash theme={"theme":"dracula"}
maestro-cli send <agent-id> -- "- revise the spec"
maestro-cli send <agent-id> -s <session-id> -- "--re-run"
maestro-cli dispatch <agent-id> -- "--force the rewrite"
```

Everything after `--` is treated as positional, so any flags you need must come before the separator. For `send` that's `-s`, `-r`, `-t` (`-t` is the boolean focus flag here); for `dispatch` it's `-t`/`--tab`, `--new-tab`, `-f`.

### Dispatching to a Desktop Tab

`dispatch` hands a prompt to an agent in the running Maestro desktop app and returns the tab/session id, so callers can address the same tab on follow-up calls without holding a persistent channel. Use this for orchestration use cases (Cue pipelines, external bots, multi-step automations).

```bash theme={"theme":"dracula"}
# Dispatch to the active tab of an agent
maestro-cli dispatch <agent-id> "review the PR description"

# Open a fresh tab and dispatch the prompt into it (hidden: no chip in the strip)
maestro-cli dispatch <agent-id> "start a new review pass" --new-tab

# Same, but give the new tab a chip so it shows in the tab strip
maestro-cli dispatch <agent-id> "start a new review pass" --new-tab --visible

# Continue a previous dispatch by targeting its tab
maestro-cli dispatch <agent-id> "and now run the tests" -t <tab-id>

# Force a write into a tab that is itself mid-turn (requires allowConcurrentSend=true).
# An idle tab of a busy agent needs no --force: it runs its own turn in parallel.
maestro-cli dispatch <agent-id> "interrupt with this" -f

# Pick how an @mention runs instead of leaving it to the wording
maestro-cli dispatch <agent-id> "fix the flaky test, then tell @Reviewer" --routing handoff
```

Output is always JSON. `sessionId` and `tabId` are the same value, duplicated so polling consumers can use either name:

```json theme={"theme":"dracula"}
{
	"success": true,
	"agentId": "a1b2c3d4-...",
	"sessionId": "tab-xyz",
	"tabId": "tab-xyz"
}
```

| Flag | Description |
| - | - |
| `--new-tab` | Create a fresh AI tab in the target agent and deliver the prompt into it. The tab is hidden: it is named from the prompt and runs normally, but draws no chip in the tab strip until you open it from the completion toast or the caller's delegation pill. It runs now, even while another tab of the agent is mid-turn. Mutually exclusive with `-t` and `-f` (a new tab is never mid-turn, so there is nothing to force) |
| `--visible` | With `--new-tab`: give the new tab a chip in the tab strip instead of creating it hidden. `--focus` implies it |
| `--background` | Leave the view where it is. Already the default with `--new-tab`; without it, suppresses the agent switch |
| `--focus` | Move the view to the target after dispatching |
| `-t, --tab <id>` | Target an existing tab by id (from a previous `dispatch`). Mutually exclusive with `--new-tab` |
| `-f, --force` | Write into a tab that is itself mid-turn (two answers interleave in one conversation). Gated by `allowConcurrentSend`; errors with code `FORCE_NOT_ALLOWED`. An idle tab of a busy agent needs no `--force`. Cannot be combined with `--new-tab` |
| `--routing <mode>` | How the message's `@mentions` run, the same pick as the composer's routing strip: `parallel` (both answer; this agent waits for the reply), `consult-first` (the mentioned agent answers first), `handoff` (this agent's answer is sent on), or `only` (just the mentioned agents answer). Overrides what the wording implies. Works with `--queue` and `--new-tab`. Errors with `INVALID_OPTIONS` for an unknown mode or a message that mentions no other agent. Read it back with `queue list`, which shows each item's `mentionRouting` |

Error codes: `INVALID_OPTIONS`, `AGENT_NOT_FOUND`, `FORCE_NOT_ALLOWED`, `MAESTRO_NOT_RUNNING`, `SESSION_NOT_FOUND`, `DISPATCH_REFUSED`, `NEW_TAB_NO_ID`, `COMMAND_FAILED`. `DISPATCH_REFUSED` fires when the desktop declines the prompt, most often because the target tab is mid-turn (use `--queue` to wait for it). `NEW_TAB_NO_ID` fires when the desktop app acknowledges `--new-tab` without returning a tab id, leaving callers nothing to chain follow-up dispatches against. Requires the Maestro desktop app to be running.

### Dispatch with Callback (`--notify-on-complete`)

`dispatch` is fire-and-forget: it returns a tab id and exits, and nothing tells the caller when that delegated run finished. `--notify-on-complete` closes that loop. When the dispatch finishes, Maestro starts a **real turn in the calling agent's live tab** carrying the result plus a handle to the full output, so an orchestrator can run build -> review -> fix -> verify without a human relaying "it's done, carry on".

```bash theme={"theme":"dracula"}
# Delegate a review, and wake me when it is done
maestro-cli dispatch <reviewer-agent> "review the diff on feat/x" \
	--new-tab \
	--notify-on-complete <orchestrator-agent>
```

The response echoes the armed callback:

```json theme={"theme":"dracula"}
{
	"success": true,
	"agentId": "reviewer-...",
	"sessionId": "tab-xyz",
	"tabId": "tab-xyz",
	"callbackId": "cb_01j...",
	"notifyOnComplete": "orchestrator-..."
}
```

| Flag | Description |
| - | - |
| `--notify-on-complete <agent-id>` | Agent to wake when this dispatch finishes. Requires `--new-tab` or `--tab` |
| `--callback-tab <id>` | Specific caller tab to wake. Default: the tab that ran `dispatch`, else a new tab |
| `--callback-prompt <text>` | Replace the default wake-up prompt body. `{{DISPATCH_*}}` variables below are substituted |
| `--callback-timeout <seconds>` | Give up and fire a `timeout` callback after this long. Default 3600, hard cap 86400 |

**Semantics**

* **Correlated.** The callback is bound to the `(target agent, target tab)` pair established at dispatch time, and only arms once the dispatched process actually starts. Other tabs of the same agent, and a predecessor turn a `--queue`d dispatch is waiting behind, never trigger it. This is why an explicit `--new-tab` or `--tab` is required.
* **Fires exactly once**, on final completion. A second exit is a no-op.
* **Auto Run aware.** If the dispatched prompt starts an Auto Run, the callback waits for the whole batch, not for task 1. A 6-task run wakes the caller once.
* **Retry aware.** If the provider refuses the turn for quota or availability and Agent Resilience holds it for a resend, the callback waits for the resend and reports how that went. It reports `failed` only if the retry is stopped or given up, and the callback timeout still applies while it waits.
* **Carries a handle, not just a slice.** The inlined result is capped at 5000 characters (same as Cue's `{{CUE_SOURCE_OUTPUT}}`); `{{DISPATCH_TARGET_ID}}` and `{{DISPATCH_TAB_ID}}` let the caller read the untruncated transcript with `maestro-cli session show <tabId>`.
* **Busy-safe delivery.** The wake-up turn goes through the same execution queue `dispatch --queue` uses, so a busy caller gets it on its next idle turn instead of having it dropped or interleaved.
* **Lands where it was asked for.** The wake-up goes to the tab that ran `dispatch` (or `--callback-tab`). When there is no such tab, because the dispatch came from a Cue or bot run, from your own shell, or the tab was closed meanwhile, it opens a new background tab in the caller agent. It never lands in whatever tab happens to be active.
* **Self-cleaning.** Entries live in a main-process registry, never in `cue.yaml`. They expire on timeout and are dropped when the dispatch is rejected. They do not survive a desktop restart.
* **Non-blocking.** The dispatching turn ends normally; the callback opens a new turn later.
* **Shown as a result card.** In the caller's transcript the wake-up is a collapsed card, not the raw prompt: the agent it came from, the exit code, the duration, and Auto Run task counts. Click it to read a short preview of the result, with a link to the source tab for the full transcript. The agent still receives the full prompt. A custom `--callback-prompt` shows as plain text.

**Callback prompt variables** (usable in `--callback-prompt`):

`{{DISPATCH_CALLBACK_ID}}`, `{{DISPATCH_TARGET_ID}}`, `{{DISPATCH_TARGET_NAME}}`, `{{DISPATCH_TAB_ID}}`, `{{DISPATCH_STATUS}}` (`completed` | `failed` | `timeout` | `cancelled`), `{{DISPATCH_EXIT_CODE}}`, `{{DISPATCH_DURATION}}`, `{{DISPATCH_OUTPUT}}`, `{{DISPATCH_OUTPUT_TRUNCATED}}`, `{{DISPATCH_TASKS_COMPLETED}}`, `{{DISPATCH_TASKS_TOTAL}}`, `{{DISPATCH_PROMPT}}`.

> [!NOTE]
>
> `{{DISPATCH_OUTPUT}}` is another agent's output landing in your agent's prompt - the same trust model as Cue's `{{CUE_SOURCE_OUTPUT}}` and cross-agent consults. The default wrapper fences it and labels it as untrusted data. Keep that fencing if you supply your own `--callback-prompt`.

Additional error cases: a callback agent that cannot be resolved (`AGENT_NOT_FOUND`), a callback that targets the dispatch tab itself, a tab that already has an armed callback (`CALLBACK_ALREADY_ARMED`), and callback flags passed without `--notify-on-complete` (all `INVALID_OPTIONS`).

### Dispatching from Inside an Auto Run

An Auto Run task (either mode) runs with `MAESTRO_CALLER_AUTORUN_ID` set, and `dispatch` reads it. There is no flag to pass:

* A dispatch that names no destination (no `--tab`, `--new-tab`, `--queue`, `--force`, or `--notify-on-complete`) goes to a **new hidden tab**, as if `--new-tab` were passed.
* A dispatch with `--new-tab` or `--tab` is **tracked by the run**: the run waits for it before its next task or iteration, and feeds the result into that turn's prompt. See [Delegating to Other Agents](https://docs.runmaestro.ai/autorun-playbooks.md#delegating-to-other-agents).
* `--callback-timeout <seconds>` bounds that wait (default 3600, hard cap 86400). `--callback-tab` and `--callback-prompt` still require `--notify-on-complete`, which takes over: an explicit callback wakes its tab instead of reporting to the run.

The reply says whether the run tracks the dispatch:

```json theme={"theme":"dracula"}
{
	"success": true,
	"agentId": "worker-...",
	"tabId": "tab-xyz",
	"callbackId": "cb_01j...",
	"autoRunTracked": true
}
```

`"autoRunTracked": false` means the work was handed over but the run will not wait for it: it had no tab to correlate (`--queue` to the active tab), the tab already carried a callback, or the run had already ended. A note on stderr says the same. `auto-run-status -a <agent>` lists the delegations a run is waiting on.

### Listing Sessions

Browse an agent's session history, sorted most recent to oldest. Supports pagination with limit/skip and keyword search.

```bash theme={"theme":"dracula"}
# List the 25 most recent sessions
maestro-cli list sessions <agent-id>

# Limit to 10 results
maestro-cli list sessions <agent-id> -l 10

# Paginate: skip the first 25, show next 25
maestro-cli list sessions <agent-id> -k 25

# Page 3 of 10-item pages
maestro-cli list sessions <agent-id> -l 10 -k 20

# Search for sessions by keyword (matches session name and first message)
maestro-cli list sessions <agent-id> -s "authentication"

# Combine limit, skip, and search with JSON output
maestro-cli list sessions <agent-id> -l 50 -k 0 -s "refactor" --json
```

| Flag | Description | Default |
| - | - | - |
| `-l, --limit <count>` | Maximum number of sessions to return | 25 |
| `-k, --skip <count>` | Number of sessions to skip (for pagination) | 0 |
| `-s, --search <keyword>` | Filter by keyword in session name or first message | - |
| `--json` | Output as JSON | - |

JSON output includes full session metadata:

```json theme={"theme":"dracula"}
{
	"success": true,
	"agentId": "a1b2c3d4-...",
	"agentName": "My Agent",
	"totalCount": 42,
	"filteredCount": 3,
	"sessions": [
		{
			"sessionId": "abc123",
			"sessionName": "Auth refactor",
			"modifiedAt": "2026-02-08T10:00:00.000Z",
			"firstMessage": "Help me refactor the auth module...",
			"messageCount": 12,
			"costUsd": 0.05,
			"inputTokens": 5000,
			"outputTokens": 2000,
			"durationSeconds": 300,
			"starred": true
		}
	]
}
```

Currently supported for `claude-code` agents.

### Session Inspection

Inspect open AI tabs across the running Maestro desktop app and read their conversation history. Pair `dispatch --new-tab` (writes, returns a `tabId`) with `session show <tabId>` (reads, supports `--since` and `--tail`) to build a stateless poll loop without owning a persistent connection - used by Maestro-Discord and Cue follow-ups.

Both verbs talk to the running desktop over the same WebSocket as `dispatch`. There is no on-disk fallback: if the app is not running, the CLI reports `MAESTRO_NOT_RUNNING` and exits `3`.

#### List Open Tabs

Flatten the open tabs across every Maestro agent into addressable entries. By default the list holds the AI tabs the tab strips draw, so its count matches the screen:

```bash theme={"theme":"dracula"}
# Default: compact text (one tab per line)
maestro-cli session list

# JSON for scripting
maestro-cli session list --json

# Hidden tabs only, visible plus hidden, or every tab with its visibility
maestro-cli session list --hidden
maestro-cli session list --include-hidden --json
maestro-cli session list --all

# File, browser, and terminal tabs too (or one kind: file, browser, terminal)
maestro-cli session list --type all
```

Every entry carries a `visibility`:

| `visibility` | Meaning |
| - | - |
| `visible` | The tab strip draws a chip for it, standalone or inside a tiled group |
| `hidden` | A real tab the tab bar does not show, such as the transcript a `maestro-cli ask` consult leaves behind |
| `orphaned` | The tab has no slot in the strip at all: a close that did not fully apply. Maestro clears these at startup |

The default lists `visible` tabs only; `--hidden` lists the hidden ones, `--include-hidden` lists both, and `--all` adds orphans. `session list --type all` with no scope flag counts the same tabs as the Usage Dashboard **Open Tabs** card. AI entries also carry `hidden` and `inTabOrder` (whether the agent's tab order holds a ref for the tab; a tab tiled into a group has none but is still on screen).

Default text columns: `state` (`busy` / `idle`), star (`★` if starred), `tabId`, agent name + id, tab name, `createdAt` (relative), and `[hidden]` or `[orphaned: ...]` on a tab that is not visible. A file, browser, or terminal row shows its kind, `*` if it is the agent's selected tab of that kind, `tabId`, agent, name, and the file path, URL, or shell directory. One tab per line so the output pipes cleanly into `grep`, `awk`, etc. A last line counts the tabs the chosen scope left out.

JSON envelope. `scope` is `visible`, `hidden`, `visible+hidden`, or `all`; `type` is the `--type` value; `counts` holds every tab of the chosen type by visibility, whatever the scope listed; `visibilityReported` is `false` when the running Maestro is too old to tell hidden tabs apart. AI tabs are always in `sessions`. With a `--type` other than `ai`, the file, browser, and terminal tabs are in `tabs`:

```json theme={"theme":"dracula"}
{
	"success": true,
	"scope": "visible",
	"type": "all",
	"counts": { "visible": 567, "hidden": 528, "orphaned": 0 },
	"visibilityReported": true,
	"sessions": [
		{
			"tabId": "tab-1",
			"sessionId": "tab-1",
			"agentId": "a1b2c3d4-...",
			"agentName": "Backend",
			"toolType": "claude-code",
			"name": "Refactor parser",
			"agentSessionId": "claude-uuid-1",
			"state": "idle",
			"createdAt": 1714268000000,
			"starred": false,
			"hidden": false,
			"inTabOrder": true,
			"visibility": "visible"
		}
	],
	"tabs": [
		{
			"tabId": "f1e2d3c4-...",
			"tabType": "file",
			"agentId": "a1b2c3d4-...",
			"agentName": "Backend",
			"name": "README.md",
			"target": "/repo/README.md",
			"active": false,
			"visibility": "visible"
		}
	]
}
```

To extract just `tabId`s with `jq`: `maestro-cli session list --json | jq '.sessions[].tabId'`.

#### Show Conversation History

Print a tab's conversation log, with optional cursor (`--since`) and cap (`--tail`) filters applied desktop-side so the wire payload stays small even on long conversations.

```bash theme={"theme":"dracula"}
# Default: formatted transcript (header + per-message blocks)
maestro-cli session show <tab-id>

# JSON for scripting
maestro-cli session show <tab-id> --json

# Only messages newer than an ISO-8601 timestamp
maestro-cli session show <tab-id> --since "2026-04-28T10:00:00Z"

# `--since` also accepts a bare epoch number (auto-detects ms vs sec by magnitude,
# so both `Date.now()` and `Date.now() / 1000` cursors work without a unit flag)
maestro-cli session show <tab-id> --since 1714268000

# Cap at the last N messages (applied after `--since`)
maestro-cli session show <tab-id> --tail 20

# Combine cursor + cap for poll loops
maestro-cli session show <tab-id> --since "$LAST_TS" --tail 50
```

| Flag | Description |
| - | - |
| `--since <timestamp>` | Only return messages strictly after this timestamp (ISO-8601, or epoch ms/sec auto-scaled) |
| `--tail <n>` | Cap output to the last N messages (non-negative integer; applied after `--since`) |
| `--json` | Output as JSON (default is a formatted transcript) |

JSON shape:

```json theme={"theme":"dracula"}
{
	"success": true,
	"tabId": "tab-1",
	"sessionId": "tab-1",
	"agentId": "a1b2c3d4-...",
	"agentSessionId": "claude-uuid-1",
	"messages": [
		{
			"id": "log-1",
			"role": "user",
			"source": "user",
			"content": "Hello",
			"timestamp": "2026-04-28T10:00:00.000Z"
		},
		{
			"id": "log-2",
			"role": "assistant",
			"source": "ai",
			"content": "Hi there",
			"timestamp": "2026-04-28T10:00:01.000Z"
		}
	]
}
```

`role` is a coarse classification (`user` | `assistant` | `system` | `tool` | `thinking` | `error` | `unknown`) so conversational consumers can branch on intent; the raw `source` is preserved alongside for callers that need to discriminate further. ISO timestamps are emitted verbatim so a `messages[-1].timestamp` from one call can be fed directly back into `--since` on the next.

Error codes: `MISSING_TAB_ID`, `TAB_NOT_FOUND`, `INVALID_OPTION`, `MAESTRO_NOT_RUNNING`, `COMMAND_FAILED`. All errors are emitted as `{ "success": false, "error": "...", "code": "..." }` with exit code `1`, except `MAESTRO_NOT_RUNNING`, which exits `3`.

### Pasted Images (`image list` / `image save`)

An image pasted into a Maestro chat reaches the agent as pixels in its context: the agent can see the screenshot, but it has no path to the file, so "save that to the repo" used to be a right-click only you could perform. These two verbs give the agent the same reach.

```bash theme={"theme":"dracula"}
# What has been pasted, newest first
maestro-cli image list --limit 5
maestro-cli image list -a <agent-id> -t <tab-id> --json

# The most recent image, into the current working directory
maestro-cli image save

# By index (from `image list`) or by handle, to an exact path
maestro-cli image save 3 -o docs/screenshots/dashboard.png
maestro-cli image save 9ca2e320 -o assets/

# Every image in one conversation, into a folder
maestro-cli image save --all -t <tab-id> -o screenshots/
```

`image list` prints one image per line: index, handle, age, agent, tab, and the first line of the message it came in on.

```
  1  9ca2e320  2m ago        Maestro  Discord Message Bus  why wasn't this picked up by our Cue pipeline?
  2  f8d010b2  9h ago        Kensho   Fibonacci Ingest     notes from a verbal session, see the image
```

| Flag | Command | Description |
| - | - | - |
| `-a, --agent <id>` | both | Only this agent (defaults to every agent) |
| `-t, --tab <tab-id>` | both | Only this AI tab |
| `--limit <n>` | `list` | Maximum images to show (default: 20) |
| `-o, --output <path>` | `save` | File or directory to write (default: a generated name in the cwd) |
| `--all` | `save` | Save every image in scope instead of just the newest |
| `--force` | Alias for `--accept-translation-limitations` | - |
| `--json` | both | Output as JSON (for scripting) |

Details worth knowing:

* **Scope it with `-a` / `-t`.** With neither, the scope is every agent, so "the newest image" is whatever was pasted most recently anywhere in the fleet. An agent saving its own conversation's screenshot should pass its own agent id.
* **The target is an index, a handle, or `latest`** (the default). A handle is the leading hex of the image's content hash, which is stable, so it keeps addressing the same picture as newer images push the indexes down.
* **The extension follows the bytes, not the name you asked for.** Saving a JPEG as `shot.png` writes `shot.jpg`, because an extension that lies about the encoding is a file every downstream decoder rejects. The path actually written is what the command prints.
* **Nothing is overwritten by accident.** A generated name that collides gets a `-2`, `-3` suffix; an explicit `--output` that already exists fails until you pass `--force`.
* **With `--all`, `--output` is always a folder** and is created if it does not exist, even when the scope happens to hold a single image.
* **The Files panel refreshes itself.** After writing, `image save` nudges the tree for whichever agents own the written paths, so the image appears without waiting for the panel's timed refresh (`--json` reports them as `refreshedAgents`). The nudge is best-effort: the bytes are already on disk, so a closed desktop is not a failed save.
* **Reads come from disk, not the running app**, so these work with the desktop closed. The cost is the renderer's two-second persistence debounce: an image pasted this instant may not be on disk yet, and `image save` says so rather than guessing.

Error codes: `AGENT_NOT_FOUND`, `NO_IMAGES`, `IMAGE_NOT_FOUND`, `AMBIGUOUS_IMAGE`, `IMAGE_MISSING`, `FILE_EXISTS`, `WRITE_FAILED`, `INVALID_USAGE`.

### Timeline and User Journey

`timeline` shows what happened around an agent in one list, oldest first: agent turns from [History](https://docs.runmaestro.ai/history.md), your actions in Maestro from the [User Journey](https://docs.runmaestro.ai/history.md#user-journey), and git commits. It shows only the newest events, and ends with the commands that read more. Both verbs read from disk, so they work while the desktop app is closed.

```bash theme={"theme":"dracula"}
# The last day for one agent (default: --since 1d, newest 30 events)
maestro-cli timeline --agent <agent-id>

# Every agent, the last two hours, only lines that match
maestro-cli timeline --since 2h --grep "tooltip"

# Choose the sources: history, journey, git, computer
maestro-cli timeline --agent <agent-id> --sources history,git --tail 50

# Open one turn in full by the [entry <id>] handle a timeline line shows
maestro-cli timeline show 1a2b3c4d

# Your actions alone, filtered by kind
maestro-cli journey --agent <agent-id> --kind file.save,browser.navigate --tail 20
```

A history line looks like `2:02 PM history USER (Fix tooltip): fixed clipping [entry 1a2b3c4d]`. Commit lines carry a `[commit <sha>]` handle for `git show`.

| Option (`timeline`) | Meaning |
| - | - |
| `--agent <id>` | Agent ID or name. Without it, every agent |
| `--since`, `--until` | `30m`, `2h`, `1d`, `1w`, ISO-8601, or epoch. Default: the last day |
| `--sources <list>` | Default `history,journey,git`. `computer` needs [Computer History](https://docs.runmaestro.ai/computer-history.md) on |
| `--tail <n>` | Only the newest N events (default 30) |
| `--per-source <n>` | Only the newest N events of each source (default 15) |
| `--grep <text>` | Only events whose line matches (regex, case-insensitive) |
| `--json` | JSON output |

`journey` kinds are `file.open`, `file.close`, `file.save`, `file.create`, `file.rename`, `file.delete`, `browser.open`, `browser.navigate`, and `browser.close`. It also takes `--since` (ISO-8601 or epoch), `--tail` (per agent), and `--json`. Prompts can read an agent's journey file through the `{{AGENT_JOURNEY_PATH}}` template variable.

### Creating, Updating, and Removing Agents

Create, mutate, or delete agents directly from the command line. Requires the Maestro desktop app to be running.

```bash theme={"theme":"dracula"}
# Create a Claude Code agent with a working directory
maestro-cli create-agent "My Agent" -d /path/to/project

# Create a Codex agent with custom model and environment variables
maestro-cli create-agent "Codex Worker" -d . -t codex --model gpt-5.3-codex --env API_KEY=abc123

# Create an agent with SSH remote execution
maestro-cli create-agent "Remote Agent" -d /home/user/project -t claude-code --ssh-remote <remote-id>

# Create an agent with all options
maestro-cli create-agent "Full Config" -d /workspace \
	-t claude-code \
	-g <group-id> \
	--nudge "Always write tests" \
	--new-session-message "You are a senior engineer working on project X" \
	--custom-path /usr/local/bin/claude \
	--custom-args "--verbose" \
	--env DEBUG=true --env LOG_LEVEL=info \
	--model opus \
	--effort high \
	--context-window 200000 \
	--provider-path /custom/provider \
	--ssh-remote <remote-id> \
	--ssh-cwd /remote/workdir \
	--auto-run-folder ~/playbooks/full-config

# Duplicate an agent the way the Left Bar's "Duplicate..." does
maestro-cli duplicate-agent <agent-id>

# Duplicate into another directory and group, under a new name
maestro-cli duplicate-agent <agent-id> --name "Reviewer" --cwd ../other-repo -g <group-id> --json

# Remove an agent
maestro-cli remove-agent <agent-id>

# Rename an agent
maestro-cli rename-agent <agent-id> "New Name"

# Move an agent into a group (use "none" to ungroup)
maestro-cli update-agent <agent-id> --group <group-id>
maestro-cli update-agent <agent-id> --group none

# Change an agent's working directory (refused while the agent process is running)
maestro-cli update-agent <agent-id> --cwd /new/path/to/project

# Combine both in a single call
maestro-cli update-agent <agent-id> --group <group-id> --cwd /new/path

# Edit the agent's settings - the same fields as the Edit Agent modal
maestro-cli update-agent <agent-id> --nudge "Always write tests"
maestro-cli update-agent <agent-id> --new-session-message "You are a senior engineer"
maestro-cli update-agent <agent-id> --model opus --effort high --context-window 200000
maestro-cli update-agent <agent-id> --env DEBUG=true --env LOG_LEVEL=info
maestro-cli update-agent <agent-id> --custom-path /usr/local/bin/claude --custom-args "--verbose"

# Clear a field by passing an empty string; --clear-env empties the env map
maestro-cli update-agent <agent-id> --nudge ""
maestro-cli update-agent <agent-id> --clear-env

# Set the Claude token source (Claude Code agents only): api | tui | dynamic
maestro-cli update-agent <agent-id> --token-source tui

# Switch provider without converting (tabs keep transcripts, start fresh on Codex)
maestro-cli update-agent <agent-id> --provider codex

# Review native provider translation before applying it (desktop required)
maestro-cli update-agent <agent-id> --provider codex --dry-run --json

# Apply the reviewed plan, then inspect its operation state
maestro-cli update-agent <agent-id> --provider codex --migration-plan <plan-id> --accept-translation-limitations --json
maestro-cli update-agent <agent-id> --migration status --migration-plan <plan-id> --json

# Opt a Codex agent into the experimental app-server transport (enables steering)
maestro-cli update-agent <agent-id> --codex-transport app-server

# Update SSH execution config (use "none" to revert to local)
maestro-cli update-agent <agent-id> --ssh-remote <remote-id> --ssh-cwd /remote/workdir
maestro-cli update-agent <agent-id> --ssh-remote none
maestro-cli update-agent <agent-id> --sync-history-to-remote true
```

`update-agent` mutates an existing agent in place, writing the same live desktop Session the Edit Agent modal edits (not the per-agent config store that `settings agent set` writes). Read the current values back with `maestro-cli show agent <id> --json`.

The group update reuses the same write path as drag-and-drop in the Left Bar. The cwd update moves the agent as a whole: the working directory, the project root the Files panel and Edit dialog read, and an Auto Run folder that lives inside the old directory all follow the new path (an Auto Run folder elsewhere is left where you put it). Provider conversations stored under the old path may not resume from the new one. Stop the agent before changing its cwd or SSH config; the underlying PTY's working directory and spawn target are fixed at launch time, so the renderer refuses those updates while the agent is busy or its process is alive and surfaces the reason on stderr. The remaining settings (nudge, messages, model, effort, env, token source, etc.) are spawn-time values and apply on the next launch, so they are accepted even while the agent is running.

For text fields, passing an empty string (for example `--nudge ""`) clears the field. `--env` replaces the environment map with the provided pairs; `--clear-env` empties it. `--context-window 0` (or `none`) clears the context-window override. `--token-source` only carries meaning for Claude Code agents: `api` uses `claude --print` (per-token API credit), `tui` drives the maestro-p TUI (Max-plan quota), and `dynamic` starts on the TUI and falls back to API when a usage window hits its limit. The `tui` and `dynamic` modes need the [maestro-p helper](https://runmaestro.ai/maestro-p/) on PATH; it is bundled locally, but for SSH remotes it must be installed on the remote host. See [Provider Notes](https://docs.runmaestro.ai/provider-notes.md#token-source-max-plan-vs-api). `--codex-transport` only carries meaning for Codex agents: `exec` (the default) runs `codex exec`, and `app-server` is an experimental opt-in that lets a running chat turn be steered, on this machine or an SSH remote (which needs a `codex` there that has `app-server`). Image, Auto Run, and Cue turns keep using `codex exec` either way.

`--provider` on its own is a plain switch, the same as Edit Agent with **Convert memory and session history** unchecked: tabs keep their transcripts, each starts a fresh conversation on the new provider, and switching back resumes the old one. Provider-specific settings are parked per provider and restored on the way back. JSON output reports `converted: false` and any `notices` (queued messages whose model or effort could not carry across).

`--convert` opts into the desktop's native conversation translation flow; every translation option below implies it. Review it with `--dry-run --json`, take the returned `plan.id`, then apply that ID with `--migration-plan` and `--accept-translation-limitations` if you accept the reported limits (`--force` is an alias). Acceptance does not bypass a blocked plan. `--migration` supports `plan`, `apply`, `status`, `recover`, and `rollback`; `--translation-resource` selects an individual user resource and is repeatable. Tabs, transcripts, drafts, queued messages, and file previews are preserved. This changes the agent's active provider. Inspect the reported state and exit status before reporting completion; a deferred or failed switch exits nonzero. Provider translation requires a matching desktop build and is refused by a headless host without changing agent state. See [Provider Notes](https://docs.runmaestro.ai/provider-notes.md#switching-providers-with-memory-and-session-carry) for supported versions, live evidence, and remaining limitations.

| Flag | Description | Default |
| - | - | - |
| `-g, --group <id>` | Move the agent to this group; supports partial IDs. Use `none` (or `null`) to ungroup | - |
| `-d, --cwd <path>` | New working directory (resolved to absolute). Agent must be stopped | - |
| `--ssh-remote <id>` | SSH remote for remote execution. Use `none` to revert to local. Agent must be stopped | - |
| `--ssh-cwd <path>` | Working directory override on the SSH remote. Agent must be stopped | - |
| `--sync-history-to-remote <bool>` | Sync history entries to `.maestro/history/` on the remote host | - |
| `--nudge <message>` | Nudge message appended to every message. Empty string clears | - |
| `--new-session-message <message>` | Message prefixed to the first message of new sessions. Empty string clears | - |
| `--custom-path <path>` | Override the agent binary path. Empty string clears | - |
| `--custom-args <args>` | Custom CLI arguments. Empty string clears | - |
| `--env <KEY=VALUE>` | Set an environment variable (repeatable; replaces the env map) | - |
| `--clear-env` | Clear all per-agent environment variables | - |
| `--model <model>` | Model override (e.g. sonnet, opus). Empty string clears | - |
| `--effort <level>` | Effort/reasoning level override. Empty string clears | - |
| `--context-window <size>` | Context window size in tokens. `0` or `none` clears | - |
| `--token-source <mode>` | Claude Code token source: `api`, `tui`, or `dynamic` (Claude Code agents only) | - |
| `--maestro-p-path <path>` | Override the maestro-p binary path. Empty string clears | - |
| `--codex-transport <transport>` | Codex transport: `exec` (standard) or `app-server` (experimental, enables steering a running turn). Codex agents only | - |
| `--provider <type>` | Switch the agent to another provider without converting (desktop required) | - |
| `--convert` | With `--provider`: convert native conversations and project memory too (opt-in) | - |
| `--dry-run` | Plan translation without native writes; requires `--provider` | - |
| `--accept-translation-limitations` | Accept the reported conversion limits; blocked plans remain blocked | - |
| `--migration <action>` | Plan, apply, inspect status, recover, or roll back a migration | - |
| `--migration-plan <id>` | Apply a reviewed plan or inspect, recover, or roll back a specific operation | - |
| `--translation-resource <path>` | Include one selected user resource; repeatable, without importing account-global data | - |
| `--force` | Alias for `--accept-translation-limitations` | - |
| `--json` | Machine-readable JSON output | - |

The flag table below covers `create-agent`:

| Flag | Description | Default |
| - | - | - |
| `-d, --cwd <path>` | Working directory for the agent (required) | - |
| `-t, --type <type>` | Agent type (claude-code, codex, opencode, factory-droid) | `claude-code` |
| `-g, --group <id>` | Group ID to assign the agent to | - |
| `--nudge <message>` | Nudge message appended to every user message | - |
| `--new-session-message <message>` | Message prefixed to first message in new sessions | - |
| `--custom-path <path>` | Custom binary path for the agent CLI | - |
| `--custom-args <args>` | Custom CLI arguments | - |
| `--env <KEY=VALUE>` | Environment variable (repeatable) | - |
| `--model <model>` | Model override (e.g., sonnet, opus) | - |
| `--effort <level>` | Effort/reasoning level override | - |
| `--context-window <size>` | Context window size in tokens | - |
| `--provider-path <path>` | Custom provider path | - |
| `--ssh-remote <id>` | SSH remote ID for remote execution | - |
| `--ssh-cwd <path>` | Working directory override on the SSH remote | - |
| `--auto-run-folder <path>` | Auto Run / playbooks folder for this agent | `<cwd>/.maestro/playbooks` |
| `--background` | Create the agent without selecting it in the Left Bar | - |
| `--focus` | Select the new agent after creating it (default) | - |
| `--json` | Machine-readable JSON output | - |

`duplicate-agent <agent>` copies what the Left Bar's **Duplicate...** copies, through the same rules the New Agent modal prefills from: provider, working directory, group, additional directories, nudge and new session messages, custom path, args, env vars, model, effort, context window and provider path, Adaptive Mode, Agent Resilience, Codex automatic resets and transport, and the SSH remote. It does not copy tabs, history, the Auto Run folder (the copy gets `<cwd>/.maestro/playbooks`), or SSH history-sync flags. A name already in use is refused, as in the modal; sharing the source's directory prints a warning. The Pianola manager cannot be duplicated. Read the copy back with `show-agent <new-id>`.

| Flag | Description | Default |
| - | - | - |
| `-n, --name <name>` | Name for the copy | `<source name> (Copy)` |
| `-g, --group <id>` | Group ID or prefix for the copy | the source's group |
| `-d, --cwd <path>` | Working directory for the copy; a remote path, taken as typed, for an SSH agent | the source's directory |
| `--background` | Create the copy without selecting it in the Left Bar | - |
| `--focus` | Select the copy after creating it (default) | - |
| `--json` | Machine-readable JSON output | - |

### Creating, Updating, and Removing Groups

Manage Left Bar groups from the command line, including their appearance and nesting, so a bootstrap script or CI job can reproduce a whole workspace layout without anyone clicking through the desktop UI. Requires the Maestro desktop app to be running. Use a group ID with `create-agent -g` or `update-agent --group` to place agents into it, and `update-agent --group none` to move an agent back out.

```bash theme={"theme":"dracula"}
# Create a group
maestro-cli create-group "Backend"

# Create a group with an emoji icon
maestro-cli create-group "Backend" -e 🔧

# Create a group with a built-in icon and a label color
maestro-cli create-group "Backend" --icon rocket --color '#EF4444'

# Create a group nested inside a root group
maestro-cli create-group "API" --parent <root-group-id>

# Machine-readable output (returns the new group ID and its stored appearance)
maestro-cli create-group "Backend" --json

# Change a group's name, icon, and color
maestro-cli update-group <group-id> --name "Frontend" --icon layers --color '#3B82F6'

# Move a group inside a root group, or promote it back to the top level
maestro-cli update-group <group-id> --parent <root-group-id>
maestro-cli update-group <group-id> --clear-parent

# Remove appearance you set earlier
maestro-cli update-group <group-id> --clear-icon --clear-color

# Fold a group in the Left Bar, or unfold it
maestro-cli update-group <group-id> --collapse
maestro-cli update-group <group-id> --expand

# Hide a group from the Left Bar (its agents stay reachable), or show it again
maestro-cli update-group <group-id> --hide
maestro-cli update-group <group-id> --show

# Remove an (empty) group
maestro-cli remove-group <group-id>

# Remove a group that still has agents (ungroups them first)
maestro-cli remove-group <group-id> --force

# Rename a group (kept for backward compatibility; update-group --name does the same)
maestro-cli rename-group <group-id> "Frontend"
```

Removing a group never deletes the agents inside it: the desktop ungroups any members (moves them to no group) and then removes the group. `remove-group` refuses a non-empty group unless you pass `--force`, so you don't accidentally scatter a populated group. Group IDs support partial-ID resolution.

#### Group appearance

`--emoji` and `--icon` are mutually exclusive: a group shows one or the other. `--color` combines with either, and it is also fine on its own.

Built-in icon IDs: `folder`, `briefcase`, `rocket`, `code`, `star`, `heart`, `lightbulb`, `target`, `calendar`, `book`, `layers`, `shield`, `wrench`, `palette`, `archive`, `zap`. Icons contributed by a plugin use their namespaced ID (`my-plugin/my-pack/my-icon`) and round-trip unchanged.

Colors are `#RRGGBB` hex values, normalized to uppercase before they are stored, or a plugin's namespaced color ID.

Notes on behavior:

* **Nothing half-applies.** Every flag is validated before the command talks to the desktop, so an invalid icon or color leaves the group exactly as it was.
* **Clearing is explicit.** Passing `--icon` never silently drops an emoji you set earlier, and vice versa; use the `--clear-*` flags to remove a value. `--clear-emoji` restores the default folder emoji. `--clear-parent` promotes a nested group to the top level.
* **Writes are verified.** After the desktop reports success, the CLI reads the group back from storage and confirms it matches what you asked for. If a desktop app older than your CLI accepted the command and ignored the icon or color, the command fails with a version-mismatch message instead of reporting a success that did not happen.
* **Icon and color survive the Groups+ feature gate.** Turning Groups+ off falls back to the legacy emoji presentation but does not discard stored icon and color; turning it back on restores them.
* Group nesting is one level deep: a root group can hold child groups, but a child group cannot hold its own children.

`maestro-cli list groups --json` reports `icon`, `color`, `parentGroupId`, and `collapsed` alongside the existing fields, so a script can read back exactly what it set.

There is no reorder verb: the Left Bar sorts groups and agents by name, and a drag only changes membership. Move an agent with `update-agent --group` (its worktree children travel with it), and a group with `update-group --parent` / `--clear-parent`.

`create-group` flags:

| Flag | Description | Default |
| - | - | - |
| `-e, --emoji <emoji>` | Emoji icon for the group. Mutually exclusive with `--icon` | - |
| `--icon <icon-id>` | Built-in icon ID or a plugin icon ID. Mutually exclusive with `--emoji` | - |
| `--color <color>` | Label color as `#RRGGBB`, or a plugin color ID | - |
| `--parent <group-id>` | Create inside this root group | - |
| `--json` | Machine-readable JSON output | - |

`update-group` flags:

| Flag | Description | Default |
| - | - | - |
| `-n, --name <name>` | New group name | - |
| `-e, --emoji <emoji>` | Emoji icon for the group. Mutually exclusive with `--icon` | - |
| `--icon <icon-id>` | Built-in icon ID or a plugin icon ID. Mutually exclusive with `--emoji` | - |
| `--color <color>` | Label color as `#RRGGBB`, or a plugin color ID | - |
| `--parent <group-id>` | Move the group inside this root group | - |
| `--clear-emoji` | Reset the emoji to the default folder | - |
| `--clear-icon` | Remove the icon | - |
| `--clear-color` | Remove the label color | - |
| `--clear-parent` | Promote the group to the top level | - |
| `--collapse` | Fold the group in the Left Bar. Mutually exclusive with `--expand` | - |
| `--expand` | Unfold a collapsed group in the Left Bar | - |
| `--json` | Machine-readable JSON output | - |

`remove-group` flags:

| Flag | Description | Default |
| - | - | - |
| `-f, --force` | Delete even if the group still has agents (ungroups them) | - |
| `--json` | Machine-readable JSON output | - |

### Moving Agents and Groups Between Windows (`window`)

The CLI half of the Left Bar's **Move to Window** menus. `move-agent` carries one agent with its worktrees; `move-group` carries every agent in a group (and its subgroups when Groups+ nesting is on), gathering a group that is split across windows into one. The primary window answers through the same code path as a click, so the same rule applies: a move that would leave the main window with no agents is refused.

```bash theme={"theme":"dracula"}
# See which windows exist and what each holds
maestro-cli window list

# Pull a whole group out into a new window
maestro-cli window move-group <group-id> --to new

# Bring an agent back to the main window, or into window 2 / a named window
maestro-cli window move-agent <agent-id> --to main
maestro-cli window move-agent <agent-id> --to 2
maestro-cli window move-agent <agent-id> --to "Research"
```

`--to` takes `new`, `main`, a window number (as shown by `window list` and the Left Bar badge), a window id, or a custom window name. Agent and group IDs accept the usual partial-ID resolution. Moving onto the window that already holds everything succeeds and moves nothing.

| Flag | Description | Default |
| - | - | - |
| `--to <window>` | Destination (required for `move-agent` / `move-group`) | - |
| `--json` | Machine-readable JSON output | - |

### Creating Worktree Agents

Branch a new agent off an existing parent agent into its own git worktree, without an Auto Run playbook. This mirrors the desktop "create worktree" flow: the parent agent must already exist in the running app, the desktop creates the worktree on disk and a child session linked to the parent, then hands back the new agent's ID.

```bash theme={"theme":"dracula"}
# Create a worktree agent off a parent, on a new branch
maestro-cli create-worktree -a <parent-agent-id> -b feature/new-thing

# Base the new branch on a specific ref when it does not yet exist
maestro-cli create-worktree -a <parent-agent-id> -b feature/new-thing --base-branch rc

# Create the worktree and immediately dispatch an initial prompt to it
maestro-cli create-worktree -a <parent-agent-id> -b feature/new-thing -m "Start on the API layer"
```

The worktree is created in the parent agent's configured Worktree Directory (`show agent <id> --json` reports it as `worktreeBasePath`), so it appears in the Left Bar like one made from the desktop. This is the only supported way for an agent to create a worktree: a bare `git worktree add` produces a checkout the desktop never learns about.

The optional `--message` is delivered to the new agent as a plain prompt (not an Auto Run loop) on the same connection, addressed by the ID the desktop just returned. Both `--agent` and `--branch` support the usual partial-ID resolution.

| Flag | Description | Default |
| - | - | - |
| `-a, --agent <id>` | Parent agent ID the worktree branches from (required) | - |
| `-b, --branch <name>` | Branch name for the worktree, created if it does not exist (required) | - |
| `--base-branch <name>` | Ref the new branch is based on when it does not yet exist (e.g. `rc`, `main`) | parent repo HEAD |
| `-m, --message <text>` | Optional initial prompt dispatched to the new agent after creation | - |
| `--background` | Create the agent without selecting it in the Left Bar | - |
| `--focus` | Select the new worktree agent after creating it (default) | - |
| `--json` | Machine-readable JSON output | - |

### Driving the Workspace (Focus, Mode, Tabs)

Steer the desktop UI itself: focus an agent, flip an agent between AI and terminal mode, and manage an agent's AI tabs. These mirror clicking around the app and require the desktop app to be running.

```bash theme={"theme":"dracula"}
# Focus (select) an agent in the Left Bar; optionally focus a specific tab
maestro-cli focus-agent <agent-id>
maestro-cli focus-agent <agent-id> --tab <tab-id>

# Switch an agent between AI chat and terminal mode
maestro-cli switch-mode <agent-id> ai
maestro-cli switch-mode <agent-id> terminal

# Open a new tab for an agent (optionally seed an AI tab with a prompt)
maestro-cli tab new -a <agent-id>
maestro-cli tab new -a <agent-id> --prompt "Start reviewing the API layer"

# Create the tab without taking the view from whoever is working
maestro-cli tab new -a <agent-id> --background

# Close, rename, star, or unstar a tab. The owning agent is resolved from the
# tab ID automatically, so you only need the tab ID (exact or a unique prefix).
maestro-cli tab close <tab-id>
maestro-cli tab rename <tab-id> "Docs"
maestro-cli tab star <tab-id>
maestro-cli tab unstar <tab-id>

# Flag a tab for the human with the unread dot, or clear it
maestro-cli tab unread <tab-id>
maestro-cli tab read <tab-id>

# Turn the tab's History synopsis on or off
maestro-cli tab save-to-history <tab-id> false

# Per-tab settings - the same switches as the composer chips. "active" means
# the tab on screen; add -a <agent-id> to say whose.
maestro-cli tab show active                     # read them all back
maestro-cli tab thinking <tab-id> sticky        # off | on | sticky | cycle
maestro-cli tab read-only <tab-id> true         # plan mode: no file writes
maestro-cli tab model <tab-id> opus             # "inherit" clears the override
maestro-cli tab effort <tab-id> high            # "inherit" clears the override
maestro-cli tab enter-to-send <tab-id> false    # "inherit" = global setting

# Move a tab in the tab bar (0-based index, or "first" / "last")
maestro-cli tab move <tab-id> first
maestro-cli tab move <tab-id> 2

# Reopen a closed tab, as Cmd+Shift+T does. "tab closed" lists the stack,
# newest first; reopen takes the newest, or one entry by --index or --tab.
maestro-cli tab closed -a <agent-id>
maestro-cli tab closed --all                          # every agent's stack, grouped by agent
maestro-cli tab reopen -a <agent-id>
maestro-cli tab reopen -a <agent-id> --index 2
maestro-cli tab reopen -a <agent-id> --tab <closed-tab-id> --background

# Pinned messages of an AI tab (default: the active tab; --tab names another).
maestro-cli tab pins                                  # list, in transcript order
maestro-cli tab pins add --last agent                 # pin the newest agent reply
maestro-cli tab pins add <message-id> --tab <tab-id>  # pin one message
maestro-cli tab pins rename <pin-id> Key decision     # no label restores the title
maestro-cli tab pins remove <pin-id>
maestro-cli tab pins show                             # open the pin panel (moves the view)

# The tab menu's Context items. Each acts on the active tab unless you name one,
# and prints the tab it produced. Merge and transfer move the transcript verbatim.
maestro-cli tab compact -a <agent-id>                         # summarize into a new tab
maestro-cli tab merge <tab-id> --into <agent-id> [--target-tab <tab-id>]
maestro-cli tab transfer <tab-id> --to <agent-id> --background

# Pin an agent to the Bookmarks section at the top of the Left Bar
maestro-cli bookmark <agent-id>
maestro-cli unbookmark <agent-id>
```

`tab reopen` prints the restored tab's new ID; without `-a` it acts on the agent selected in the desktop, and an empty stack or a bad `--index` / `--tab` exits 1 with a message. The closed-tab stack is kept across restarts, capped at 25 entries per agent.

### Message Pins

`tab pins` is the CLI half of the pin button on a message and the pin panel (see [Pinned Messages](https://docs.runmaestro.ai/general-usage.md#pinned-messages)). Every verb answers with the tab's pins after it ran, so `--json` output is enough to verify a change. Only user messages and agent replies can be pinned. `add` takes any transcript entry ID (exact or a unique prefix; a later chunk of a streamed reply pins the whole reply) or `--last user|agent`, and pinning a message twice reports `alreadyPinned` instead of failing. A pin listed as `loaded: false` points at a message older than what the tab has read back. `remove` and `rename` take a pin ID (exact or a unique prefix). `show` selects the agent and the tab, then opens the panel; it refuses a tab with no pins.

`tab compact` prints the compacted tab's ID and how much smaller its context is; it refuses a tab too small to compact. `tab merge` sends into the target agent's active tab unless `--target-tab` names another (another tab of the same agent works too); with `--background` the context waits on that tab and sends when it is next opened, which the output says. `tab transfer` prints the new tab's ID in the target agent; a busy target queues the context behind its running turn. A compaction can take minutes, so the CLI waits up to 10 minutes; if any of the three runs out of time it exits 5 and says the operation may still be running, rather than reporting a failure.

`tab new`, `tab reopen`, `tab compact`, `tab merge`, `tab transfer`, and `switch-mode` take `--background` / `--focus`; see [Who Moves the View](#who-moves-the-view---background----focus). `switch-mode --background` refuses when the target is the agent already on screen, since the mode change *is* the view change there, and tells you to re-run with `--focus` if you meant it anyway.

Find tab IDs with `maestro-cli session list`. `tab new` returns the new tab's ID (printed, or in the JSON payload with `--json`). Every verb that takes a `<tab-id>` also accepts the literal `active`, which resolves to the tab the agent currently has selected - `-a <agent-id>` says whose, and without it the CLI uses the agent the desktop has focused.

An agent running inside Maestro gets its **own** tab ID in its system prompt (the `Tab ID` line under Session Information, from the `{{TAB_ID}}` variable), so you can just tell it "close this tab" or "rename this tab to Docs" and it will act on the right one. Every other entry in `session list` is a different live conversation, so agents are instructed never to guess a tab ID from that list.

Bookmark, unread, star, and save-to-history are explicit set operations rather than toggles, so re-running a script lands on the same state either way. `tab thinking` is the one exception, and only in its `cycle` form, which advances one step the way clicking the chip does. Read the current values back with `maestro-cli tab show <tab-id>`, `maestro-cli show agent <id> --json` (field `bookmarked`), or `maestro-cli session list --json` (fields `starred`, `thinking`, `readOnly`, `model`, `effort`, `saveToHistory`, `enterToSend`, `active`).

`model`, `effort`, and `enter-to-send` are per-tab overrides: `inherit` clears the override so the tab follows the agent's model/effort or the global `enterToSendAI` setting again. That is not the same as `false` - `tab enter-to-send <tab-id> false` pins the tab to Cmd+Enter even when the global default is Enter. Agent-wide defaults still live on `maestro-cli update-agent <id> --model/--effort`. `bookmark` also has a flag form, `maestro-cli update-agent <id> --bookmark true`, for when you are already changing other agent settings in the same call.

### Stopping a Running Turn (`interrupt`)

Stop a turn another agent cannot get out of, the same as clicking the red Stop pill. It requires the desktop app to be running.

```bash theme={"theme":"dracula"}
# Stop every busy tab of an agent (what the Stop pill does)
maestro-cli interrupt <agent-id>

# Stop one tab only: an exact tab ID, a unique prefix, or "active"
maestro-cli interrupt <agent-id> --tab <tab-id>
maestro-cli interrupt <agent-id> --tab active

# Machine-readable result
maestro-cli interrupt <agent-id> --json
```

The stop goes through the same code as the desktop: it signals the tab's own process, cancels a pending auto-retry, context compaction, hand-off, or consult for that scope, and settles the tab to idle. With no `--tab`, every busy tab of the agent stops; `--tab` leaves the agent's other tabs running.

The verb is safe to re-run. When nothing is running it prints `Nothing to stop` and exits 0 (`wasBusy: false` in JSON). A failed stop exits 1, and a desktop that never answered exits 5. The JSON payload is `{ success, agentId, tabId, wasBusy, interrupted, stoppedTabIds, exited }`. `exited: true` means the stopped processes are gone, so `maestro-cli tab show <tab-id>` (the `State` row) and `maestro-cli session list --json` (field `state`) already read idle; when it is `false`, the CLI prints the `tab show` command to check again.

An agent cannot interrupt itself from inside its own turn: the verb refuses the caller's own agent, or `--tab` naming the caller's own tab. A sibling tab of the same agent is allowed.

### Live Mode (`live`)

Read or switch Live mode, the LIVE pill in the Left Bar that opens the web interface to other devices on the network, and Remote Control, the Cloudflare tunnel that opens it to the internet. It requires the desktop app to be running.

```bash theme={"theme":"dracula"}
# On or off, the web interface URL, and Remote Control
maestro-cli live status
maestro-cli live status --json

# Turn it on or off (each answers with the resulting status)
maestro-cli live on
maestro-cli live off --json

# Live mode and Remote Control in one step
maestro-cli live on --tunnel

# Remote Control alone (Live mode must already be on)
maestro-cli live tunnel on
maestro-cli live tunnel off
```

`live on` and `live off` run the same main-process switch as the pill, so every open window's pill follows. They are explicit set verbs, safe to re-run: when Live is already in the requested state nothing restarts, the access token stays the same, and the command prints `Live mode was already on` (`changed: false` in JSON). `live off` also stops Remote Control (the tunnel), as the pill does; `live on` starts it only with `--tunnel`.

Remote Control needs `cloudflared` on your PATH (macOS: `brew install cloudflared`), and refuses while Live is off, because the only server running then is the local one `maestro-cli` itself talks to. It does not restart the server, so `live tunnel on` simply waits for the tunnel (up to 45 seconds) and prints its public URL. The LIVE panel's Remote Control row follows whatever the CLI does.

Switching Live replaces the server the CLI talks to, so the desktop answers first and then switches. The CLI reconnects and polls `live status` until the switch finishes (up to 20 seconds), then prints the result. A failed switch exits 1 with the desktop's error, which `live status` also shows as `Last error` until the next success. The JSON payload is `{ success, changed, live, url, remoteControl, remoteControlUrl, remoteControlError?, revision, lastError? }`; `live status --json` has the same fields without `changed`.

> [!WARNING]
>
> `live on` opens the web interface to every device that can reach this machine on the network, with no confirmation, the same as clicking the pill. Anyone holding the URL (it carries the access token) can drive your agents.

### Listing Resources

```bash theme={"theme":"dracula"}
# List all groups
maestro-cli list groups

# List all agents
maestro-cli list agents
maestro-cli list agents -g <group-id>
maestro-cli list agents --group <group-id>

# Federation: the agents on one peer, or local agents plus every peer
maestro-cli list agents --peer build-box
maestro-cli list agents --all-peers --json

# Show agent details (history, usage stats, cost)
maestro-cli show agent <agent-id>

# List all playbooks (or filter by agent)
maestro-cli list playbooks
maestro-cli list playbooks -a <agent-id>
maestro-cli list playbooks --agent <agent-id>

# Show playbook details
maestro-cli show playbook <playbook-id>
```

### Running Playbooks

```bash theme={"theme":"dracula"}
# Run a playbook
maestro-cli playbook <playbook-id>

# Dry run (shows what would be executed)
maestro-cli playbook <playbook-id> --dry-run

# Run without writing to history
maestro-cli playbook <playbook-id> --no-history

# Wait for agent if busy, with verbose output
maestro-cli playbook <playbook-id> --wait --verbose

# Debug mode for troubleshooting
maestro-cli playbook <playbook-id> --debug

# Run this playbook on a different model than the agent's default
maestro-cli playbook <playbook-id> --model opus --effort high

# Clean orphaned playbooks (for deleted sessions)
maestro-cli clean playbooks
maestro-cli clean playbooks --dry-run
```

### Goal-Driven Auto Run

Spec-Driven runs (the `playbook` command above) work through a checklist of documents. Goal-Driven runs instead pursue a single free-text objective: each iteration spawns a fresh agent that makes one increment of progress, reports how far along it is, and exits, repeating until the goal is reached, a deadlock is declared, the iteration limit is hit, or progress stalls.

```bash theme={"theme":"dracula"}
# Run until the goal is reached or a deadlock is detected (infinite iterations)
maestro-cli goal-run <agent-id> "Migrate the settings store from Redux to Zustand and keep all tests green"

# Spell out what "done" looks like (guides the agent; not matched automatically)
maestro-cli goal-run <agent-id> "Improve test coverage" \
  --exit-criteria "Done when coverage is above 90% and all tests pass"

# Cap the number of iterations
maestro-cli goal-run <agent-id> "Refactor the auth module" --max-iterations 10

# Machine-parseable JSON lines for scripting / CI
maestro-cli goal-run <agent-id> "Fix all lint errors" --json

# Show the full prompt sent to the agent each iteration
maestro-cli goal-run <agent-id> "Tidy the codebase" --verbose

# Run without writing history entries
maestro-cli goal-run <agent-id> "Quick experiment" --no-history

# Pursue the goal on a different model than the agent's default
maestro-cli goal-run <agent-id> "Port the parser to the new API" --model opus --effort high

# Run it INSIDE the desktop app, where you can watch it, instead of headlessly
maestro-cli goal-run <agent-id> "Migrate the settings store" --visible

# Same, but queue behind whatever the agent is doing rather than failing
maestro-cli goal-run <agent-id> "Migrate the settings store" --visible --wait --json
```

| Option | Description | Default |
| - | - | - |
| `--exit-criteria <text>` | What "done" looks like and when to declare a deadlock | *(none)* |
| `--max-iterations <n>` | Cap the number of iterations | Infinite |
| `--no-history` | Do not write history entries | Writes |
| `--json` | Output as JSON lines (for scripting) | Human text |
| `--verbose` | Show the full prompt sent to the agent on each iteration | Off |
| `--visible` | Run inside the desktop app as a visible Auto Run instead of headlessly | Headless |
| `--wait` | With `--visible`, wait for a busy agent instead of failing (requires `--visible`) | Fail if busy |
| `--model <model>` | Model to use for this run only, overriding the agent's configured default | Agent default |
| `--effort <effort>` | Reasoning effort for this run only, overriding the agent's configured default | Agent default |

The run writes an immediate "started" history entry (recording the goal and exit criteria), one entry per iteration, and a final summary with the stop reason and final progress. Goal-Driven runs honor the same per-agent SSH remote and model/effort/args overrides as `playbook`, and refuse to start if the agent is already busy in the desktop app or another CLI instance.

**JSON event stream:** `goal_start`, `goal_iteration_start`, `goal_iteration_complete` (carries `progress`, `rationale`, `complete`, `deadlock`), and `goal_complete` (carries `success`, `exitReason`, `finalProgress`, `iterations`).

#### Visible runs (`--visible`)

By default `goal-run` is **headless**: the CLI spawns the agent itself, so the
run is real but only observable through the CLI stream and history entries. It
never appears in the agent's Auto Run surface.

`--visible` hands the run to the **running desktop app** instead. It then
behaves exactly like a run started from the Auto Run modal's **Go** button:
it shows up in the Auto Run panel, `maestro-cli stop-auto-run -a <agent-id>`
stops it, and `maestro-cli session list` reports it. The CLI returns as soon as
the desktop confirms the run has started rather than streaming iterations, and
prints a `maestro://session/<agent-id>/tab/<tab-id>` deep link that reopens it.

Use it when an orchestrating agent needs to launch a worker the user can watch;
use the headless default for CI and scripting.

`--visible` **fails closed**. If the desktop app is not reachable it reports
`MAESTRO_NOT_RUNNING` and exits `3` rather than quietly running headlessly, because a silent
fallback is invisible in exactly the surface you were pointing at. Other stable
failure codes: `AGENT_BUSY` (the agent already has an Auto Run going - pass
`--wait` to queue instead), `AUTO_RUN_DISABLED`, `SESSION_NOT_FOUND`,
`LAUNCH_TIMEOUT`, and `UNSUPPORTED_COMMAND` (the desktop app is an older build
than the CLI - rebuild and restart it).

With `--json`, a successful launch emits a single `visible_launch` event:

```json theme={"theme":"dracula"}
{
	"type": "visible_launch",
	"ok": true,
	"mode": "goal",
	"visible": true,
	"agentId": "agent-123",
	"sessionId": "agent-123",
	"tabId": "tab-9",
	"status": "running",
	"uri": "maestro://session/agent-123/tab/tab-9"
}
```

Goal-Driven Auto Runs attach to the **agent**, not to a tab, so there is no
`--new-tab` / `--tab`: the run surfaces on whichever AI tab is active, and that
is the tab the returned deep link addresses.

### Running Documents Without a Playbook (`run-doc`)

`run-doc` runs one or more Auto Run `.md` documents directly, without saving a playbook first. Like `playbook`, it runs **headlessly** - it spawns the target agent itself and streams events, so it works whether or not the Maestro desktop window is open. This is the reliable way to execute a document an agent just wrote.

```bash theme={"theme":"dracula"}
# Run a single document on an agent (by ID or name)
maestro-cli run-doc plans/frontend-plan.md --agent "Frontend"

# The path may be relative to the agent's Auto Run folder, relative to the
# current directory, or absolute. Multiple documents run in sequence.
maestro-cli run-doc plan-a.md plan-b.md --agent <agent-id>

# Wait for the agent if it is busy, loop until all tasks are done
maestro-cli run-doc plans/migrate.md --agent <agent-id> --wait --loop

# JSON output for scripting; skip history writes
maestro-cli run-doc plans/spec.md --agent <agent-id> --json --no-history

# Run this document on a different model than the agent's default
maestro-cli run-doc plans/spec.md --agent <agent-id> --model opus --effort high
```

`run-doc` accepts the same execution flags as `playbook` (`--dry-run`, `--no-history`, `--json`, `--debug`, `--verbose`, `--no-synopsis`, `--wait`, `--model`, `--effort`, `--ignore-model-hints`) plus `--prompt`, `--loop`, `--max-loops`, and `--reset-on-completion`. When no `--prompt` is given it uses the default Auto Run prompt.

#### Per-run model override

All four Auto Run entry points - `playbook`, `run-doc`, `goal-run`, and
`auto-run` - accept `--model <model>` and `--effort <effort>`. Both are
**run-scoped**: they apply to every agent spawn the run makes (including the
per-task synopsis and goal-handoff spawns) and take precedence over the agent's
configured model, but nothing is written back to the agent. When the run ends,
the agent is exactly as it was.

`playbook`, `run-doc`, and `auto-run` also take `--ignore-model-hints`. It skips
every `MAESTRO:MODEL` marker in the run's documents, so each task runs at
`--model` / `--effort` (or the agent's configured default when those are
omitted) instead of the tier the document asked for. `goal-run` has no
documents, so it has no such flag.

```bash theme={"theme":"dracula"}
maestro-cli playbook <playbook-id> --model opus
maestro-cli playbook <playbook-id> --model opus --ignore-model-hints
maestro-cli run-doc plans/spec.md --agent <agent-id> --model opus
maestro-cli goal-run <agent-id> "Ship the migration" --model opus --effort high
maestro-cli auto-run doc1.md --agent <agent-id> --launch --model opus
```

Notes:

* Omitting the flags keeps the existing behavior exactly: the run uses the
  agent's configured model and effort.
* Valid values are provider-specific (for example `sonnet` / `opus` for Claude
  Code). The CLI passes the value through rather than validating it against the
  provider's model list.
* `--effort` only does something on providers that expose a reasoning-effort
  setting; it is ignored elsewhere.
* The headless commands (`playbook`, `run-doc`, `goal-run`) print a
  `Model: <value> (this run only)` line in human-readable (non-`--json`) output
  so you can confirm which model the run used. JSONL output is unchanged.
  `auto-run` hands the run to the desktop app, so confirm that one in the
  desktop UI instead.
* The desktop Auto Run launch modal has the same two pickers, both defaulting to
  "Use agent default". See [Auto Run](https://docs.runmaestro.ai/autorun-playbooks.md).

> **`playbook` vs `run-doc` vs `auto-run --launch`:** use `playbook <id>` for a saved playbook and `run-doc <docs>` for raw documents - both run headlessly with no desktop dependency. `auto-run --launch` instead hands the run to the running desktop app (needed only when you want the run to appear and be controlled in the desktop UI).

> **`--agent` accepts a name:** the `-a, --agent` flag on these commands resolves an agent by ID (full or partial) **or** by display name. This lets a group-chat participant target itself with `--agent "<its name>"`.

### Prompt Customization

The CLI uses the same core system prompts as the desktop app. When you customize prompts via Settings → **Maestro Prompts**, those customizations are stored in `core-prompts-customizations.json` in the Maestro data directory and are automatically picked up by the CLI during playbook runs.

The prompts most relevant to CLI playbook execution are:

| Prompt ID | Controls |
| - | - |
| `autorun-default` | Default Auto Run task execution behavior |
| `autorun-synopsis` | Synopsis generation after task completion |
| `commit-command` | `/commit` command behavior |
| `maestro-system-prompt` | Maestro system context injected into sessions |
| `context-grooming` | Context grooming during transfers |

To customize these prompts, either use the desktop app's **Maestro Prompts** tab or edit the JSON file directly:

```text theme={"theme":"dracula"}
# macOS
~/Library/Application Support/Maestro/core-prompts-customizations.json

# Linux
~/.config/Maestro/core-prompts-customizations.json

# Windows
%APPDATA%\Maestro\core-prompts-customizations.json
```

The file format is:

```json theme={"theme":"dracula"}
{
	"prompts": {
		"autorun-default": {
			"content": "Your customized prompt content...",
			"isModified": true,
			"modifiedAt": "2026-04-11T..."
		}
	}
}
```

### Reading Prompts (`prompts list` / `prompts get`)

The CLI exposes Maestro's prompt registry directly so other agents can self-fetch reference material on demand. Parent prompts can use the `{{REF:name}}` directive (see [Prompt Customization → Include Directives](https://docs.runmaestro.ai/prompt-customization.md#include-directives)) to expand into a one-line pointer; the agent then runs `prompts get` to retrieve the full content.

```bash theme={"theme":"dracula"}
# List every available prompt id with description and category
maestro-cli prompts list

# JSON output for scripting
maestro-cli prompts list --json

# Print a specific prompt's content (honors user customizations)
maestro-cli prompts get _maestro-cli
maestro-cli prompts get autorun-default

# Include metadata in the response
maestro-cli prompts get _maestro-cue --json
```

`prompts get` returns the same content the desktop app would deliver, so customizations made via Settings → **Maestro Prompts** are reflected immediately. Bundled include fragments use a leading underscore in their id (e.g., `_maestro-cli`, `_history-format`); standalone prompts do not.

### Managing Settings

View and modify any Maestro configuration setting directly from the CLI. Changes take effect immediately in the running desktop app - no restart required.

```bash theme={"theme":"dracula"}
# List all settings with current values
maestro-cli settings list

# List with descriptions (great for understanding what each setting does)
maestro-cli settings list -v

# Filter by category
maestro-cli settings list -c appearance
maestro-cli settings list -c shell -v

# Show only setting keys
maestro-cli settings list --keys-only

# Get a specific setting
maestro-cli settings get fontSize
maestro-cli settings get activeThemeId

# Get nested settings with dot-notation
maestro-cli settings get encoreFeatures.directorNotes

# Get with full details (type, default, description)
maestro-cli settings get fontSize -v

# Set a setting (type is auto-detected)
maestro-cli settings set fontSize 16
maestro-cli settings set audioFeedbackEnabled true
maestro-cli settings set activeThemeId monokai
maestro-cli settings set defaultShowThinking on

# Set complex values with explicit JSON
maestro-cli settings set localIgnorePatterns --raw '["node_modules",".git","dist"]'

# Reset a setting to its default value
maestro-cli settings reset fontSize
```

| Flag | Description | Commands |
| - | - | - |
| `-v, --verbose` | Show descriptions for each setting | `list`, `get` |
| `--keys-only` | Show only setting key names | `list` |
| `--defaults` | Show default values alongside current values | `list` |
| `-c, --category <name>` | Filter by category (appearance, shell, editor, etc.) | `list` |
| `--show-secrets` | Show sensitive values like API keys (masked by default) | `list` |
| `--raw <json>` | Pass an explicit JSON value | `set` |
| `--json` | Machine-readable JSON output | all |

**Categories:** appearance, editor, shell, notifications, updates, logging, web, ssh, file-indexing, context, document-graph, stats, accessibility, integrations, onboarding, advanced, internal.

> [!TIP]
>
> Use `maestro-cli settings list -v` from inside an AI agent conversation to give the agent full context about every available setting and what it controls.

### Theme and Encore Features

Ergonomic, validated wrappers over the underlying settings, for the customizations users most often ask for by voice. Unlike `settings set` (which writes the settings file), these route through the running desktop app, so the change applies live. The app must be running.

```bash theme={"theme":"dracula"}
# Switch the active theme by ID or display name (case-insensitive)
maestro-cli set-theme tokyo-night
maestro-cli set-theme "Catppuccin Mocha"

# See every available theme
maestro-cli set-theme --list

# Set how much light the app chrome catches (Settings -> Themes -> Surface Gloss)
maestro-cli gloss strong

# See the current level and what each one does
maestro-cli gloss
maestro-cli gloss --list

# List Encore (experimental) features and whether each is enabled
maestro-cli encore list

# Enable or disable an Encore feature
maestro-cli encore enable symphony
maestro-cli encore disable maestroCue
```

Encore feature IDs: `directorNotes`, `usageStats`, `symphony`, `maestroCue`, `pianola`, `quickChat`, and on macOS `maestroRun`. Friendly aliases are accepted (for example `cue` for `maestroCue`, `quick-chat` for `quickChat`). Group Chat is a core feature with no Encore flag, so `group-chat` is not an alias for `symphony`.

`autopilot`, `auto-pilot`, and `pilot` remain aliases for enabling Pianola. They do not grant automatic repair permission. `encore list --json` includes `pianola.mode` (`disabled`, `supervision`, or `automatic_repairs`), the saved `autoFixEnabled` permission, and `automaticMergeAvailable: false`.

Automatic repairs are a separate opt-in in **Settings > Plugins > Pianola > Settings > Automatic repairs**, or via `maestro-cli settings set pianolaAutoFixEnabled true`. The setting defaults to `false` and is re-read before repair actions. Set it to `false` to revoke permission. Repair dispatches remain bounded; repair workers can change files within their existing access. Enabling repairs does not authorize merging. The current merge adapter records `skipped` and never executes a merge.

Legacy hand-edited `encoreFeatures.autopilot` values no longer grant repair permission. Review the separate setting and opt in explicitly if repairs are wanted; no migration silently enables them.

Gloss levels, least to most: `off` (the shipped flat look), `sheen`, `strong`, `max`. Gloss only adds highlights and shadows to the sidebars, headers, tab bar and composer, so it changes no theme color and leaves text exactly as legible. It has no effect on light themes.

### MaestroRun (macOS)

Set up [MaestroRun](https://docs.runmaestro.ai/maestro-run.md), the signed launcher that holds one Full Disk Access grant for your scheduled scripts. Each verb takes the same path as the matching button on the MaestroRun tile in Settings. The app must be running, and the plugin must be on (`maestro-cli encore enable maestroRun`).

```bash theme={"theme":"dracula"}
maestro-cli maestro-run status               # installed version, signature, Full Disk Access
maestro-cli maestro-run status --check-latest --json
maestro-cli maestro-run install              # install the newest release for this Mac, or update
maestro-cli maestro-run grant                # open the Full Disk Access list and watch for the switch
maestro-cli maestro-run grant --reveal       # also show MaestroRun.app in Finder
```

`grant` cannot switch the permission on: macOS has no prompt for Full Disk Access, so you flip the switch in System Settings and `status` reports `ready` once you have. These verbs set MaestroRun up. To run a script, use the launcher itself, at the path `status` prints.

### Dataview

Run a note's Dataview queries and get the same result File Preview renders. `this` is the note, and the query runs against the index of the vault that holds it, in the running app (local or over SSH). The CLI indexes nothing itself, so the app must be running.

```bash theme={"theme":"dracula"}
maestro-cli dataview query "People/Pedram Amini.md"            # every dataview block in the note
maestro-cli dataview query notes/today.md --block 2 --json     # only the 2nd dataview block
maestro-cli dataview eval notes/today.md 'LIST FROM #meeting'  # an ad-hoc query
maestro-cli dataview eval notes/today.md '= this.file.name'    # an inline expression
maestro-cli dataview index status                              # every open vault index
maestro-cli dataview index status ~/Vault --json
maestro-cli dataview index rebuild ~/Vault                     # drop the cache and index again
maestro-cli dataview trust ~/Vault                             # run the vault's DataviewJS blocks without asking
maestro-cli dataview untrust ~/Vault                           # ask again before they run
maestro-cli dataview trusted --json                            # the trusted vaults
```

`--block <n>` counts `dataview` fences only, from 1. A note's agent is the agent whose folder holds it; pass `--agent <id>` to choose one, and to name the SSH remote for `index status` and `index rebuild`. Tables fit the terminal width; `--json` prints the full result, with links as objects and dates as ISO strings. A `dataviewjs` block prints `DataviewJS renders in the desktop app only` and exits `2`; a bad `--block` or a note no agent owns also exits `2`, and a query error exits `1`.

`trust`, `untrust`, and `trusted` edit and list the vaults whose `dataviewjs` blocks run without asking, the same list as **Trusted Vaults** in the Dataview settings and **Always trust this vault** on a block. The CLI never runs a script. A root is resolved against the current folder (`~` works) and stored without a trailing separator; it must be the vault root as the app names it (the folder that holds `.obsidian/`, or the agent's folder). `untrust` also ends that vault's **Run once** grants.

### Quick Chat

Drive the [Quick Chat](https://docs.runmaestro.ai/quick-chat.md) window, the floating chat summoned by a system-wide hotkey. Each verb takes the same path as the matching button in the window. The app must be running.

```bash theme={"theme":"dracula"}
maestro-cli quick-chat toggle                # what the hotkey does: open, focus, or close
maestro-cli quick-chat send "summarize the last commit"
maestro-cli quick-chat send "what broke?" --image shot.png   # attach images, like a paste in the window
maestro-cli quick-chat status --json         # window state, agent, mode, and each message with the tab it went to
maestro-cli quick-chat keep                  # keep the current chat as a visible tab ("keep off" undoes it)
maestro-cli quick-chat pin                   # float the window on top ("pin off" lets it fall behind)
maestro-cli quick-chat thinking on           # show the agent's reasoning until the answer arrives (sticky keeps it, off hides it)
maestro-cli quick-chat tab new               # next message to a new tab; or a tab id from status, or auto
maestro-cli quick-chat reveal [message-id]   # open a message's tab in Maestro (default: the latest)
maestro-cli quick-chat new-tab [message-id]  # send a message to a new tab instead (queued, or wrong tab)
maestro-cli quick-chat font in               # bigger conversation text (out, reset, or a size such as 120%)
maestro-cli quick-chat new                   # start over; hidden tabs an ephemeral chat created are deleted
maestro-cli quick-chat agent <agent-id>      # switch agents (starts a new chat)
maestro-cli quick-chat stop                  # stop replies in progress and withdraw queued messages
maestro-cli quick-chat history               # recent chats, numbered, newest first
maestro-cli quick-chat recall 2              # bring one back: its agent, tab, and messages (number, id, or id prefix)
maestro-cli quick-chat bounds --width 640 --height 520   # resize or move the window (remembered)
```

### Custom Theme Palette

`set-theme` only switches between built-in themes. The `theme` command group manages the user-configurable **Custom** theme palette (the same two settings the in-app Custom Theme Builder edits: `customThemeColors` and `customThemeBaseId`). Activate the result with `set-theme custom`.

```bash theme={"theme":"dracula"}
# Print the current custom palette and its base theme (reads from disk; works offline)
maestro-cli theme show
maestro-cli theme show --json

# Export the custom theme as portable JSON (stdout, or to a file)
maestro-cli theme export
maestro-cli theme export --file my-theme.json

# Import a theme JSON file, apply it live, and activate it
maestro-cli theme import my-theme.json
maestro-cli theme import my-theme.json --no-activate   # save the palette without switching to it

# Set individual colors (key=value); optionally re-base from a built-in theme first
maestro-cli theme set accent=#ff0000 bgMain=#1a1a1a
maestro-cli theme set --base dracula accent=#ff79c6 --activate
```

Export files are byte-compatible with the in-app Custom Theme Builder, so a palette round-trips between the UI and CLI. `theme show` and `theme export` read the on-disk settings store directly (no running app required); `theme import` and `theme set` apply live through the running desktop app. Imports are validated the same way as the in-app importer: every required color key must be present and every value must be a valid CSS color.

| Command | Flag | Description |
| - | - | - |
| `theme show` | `--json` | Machine-readable output |
| `theme export` | `-f, --file <path>` | Write the theme JSON to this file instead of stdout |
| `theme import` | `--no-activate` | Save the palette without switching to the Custom theme |
| `theme set` | `-b, --base <id>` | Initialize from a built-in theme before applying overrides |
| `theme set` | `-a, --activate` | Switch to the Custom theme after applying |

### Managing Agent Configuration

Each agent (Claude Code, Codex, OpenCode, Factory Droid) can have its own configuration for custom paths, CLI arguments, environment variables, and model overrides.

> [!NOTE]
>
> `settings agent set` writes the per-agent-type configuration store (defaults applied to newly created agents and headless CLI spawns). To change the settings of a specific existing agent shown in the Left Bar - its nudge message, model, env vars, Claude token source, and so on - use [`update-agent`](#creating-updating-and-removing-agents) instead, which writes that agent's live desktop Session.
>
> `settings agent list` and `settings agent get` also accept an agent ID (or a unique prefix) in place of a provider type. They then read that agent's own settings, the same fields `update-agent` writes and `show-agent` reports: `codexTransport`, `tokenSource`, `customModel`, `nudgeMessage`, and so on. `set` and `reset` refuse an agent ID and point you at `update-agent`.

```bash theme={"theme":"dracula"}
# List all agent configurations
maestro-cli settings agent list

# List config for a specific agent
maestro-cli settings agent list claude-code

# Get a specific agent config value
maestro-cli settings agent get codex model
maestro-cli settings agent get claude-code customPath

# Read one setting of a specific agent (by agent ID)
maestro-cli settings agent get <agent-id> codexTransport

# Set agent config values
maestro-cli settings agent set codex contextWindow 128000
maestro-cli settings agent set claude-code customPath /usr/local/bin/claude
maestro-cli settings agent set codex customEnvVars --raw '{"DEBUG":"true"}'

# Remove an agent config key
maestro-cli settings agent reset codex model
```

| Flag | Description | Commands |
| - | - | - |
| `-v, --verbose` | Show descriptions for each config key | `list`, `get` |
| `--raw <json>` | Pass an explicit JSON value | `set` |
| `--json` | Machine-readable JSON output | all |

**Common agent config keys:**

| Key | Type | Description |
| - | - | - |
| `customPath` | string | Custom path to the agent CLI binary |
| `customArgs` | string | Additional CLI arguments |
| `customEnvVars` | object | Extra environment variables |
| `model` | string | Model override (e.g., `gpt-5.3-codex`, `o3`) |
| `contextWindow` | number | Context window size in tokens |
| `reasoningEffort` | string | Reasoning effort level (`low`, `medium`, `high`) |
| `reasoningSummary` | string | Codex only: reasoning shown in Thinking (`auto`, `concise`, `detailed`, `none`); empty inherits the Codex default |

Codex configuration notices, such as an ignored setting, appear as `Codex warning:`
diagnostics in the desktop transcript even with Thinking off. Headless CLI runs
print them to stderr. These notices do not stop the turn or become part of the
assistant's answer; actual turn failures still use normal error handling.

> [!NOTE]
>
> Settings and agent config changes made via the CLI are automatically detected by the running Maestro desktop app. The app watches for file changes and reloads immediately - it's as if you toggled the setting in the Settings modal yourself.

### Managing SSH Remotes

Create, list, update, and remove SSH remote configurations. These commands read and write directly to the Maestro settings file - no running desktop app required.

```bash theme={"theme":"dracula"}
# List all configured SSH remotes
maestro-cli list ssh-remotes

# Create a new SSH remote
maestro-cli create-ssh-remote "Dev Server" -H 192.168.1.100 -u deploy

# Create with SSH config mode (uses ~/.ssh/config)
maestro-cli create-ssh-remote "Prod" -H prod-host --ssh-config

# Create with all options
maestro-cli create-ssh-remote "Build Server" \
	-H build.example.com \
	-p 2222 \
	-u ci \
	-k ~/.ssh/build_key \
	--env PATH=/usr/local/bin --env NODE_ENV=production \
	--set-default

# Reach a host through a tunnel with extra ssh -o options
maestro-cli create-ssh-remote "Tunnelled box" \
	-H internal.example.com \
	-u deploy \
	--ssh-option 'ProxyCommand=cloudflared access ssh --hostname %h' \
	--ssh-option ConnectTimeout=45

# Update an existing remote (merges by default)
maestro-cli update-ssh-remote <remote-id> --ssh-option ConnectTimeout=60
maestro-cli update-ssh-remote <remote-id> --clear-ssh-options
maestro-cli update-ssh-remote <remote-id> --enabled false

# Remove an SSH remote
maestro-cli remove-ssh-remote <remote-id>
```

`create-ssh-remote` flags:

| Flag | Description | Default |
| - | - | - |
| `-H, --host <host>` | SSH hostname or IP (required; Host pattern with `--ssh-config`) | - |
| `-p, --port <port>` | SSH port | `22` |
| `-u, --username <user>` | SSH username | - |
| `-k, --key <path>` | Path to private key file | - |
| `--env <KEY=VALUE>` | Remote environment variable (repeatable) | - |
| `--ssh-option <K=V>` | Extra `ssh -o` option, e.g. `ProxyCommand=...` (repeatable) | - |
| `--ssh-config` | Use `~/.ssh/config` for connection settings | - |
| `--disabled` | Create in disabled state | - |
| `--set-default` | Set as the global default SSH remote | - |
| `--json` | Machine-readable JSON output | - |

`update-ssh-remote` takes the same connection flags plus the ones below. `--env`
and `--ssh-option` MERGE into what the remote already has, so a single flag does
not silently drop the rest; pair them with the matching `--clear-*` flag to
replace the set outright. Passing an empty string to `-u` or `-k` clears it.

| Flag | Description | Default |
| - | - | - |
| `-n, --name <name>` | Display name | - |
| `--clear-env` | Drop all remote environment variables before applying `--env` | - |
| `--clear-ssh-options` | Drop all extra `ssh -o` options before applying `--ssh-option` | - |
| `--ssh-config <bool>` | Turn `~/.ssh/config` mode on or off | - |
| `--enabled <bool>` | Enable or disable this remote | - |
| `--set-default` | Set as the global default SSH remote | - |
| `--json` | Machine-readable JSON output, including `resolvedSshOptions` | - |

A command-line `-o` outranks `~/.ssh/config`, so `--ssh-option` is the only way
to change one of Maestro's connection defaults (`ConnectTimeout`, `BatchMode`,
and friends). `list ssh-remotes --json` and `update-ssh-remote --json` both
report `resolvedSshOptions`, the full merged set `ssh` actually receives, which
is what answers "did my `ConnectTimeout` take effect?". See
[SSH Remote Execution](https://docs.runmaestro.ai/ssh-remote-execution.md) for the reserved keys and the
merge rules.

> [!NOTE]
>
> SSH remote changes made via the CLI are detected by the running Maestro desktop app through file watching, just like settings changes.

## Partial IDs

All commands that accept an agent ID, group ID, or SSH remote ID support partial matching. You only need to type enough characters to uniquely identify the resource:

```bash theme={"theme":"dracula"}
# These are equivalent if "a1b2" uniquely matches one agent
maestro-cli send a1b2c3d4-e5f6-7890-abcd-ef1234567890 "hello"
maestro-cli send a1b2 "hello"
```

If the partial ID is ambiguous, the CLI will show all matches.

## JSON Output

By default, commands output human-readable formatted text. Use `--json` for machine-parseable output:

```bash theme={"theme":"dracula"}
# Human-readable output (default)
maestro-cli list groups
GROUPS (2)

  🎨  Frontend
      group-abc123
  ⚙️  Backend
      group-def456

# JSON output for scripting
maestro-cli list groups --json
{"type":"group","id":"group-abc123","name":"Frontend","emoji":"🎨","collapsed":false,"timestamp":...}
{"type":"group","id":"group-def456","name":"Backend","emoji":"⚙️","collapsed":false,"timestamp":...}

# Note: list agents outputs a JSON array (not JSONL)
maestro-cli list agents --json
[{"id":"agent-abc123","name":"My Agent","toolType":"claude-code","cwd":"/path/to/project",...}]

# Running a playbook with JSON streams events
maestro-cli playbook <playbook-id> --json
{"type":"start","timestamp":...,"playbook":{...}}
{"type":"document_start","timestamp":...,"document":"tasks.md","taskCount":5}
{"type":"task_start","timestamp":...,"taskIndex":0}
{"type":"task_complete","timestamp":...,"success":true,"summary":"...","elapsedMs":8000,"usageStats":{...}}
{"type":"document_complete","timestamp":...,"document":"tasks.md","tasksCompleted":5}
{"type":"loop_complete","timestamp":...,"iteration":1,"tasksCompleted":5,"elapsedMs":60000}
{"type":"complete","timestamp":...,"success":true,"totalTasksCompleted":5,"totalElapsedMs":60000,"totalCost":0.05}
```

If the run is interrupted (Ctrl+C or SIGTERM), the agent turn in flight is stopped gracefully and the stream ends with a `complete` event carrying `"stopped":true`. The interrupted task is recorded as "interrupted" rather than failed, and the process exits with code `130`. A second Ctrl+C exits immediately. `maestro-cli playbook`, `maestro-cli run-doc` and `maestro-cli goal-run` all behave this way; a goal run ends with `exitReason: "stopped-by-user"`.

```json theme={"theme":"dracula"}
{"type":"complete","timestamp":...,"success":false,"totalTasksCompleted":2,"totalElapsedMs":31000,"stopped":true}
```

The `send` command always outputs JSON (no `--json` flag needed).

### Desktop Integration

Commands for interacting with the running Maestro desktop app. These are especially useful for AI agents to trigger UI updates after creating or modifying files.

#### Open a Maestro Surface (Modal or Dashboard)

Bring up one of Maestro's modals or dashboards in the running app, optionally on a specific tab. This is how an agent answers "where do I see X?" by *showing* you rather than describing a menu path.

```bash theme={"theme":"dracula"}
# Every openable surface, with its tabs and hotkey
maestro-cli open --list

# Open Maestro Cue
maestro-cli open cue

# Deep-link to a tab
maestro-cli open cue --tab scheduled
maestro-cli open settings --tab shortcuts
maestro-cli open usage-dashboard --tab cue
```

| Flag | Description |
| - | - |
| `-t, --tab <tab>` | Deep-link to a tab within the surface |
| `--list` | List every openable surface, its tabs, and its shortcut |
| `--json` | Output as JSON (for scripting) |

Surfaces are addressed by id or alias (`usage`, `stats`, and `dashboard` all reach the Usage Dashboard). A `--tab` value matches either the tab id (`scheduled`) or its label (`"Scheduled Tasks"`).

On success the command also prints how to reach that surface by hand:

```
Opened Maestro Cue (scheduled tab) in Maestro.
You can also reach Maestro Cue yourself: press Alt+Q, or open the command palette and search "Maestro Cue", or click the lightning-bolt icon in the Left Bar footer.
```

That second line is the point: an agent should relay it, so opening a surface for you teaches you the hotkey instead of making you ask again next time.

Surfaces behind an Encore Feature that you have switched off (Cue, Symphony, Director's Notes, the Usage Dashboard) refuse to open and say so in a toast rather than silently doing nothing or turning your setting back on.

#### Open a File

Open a file as a preview tab in the Maestro desktop app. Without `--agent`, a shell inside Maestro (an agent's own turn, or a terminal tab) opens the file in the agent it belongs to, so `maestro-cli open-file ~/.bashrc` typed in a terminal tab lands in that tab's agent. Elsewhere the owning agent is auto-detected by which agent's working directory the file lives in (longest-prefix match, most-recently-active wins on ties), and a path outside every agent's directory is an error. Pass `--agent <id>` to name the agent yourself.

```bash theme={"theme":"dracula"}
maestro-cli open-file <file-path> [-a <id>] [--background | --no-switch] [--queue]
```

| Flag | Description |
| - | - |
| `-a, --agent <id>` | Target agent (defaults to the agent owning this shell or terminal tab, else the file path's owning agent) |
| `--background` | Open the preview tab without changing anything currently rendered, on any agent |
| `--focus` | Switch to the file after opening it (default) |
| `--no-switch` | Don't switch to the target agent, but still activate the tab there |
| `--queue` | Audio/video only: add to the media player queue and show the player without starting playback |

A folder has no preview, so `open-file <folder>` reveals it in the agent's Files panel instead: the Right Bar opens on the Files tab, every ancestor and the folder itself expand, and its row is selected. Clicking a folder link in the chat does the same. `--background` and `--no-switch` expand and select without moving the view. A folder outside the agent's file tree cannot be revealed there.

This is also the verb that plays media. A local audio or video file does not become a tab at all: it goes to the [floating media player](https://docs.runmaestro.ai/media-player.md), so `open-file ~/Music/track.mp3 --agent <id>` is how you or an agent starts playback without handing the file to your system's default player. There is no separate `play` command. `--background` has nothing to suppress in that case, since playback is audible either way, and a file on an SSH remote has no stream to play, so it falls back to the ordinary binary-file path.

`--no-switch` and `--background` are different asks, and this is the one command that offers both. `--no-switch` keeps the Left Bar selection where it is but still activates the new tab inside the target agent - so if you were already on that agent, your view still changes. `--background` changes nothing rendered anywhere. Passing both is fine; `--background` is strictly stronger and wins. If `--no-switch` is what you reached for, `--background` is probably what you meant.

Audio and video never open as a tab: they go to the [floating media player](https://docs.runmaestro.ai/media-player.md), and a plain `open-file` starts playing. `--queue` puts the file in the player without pressing play. If nothing is loaded, the file loads paused and the player appears; if something is already loaded, the file lines up behind it and nothing is interrupted. A minimized player comes back either way. It never switches agents, since the player is app-wide. To hand someone a playlist to start themselves, queue each file in order:

```bash theme={"theme":"dracula"}
for f in episodes/*.mp3; do maestro-cli open-file "$f" --queue; done
```

`--queue` on a file that is not audio or video is an error.

Pass an `http://` or `https://` URL instead of a path to stream it in the player. This covers progressive MP4 (H.264 video, AAC audio) and plain audio files such as MP3 or M4A. Adaptive and live formats (HLS `.m3u8`, DASH, RTSP, RTMP) are not supported. A URL never becomes a tab and never switches agents; it is filed under `--agent`, or the agent that owns your shell's current directory. `--queue` works the same as for a file:

```bash theme={"theme":"dracula"}
maestro-cli open-file https://example.com/clip.mp4 --queue
```

#### Open a Browser Tab

Open a URL as a browser tab in the Maestro desktop app. Only `http(s)` URLs are accepted; scheme-less inputs like `localhost:3000` or `example.com:8080` are auto-prefixed with `https://`.

By default this **switches the UI** to the target agent and makes the new tab visible. Pass `--background` to create the tab without moving the user: the active agent is left alone and whatever tab they were looking at stays on screen. Either way the command prints the new tab's ID, which is the handle for `close-browser`.

```bash theme={"theme":"dracula"}
# Open in the active agent (switches the UI to it)
maestro-cli open-browser https://docs.runmaestro.ai

# Scheme-less - gets https:// prepended
maestro-cli open-browser localhost:3000

# Target a specific agent
maestro-cli open-browser https://github.com/RunMaestro/Maestro -a <agent-id>

# Background tab - does not switch agents or change the visible tab
maestro-cli open-browser https://example.com/docs --background -a <agent-id>
```

| Flag | Description |
| - | - |
| `-a, --agent <id>` | Target agent by ID (defaults to the active agent) |
| `--background` | Create the tab without focusing it or switching the active agent |
| `--focus` | Switch to the browser tab after opening it (default) |

> [!NOTE]
>
> Agents doing research should always pass `--background` and then `close-browser` when finished. A
> foreground tab pulls the window away from whatever the user is doing, potentially mid-keystroke.

#### Close a Browser Tab

Close a browser tab by the ID that `open-browser` returned. The owning agent is resolved from the tab ID, so no `--agent` is needed. Exits non-zero if no such tab exists, so cleanup scripts can tell a real close from a no-op.

```bash theme={"theme":"dracula"}
maestro-cli close-browser <tab-id>
```

| Flag | Description |
| - | - |
| `--json` | Output as JSON (for scripting) |

#### Open a Terminal Tab

Open a fresh terminal tab in the Maestro desktop app. The working directory must resolve inside the target agent's `cwd`; paths outside it are rejected.

```bash theme={"theme":"dracula"}
# Open a terminal in the active agent's cwd with the default shell
maestro-cli open-terminal

# Custom cwd, shell, and tab label
maestro-cli open-terminal --cwd ./packages/api --shell bash --name "API tests"

# Start a dev server in a named terminal
maestro-cli open-terminal --name "Dev server" --command "npm run dev"

# Target a specific agent
maestro-cli open-terminal -a <agent-id> --name "Build watch"
```

| Flag | Description | Default |
| - | - | - |
| `-a, --agent <id>` | Target agent by ID (defaults to the active agent) | - |
| `--cwd <path>` | Working directory for the terminal (must be inside the agent's cwd) | agent's cwd |
| `--shell <bin>` | Shell binary to use | `zsh` |
| `--name <label>` | Display name for the tab | - |
| `--command <cmd>` | Command to run once the shell is ready | - |
| `--background` | Create the tab without moving the view (agent and tab stay put) | - |
| `--focus` | Switch to the terminal tab after opening it (default) | - |
| `--input-required` | Notify the user that the terminal needs them to type in it | - |

`--input-required` is for a terminal opened because a person must type there, such as a `sudo` password prompt. Once the shell starts, Maestro raises a **Terminal needs your input** notification that names the agent and the terminal. The notification does not move the view; clicking it opens that terminal. Pair it with `--background`. For a terminal that is already open, send the same notice with `notify toast "Terminal needs your input" "Your input is needed." --agent <agent-id> --open-terminal <tab-id>`.

`--command` is stored as the tab's startup command, the same field the tab's right-click "Startup Command…" menu writes. The command runs as soon as the shell finishes loading its rc files, and it runs again if the tab is restarted or the app is reopened. That is what you want for `npm run dev`; for a one-shot command that should not come back, close the tab when it finishes, or use `send-terminal` instead.

The command prints the new tab's ID. Keep it: it is the handle for `send-terminal --tab`.

#### Run a Command in an Existing Terminal Tab

`open-terminal` makes a new terminal. `send-terminal` types into one that is already open, which is what you want to drive a shell the user is watching.

```bash theme={"theme":"dracula"}
# Run something in the agent's active terminal
maestro-cli send-terminal "npm test"

# Target a terminal by the ID open-terminal printed, or by its tab name
maestro-cli send-terminal --tab <tab-id> "git status"
maestro-cli send-terminal --tab "Dev server" "npm run build"

# Stop whatever is running (Ctrl-C)
maestro-cli send-terminal --tab "Dev server" --control C

# Type the command but leave it unexecuted, so a human can read it first
maestro-cli send-terminal --no-enter "rm -rf ./dist"
```

| Flag | Description | Default |
| - | - | - |
| `-a, --agent <id>` | Target agent by ID | active agent |
| `--tab <id-or-name>` | Terminal tab ID, or its display name | the agent's active terminal |
| `--control <letter>` | Send a control character instead of a command (`C` = Ctrl-C) | - |
| `--no-enter` | Type the command without pressing Enter | Enter is sent |

Notes:

* A tab **ID** is matched across every agent, so an ID from `open-terminal` works without `--agent`. A tab **name** is matched only within the target agent, because names collide (three projects can each have a "Dev server").
* With no `--tab`, the agent's active terminal receives the command. If several terminals are open and none is active, the command fails rather than guessing.
* The terminal must have a running shell. A tab that has never been displayed has no shell yet: open it with `open-terminal --command` instead, or select it in the app first.
* Text is typed into the shell verbatim. If something is already half-typed at the prompt, your command lands on the end of it.

#### Read a Terminal Tab's Output

`send-terminal` types into a shell; `read-terminal` reads back what it printed. Without it the terminal is write-only from a script's point of view: `open-terminal --command "npm run dev"` is the right way to run a long-lived process, but nothing could observe whether it came up.

```bash theme={"theme":"dracula"}
# Last 200 lines of the agent's active terminal
maestro-cli read-terminal

# Target a specific tab, by ID or by name
maestro-cli read-terminal --tab <tab-id>
maestro-cli read-terminal --tab "Dev server" --tail 50

# Run something, then read what it printed
maestro-cli send-terminal --tab "Dev server" "npm run build" && \
    sleep 5 && maestro-cli read-terminal --tab "Dev server"

# Structured output - `busy` tells you whether the command is still running
maestro-cli read-terminal --tab "Dev server" --json
```

| Flag | Description | Default |
| - | - | - |
| `-a, --agent <id>` | Target agent by ID | active agent |
| `--tab <id-or-name>` | Terminal tab ID, or its display name | the agent's active terminal |
| `--tail <n>` | Return only the last N lines | 200 |
| `--json` | JSON output for scripting | plain text |

`--json` returns `{ tabId, name, cwd, state, busy, totalLines, lines: [...] }`. `busy` is the useful one for automation: it distinguishes "the command finished and this is its final output" from "it is still running and there is more to come". `totalLines` is the size of the buffer before `--tail` truncation, so you can tell a complete read from a partial one.

Notes:

* Output is plain text. The scrollback comes from the terminal emulator, which has already interpreted the escape sequences, so there are no colour codes to strip.
* Reads are bounded on purpose. A `tail -f` tab can hold an enormous buffer, and the default cap keeps it from swamping the caller; reads are capped app-side regardless of `--tail`.
* The tab needs a live buffer. Terminals stay mounted once their agent has been on screen, but a tab belonging to an agent never visited since launch has nothing to read yet - select the agent once, then read.
* Tab resolution matches `send-terminal` exactly: an ID matches across every agent, a name only within the target agent.

#### List Open Terminal Tabs

Terminal tabs live in the desktop app, so this asks the running app rather than reading from disk.

```bash theme={"theme":"dracula"}
maestro-cli list terminals              # every agent
maestro-cli list terminals -a <agent-id>
maestro-cli list terminals --json
```

Each row is `state | active-marker | tabId | agent | name | cwd`, with the startup command appended when the tab has one. `*` marks the agent's active terminal (the one `send-terminal` writes to by default).

#### Refresh the File Tree

Refresh the file tree sidebar after creating multiple files or making significant filesystem changes:

```bash theme={"theme":"dracula"}
maestro-cli refresh-files [--agent <id>] [--background]
```

This one never disturbs you: it renders no notice and moves no selection, since the Files panel it refreshes is only drawn for the agent already on screen. `--background` is accepted and ignored, so an agent that passes it on every command does not get a usage error here.

#### Refresh Auto Run Documents

Refresh the Auto Run document list after creating or modifying auto-run documents:

```bash theme={"theme":"dracula"}
maestro-cli refresh-auto-run [--agent <id>] [--background | --focus]
```

Unflagged (or with `--background`), this never moves the view: an agent already on screen is refreshed silently, and an off-screen one is left alone, since its documents are re-read the moment you switch to it anyway. `--focus` **switches to the target agent** and flashes the document count on screen. This is the one verb whose default is background, because a focusing refresh only ever moved you when you were looking at a different agent.

| Flag | Description |
| - | - |
| `--background` | Refresh without switching to the target agent, and without a flash (the default) |
| `--focus` | Switch to the target agent while refreshing, and flash the count |

#### Notifications

Surface notifications in the running desktop app from any script, hook, or agent. Two delivery modes are available, both built on the same five-color design language so they feel unified:

* **Toast** - persistent notification that lands in the toast queue (top-right). Auto-dismisses by default. Use this when you want the user to see a result they may want to act on later, when an OS notification should also fire, or when the message benefits from being clickable to jump to a specific agent. Toasts can be made **sticky** with `--dismissible` so they require an explicit click to dismiss - use this for messages the user must acknowledge.
* **Center Flash** - momentary, single-slot center-screen confirmation that auto-dismisses (default 1.5s, max 5s). Use this for "I did the thing" feedback for a user-initiated action - clipboard acks, quick status nudges, brief success notes. Only one flash is visible at a time; firing a new one replaces the active one.

##### Color palette (shared by both)

Both commands accept `--color`, one of five canonical values:

| Color | Looks like | When to use |
| - | - | - |
| `theme` | Active Maestro theme accent | **Default.** Generic confirmation with no semantic |
| `green` | Success green | Succeeded ("Build passed", "Tests green", "Deploy complete") |
| `yellow` | Warning yellow | Soft heads-up ("Quota at 60%", "Slow query detected") |
| `orange` | Warm orange (`#f97316`) | More emphatic warning ("Approaching context limit", "Quota at 90%") |
| `red` | Error red | Failure / blocked ("CI failed", "Auth expired", "Sync error") |

Pick `theme` when you don't have an opinion - the flash/toast will visually match whatever theme the user is running.

##### Toasts

```bash theme={"theme":"dracula"}
# Default - themed, queue-based, auto-dismisses on the app's default schedule.
maestro-cli notify toast "Build" "Compiled in 3.2s"

# Pick a color and a custom timeout (in seconds, max 60).
maestro-cli notify toast "Tests" "All green" --color green --timeout 10
maestro-cli notify toast "Quota" "Approaching limit" --color orange --timeout 30
maestro-cli notify toast "Tests failing" "12 failures in auth.test.ts" --color red

# Sticky - user must click to dismiss. Cannot combine with --timeout.
maestro-cli notify toast "Action required" "Approve the PR before EOD" \
    --color red --dismissible

# Toast linked to an agent (clicking jumps to it).
maestro-cli notify toast "Auto Run done" "All tasks completed" --agent <agent-id>

# Jump to a specific AI tab inside the agent.
maestro-cli notify toast "Diff ready" "Switch to review tab" \
    --agent <agent-id> --tab <tab-id>

# Open a file in the agent's File Preview pane on click.
maestro-cli notify toast "Patch ready" "Open the diff" \
    --agent <agent-id> --open-file src/foo.ts

# Focus one of the agent's terminal tabs on click. The value is a tab id or
# its name; bare --open-terminal lands on the agent's active terminal tab.
maestro-cli notify toast "Dev server crashed" "Exit code 1" \
    --agent <agent-id> --open-terminal "Dev server"

# Open a URL in an in-app browser tab on the agent, or focus a browser tab
# that is already open (the id `open-browser` printed).
maestro-cli notify toast "Preview ready" "localhost:3000" \
    --agent <agent-id> --open-browser http://localhost:3000
maestro-cli notify toast "Docs updated" "Back to the page you had open" \
    --agent <agent-id> --open-browser-tab <browser-tab-id>

# Open an external URL in the system browser on click (outside Maestro).
maestro-cli notify toast "Run finished" "View logs" \
    --open-url https://example.com/logs

# Render an inline action link beneath the message body (separate from
# the body click). Useful for "view PR" style affordances.
maestro-cli notify toast "PR opened" "Auto Run completed" \
    --agent <agent-id> \
    --action-url https://github.com/org/repo/pull/42 --action-label "View PR"
```

| Flag | Description |
| - | - |
| `-c, --color` | `green \| yellow \| orange \| red \| theme` (default: `theme`) |
| `-t, --timeout <sec>` | Auto-dismiss after N seconds (range: `(0, 60]`; omitted = app default) |
| `--dismissible` | Sticky toast - no auto-dismiss, click to close. Mutually exclusive with `--timeout` |
| `-a, --agent <id>` | Associate with an agent so clicking the toast jumps to it |
| `--tab <id>` | AI tab ID within the agent - clicking jumps to that tab. Requires `--agent` |
| `--open-file <path>` | On click, switch to the agent and open the file in File Preview. Requires `--agent` |
| `--open-terminal [tab]` | On click, focus a terminal tab on the agent (id or name; bare = its active one). Requires `--agent` |
| `--open-browser <url>` | On click, open the URL in a new in-app browser tab on the agent. Requires `--agent` |
| `--open-browser-tab <id>` | On click, focus an existing in-app browser tab. Requires `--agent` |
| `--open-url <url>` | On click, open the URL in the system browser (outside Maestro) |
| `--action-url <url>` | Inline link rendered beneath the message body (separate from the body click - opens in browser) |
| `--action-label <text>` | Label for `--action-url` (defaults to the URL itself); requires `--action-url` |
| `--json` | JSON output for scripting |

The body-click hierarchy is: the `--open-*` flags (mutually exclusive with each other) > `--agent` (+ optional `--tab`). A click on the body can therefore land on an AI tab, a File Preview tab, a terminal tab, an in-app browser tab, or the system browser. When the target tab has since been closed, the click still switches to the agent and says what was missing. `--action-url` is independent - it renders a separate inline link button and does not affect the body click.

##### Center Flash

```bash theme={"theme":"dracula"}
# Default - themed, auto-dismisses after 1.5s.
maestro-cli notify flash "Deployed"

# Pick a color. Use --timeout in seconds (max 5).
maestro-cli notify flash "Tests passed" --color green
maestro-cli notify flash "Production deploy starting" --color orange --detail "v1.42.0"
maestro-cli notify flash "CI failed on main" --color red --timeout 5

# Add a second line of detail.
maestro-cli notify flash "Cache cleared" --detail "1.2 GB freed" --timeout 3
```

| Flag | Description |
| - | - |
| `-c, --color` | `green \| yellow \| orange \| red \| theme` (default: `theme`) |
| `-D, --detail` | Optional mono-font second line shown beneath the message |
| `-t, --timeout` | Auto-dismiss after N seconds (range: `(0, 5]`; default 1.5) |
| `--json` | JSON output for scripting |

##### Caps and dismissibility

External (CLI/web) callers are capped to **5 seconds** for Center Flash and **60 seconds** for Toast. The cap exists so external scripts can't stick a permanent overlay on the user. The only way to leave a notification on screen indefinitely is `--dismissible` on a toast - there is no equivalent for Center Flash (it is, by design, momentary).

Both commands support `--json` for scripting. Toasts respect the user's notification settings (audio feedback, OS desktop notifications) configured in the app.

### Configuring Auto-Run

Set up and optionally launch an auto-run session with one or more markdown documents. Documents must be `.md` files containing `- [ ]` checkbox tasks.

```bash theme={"theme":"dracula"}
# Configure documents for auto-run
maestro-cli auto-run doc1.md doc2.md

# Configure and immediately launch
maestro-cli auto-run doc1.md doc2.md --agent <agent-id> --launch

# Add a custom prompt for the agent
maestro-cli auto-run doc1.md --prompt "Focus on test coverage"

# Save as a reusable playbook
maestro-cli auto-run doc1.md doc2.md --save-as "Auth Rewrite"

# Enable looping (re-run documents after completion)
maestro-cli auto-run doc1.md --loop --launch

# Loop with a maximum number of iterations
maestro-cli auto-run doc1.md --loop --max-loops 3 --launch

# Reset task checkboxes on completion (useful with looping)
maestro-cli auto-run doc1.md --reset-on-completion --loop --launch

# Run the auto-run inside a fresh git worktree on a dedicated branch
maestro-cli auto-run doc1.md --agent <agent-id> --launch \
  --worktree --branch feature/auto-x --worktree-path ../repo-auto-x

# Open a PR against the repo's default branch when the auto-run finishes
maestro-cli auto-run doc1.md --agent <agent-id> --launch \
  --worktree --branch feature/auto-x --worktree-path ../repo-auto-x \
  --create-pr

# Target a specific base branch for the PR
maestro-cli auto-run doc1.md --agent <agent-id> --launch \
  --worktree --branch feature/auto-x --worktree-path ../repo-auto-x \
  --create-pr --pr-target-branch develop

# Run this one auto-run on a different model than the agent's default
maestro-cli auto-run doc1.md --agent <agent-id> --launch --model opus

# Override the reasoning effort too (provider-dependent)
maestro-cli auto-run doc1.md --agent <agent-id> --launch --model opus --effort high
```

| Flag | Description |
| - | - |
| `-a, --agent <id>` | Target agent to run the documents (partial ID supported) |
| `-p, --prompt <text>` | Custom prompt/instructions for the agent |
| `--loop` | Enable looping (re-run documents after completion) |
| `--max-loops <n>` | Maximum number of loop iterations (implies `--loop`) |
| `--save-as <name>` | Save the configuration as a named playbook |
| `--launch` | Immediately start the auto-run after configuring |
| `--reset-on-completion` | Reset task checkboxes when documents complete |
| `--worktree` | Run the auto-run inside a git worktree (requires `--launch`, `--branch`, and `--worktree-path`) |
| `--branch <name>` | Branch name for the worktree (created if it does not exist) |
| `--worktree-path <path>` | Filesystem path for the worktree (must be a sibling of the repo, not nested inside it) |
| `--create-pr` | Open a GitHub PR when the auto-run completes successfully |
| `--pr-target-branch <branch>` | Target branch for the PR (defaults to the repo's default branch) |
| `--model <model>` | Model to use for this run only, overriding the agent's configured default |
| `--effort <effort>` | Reasoning effort for this run only, overriding the agent's configured default |
| `--ignore-model-hints` | Skip the documents' `MAESTRO:MODEL` markers; every task runs at `--model`/`--effort` or the agent default |

`--model` and `--effort` are **run-scoped**: they apply to every task spawn in
this auto-run and are never written back to the agent. The agent's interactive
tabs keep using its configured default, and the override disappears when the run
ends. Omit them to use the agent default. They are honored in worktree mode too,
without changing the child worktree session's own configured model. See
[Per-run model override](#per-run-model-override) for the full picture.

Every document must sit inside the agent's Auto Run folder. A saved playbook
stores each one relative to that folder, so `--save-as` and `--launch` both
refuse a document outside it and name the file. When a saved playbook names a
document that no longer exists, `maestro-cli playbook` fails with
`DOCUMENT_NOT_FOUND` and lists the missing paths.

Worktree mode reuses the desktop app's Auto Run pipeline: the app creates the
worktree (or reuses an existing one on the same repo), checks out the requested
branch, dispatches the agent inside the worktree, and - when `--create-pr` is
set - runs `gh pr create` once the batch completes. See
[Git Worktrees](https://docs.runmaestro.ai/git-worktrees.md) for more on worktree behavior.

### Controlling a Running Auto Run

Once an Auto Run is going, these commands stop it or recover it from an error pause - the counterpart to launching with `auto-run --launch`. They require the desktop app to be running.

```bash theme={"theme":"dracula"}
# Stop the active Auto Run for an agent
maestro-cli stop-auto-run -a <agent-id>

# When an Auto Run pauses on an error, choose how to proceed:
maestro-cli resume-auto-run -a <agent-id>   # clear the error and continue
maestro-cli skip-auto-run -a <agent-id>     # skip the failing document, continue with the next
maestro-cli abort-auto-run -a <agent-id>    # stop the run entirely

# Revert all completed [x] tasks back to [ ] in one document so it can re-run
maestro-cli reset-auto-run-tasks loop/step-1.md -a <agent-id>

# Delete a saved playbook (find IDs with "list playbooks -a <agent-id>")
maestro-cli remove-playbook <agent-id> <playbook-id>
```

The filename for `reset-auto-run-tasks` is relative to the agent's Auto Run folder; absolute paths and `..` traversal are rejected.

### Steering a Running Auto Run

A steering note changes a run's direction without stopping it: the note parks until the run dispatches its next task, then opens that task's prompt. These are the CLI half of the **Steer Auto Run** button in the Thought Stream. See [Steering a Run in Flight](https://docs.runmaestro.ai/autorun-playbooks.md#steering-a-run-in-flight) for what the agent is told to do with a note.

```bash theme={"theme":"dracula"}
# Send a note; it is delivered at the start of the next task
maestro-cli steer-auto-run send "Use the v3 endpoint for the rest of these tasks" -a <agent-id>

# Read the notes still waiting, and each delivered note with its task's reply
maestro-cli steer-auto-run list -a <agent-id>
maestro-cli steer-auto-run list -a <agent-id> --json   # includes each full reply

# Take back a note no task has read yet (accepts a unique id prefix)
maestro-cli steer-auto-run cancel <note-id> -a <agent-id>
```

`send` is refused when no Auto Run is active on the agent, or when the run belongs to another Maestro client: there is no next task to hand the note to. A note longer than 4000 characters is refused rather than cut to fit. `list` keeps working after the run ends, since the reply to a run's last note arrives as it finishes; the notes are cleared when the next run starts. `send --background` queues the note without the on-screen "Steering note queued" flash.

### Checking Status

Check if the Maestro desktop app, or a [headless host](#headless-host-maestro-cli-host), is running and reachable:

```bash theme={"theme":"dracula"}
maestro-cli status
```

Returns the port and agent count, and names a headless host as one. With nothing running, it says so and points at `maestro-cli host start`.

### Diagnosing Problems (`doctor`)

When a command isn't working, `doctor` runs a checklist covering the most common causes in one shot: the desktop app reachable, the running build's version vs. this CLI's, whether the running app understands newer commands, and whether configured SSH remotes are well-formed.

```bash theme={"theme":"dracula"}
maestro-cli doctor
maestro-cli doctor --json
```

```
  ✓ Discovery file present - port 54748
  ✓ App process alive - pid 10510
  ⚠ Version match - App is 0.17.1 but CLI is 0.17.2. Rebuild/restart whichever is behind.
  ✓ WebSocket reachable
  ✓ App handles commands
  ✓ SSH remotes - 2 configured, all well-formed
```

The version and "App handles commands" checks catch the most common gotcha: a freshly-built CLI talking to an older desktop app that's still running. When the app is behind, new commands fail because their handlers don't exist in the running build - rebuild and restart the desktop app. The CLI surfaces this directly: a command the running app doesn't recognize fails fast with "The running Maestro app does not support the '...' command" instead of a generic timeout.

### Shell Completions

Generate a completion script for your shell and source it:

```bash theme={"theme":"dracula"}
# zsh - add to a directory on your fpath, or source from ~/.zshrc
maestro-cli completions zsh > ~/.maestro-cli-completion.zsh
echo 'source ~/.maestro-cli-completion.zsh' >> ~/.zshrc

# bash
maestro-cli completions bash >> ~/.bashrc

# fish
maestro-cli completions fish > ~/.config/fish/completions/maestro-cli.fish
```

The script is generated by introspecting the live command tree, so regenerating it after a CLI upgrade picks up new commands and flags automatically. The full command list is also available as `maestro-cli reference` (Markdown or `--format json`); [docs/cli-reference.md](https://docs.runmaestro.ai/cli-reference.md) is generated from it via `npm run gen:cli-reference`.

## Headless Host (`maestro-cli host`)

`maestro-cli host` runs Maestro's runtime with no desktop app: on a server, in a container, or on a laptop where the app is closed. The host owns the data directory the way the desktop does and serves the same WebSocket bridge, so `maestro-cli` commands attach to it exactly as they attach to the app. It runs:

* **Agents**: create, update, rename, move between groups, and remove them.
* **Chat turns** sent with `maestro-cli dispatch` (including `--new-tab` and `--queue`). A message to a busy agent waits its turn in the agent's queue instead of being turned away.
* **Auto Run**: `maestro-cli auto-run --launch` and goal-driven runs, with `auto-run stop`, `resume`, `skip`, and `abort`. A run keeps going after the terminal that started it closes.
* **Group chats** and **consults** between agents.
* **Maestro Cue**, when Cue is on in the shared settings and no other engine holds the Cue lock. This is the only way to run Cue subscriptions with `action: autorun` without the desktop: `maestro-cli cue engine start` has no runtime to run an Auto Run in and fails those runs.

```bash theme={"theme":"dracula"}
# Start a detached host on the default data directory
maestro-cli host start

# Is it up, and what is it doing?
maestro-cli host status

# Stop it (refuses while work is in flight)
maestro-cli host stop

# Wait up to 10 minutes for the work in flight, then stop
maestro-cli host stop --wait 600
```

### `host start`

Starts the host as a detached process and returns once it is listening. The host keeps running after the shell that started it exits.

| Flag | Description | Default |
| - | - | - |
| `--data-dir <path>` | Maestro data directory to serve | resolved like the desktop app |
| `--dev` | Use the development data directory | - |
| `--port <port>` | Port to listen on (always `127.0.0.1`) | any free port |
| `--stop-grace <seconds>` | On SIGTERM or SIGINT, wait this long for the work in flight before stopping. `0` stops at once | `30` |
| `--no-prevent-sleep` | macOS: let the Mac sleep even while work is in flight. By default the host holds a `caffeinate -i` child while a turn, an Auto Run, a group chat round, a consult or a Cue run is in flight, and releases it when idle. No effect on other platforms | - |
| `--foreground` | Serve in this process instead of detaching. What the detached child runs, and what a service manager such as systemd should run | - |
| `--json` | Output as JSON (for scripting) | - |

`start` reports the pid, the port, the log file, and where Cue stands. `host status --json` reports `preventingSleep: true` while a macOS host holds the Mac awake. A Cue that did not start does not fail the start: the host still serves turns and Auto Runs, and the output says Cue is not running and why.

**Signals.** SIGTERM or SIGINT (`systemctl stop`, `systemctl restart`, Ctrl+C on `--foreground`) drains the host: it waits up to `--stop-grace` seconds for chat turns, Auto Runs, group chat rounds, consults, and Cue runs to finish, then stops. A second signal stops it at once. New work is not turned away during the wait, so work that starts in it is waited for too, up to the same deadline. Keep the grace below your service manager's own stop timeout (systemd sends SIGKILL after 90 seconds by default), with a few seconds to spare: Cue runs still going when the grace runs out get up to about 7 more seconds to exit after they are stopped.

Cue drains the way [`cue engine start`](https://docs.runmaestro.ai/maestro-cue-server#stop) does. On the first signal every trigger is disarmed at once, so no subscription fires while the host waits, and events already accepted by Cue remain queued instead of run. Cue runs in flight get the same `--stop-grace`; the ones still running when it ends are stopped and recorded as `stopped`. Queued events and fan-ins still waiting on sources are saved and pick up on the next start of whichever Cue engine serves the data directory. A second signal stops every Cue run and kills its processes at once, and still saves the queue. `host stop` and a host that lost its data directory drain Cue the same way with no wait. Switching Cue off in the settings while the host runs is not a shutdown: it stops the runs and clears the queue, as on the desktop.

### `host status`

Reports the host's pid, uptime, version, the holder of the data directory's lock, how many clients are attached, the work in flight, and the Cue state. If another Cue engine takes the Cue lock over while the host runs (the host was suspended long enough for its lock to go stale, say), the host stops its Cue runs and gives Cue up, and the Cue state names the new holder (`not running here: desktop pid 1234 holds the Cue lock`) instead of `running`. The host does not take Cue back on its own: switching Cue off and on again in the settings, or restarting the host, tries again. With no host it exits with code `3` and names whoever holds the lock, if anyone does (a TUI hosting in its own process, say).

| Flag | Description | Default |
| - | - | - |
| `--data-dir <path>` | Maestro data directory | resolved like the desktop app |
| `--dev` | Use the development data directory | - |
| `--json` | Output as JSON (for scripting) | - |

### `host endpoint`

Prints the endpoint of the host serving the data directory, for [Federation](https://docs.runmaestro.ai/federation.md) over SSH: a laptop runs `maestro-cli host endpoint --json` on the remote through the SSH remote it already has, and SSH is the authentication. With `--json` it prints `{running, port, token, cliSecret, version, pid}`, or `{running: false}` with exit code `3` when no host is running. Without `--json` it prints the pid, port and version only: the token and the CLI secret never reach a terminal or a log. On macOS and Linux it refuses, and prints neither, when the discovery file (`cli-server.json`) can be read by any user but its owner.

| Flag | Description | Default |
| - | - | - |
| `--data-dir <path>` | Maestro data directory | resolved like the desktop app |
| `--dev` | Use the development data directory | - |
| `--json` | Output as JSON, with the token and the CLI secret | - |

### `host stop`

Asks the host to stop and waits for its process to exit. With work in flight (a chat turn, an Auto Run, a group chat round, a consult, or a Cue run) it refuses, names the work, and exits `1`, unless `--wait` or `--force` says otherwise.

| Flag | Description | Default |
| - | - | - |
| `--data-dir <path>` | Maestro data directory | resolved like the desktop app |
| `--dev` | Use the development data directory | - |
| `--wait [seconds]` | Instead of refusing, wait for the work in flight to finish, then stop. If work is still running at the deadline, exit `5` and leave the host running. Never forces | `300` when given no value |
| `--force` | Stop even with work in flight. A running Auto Run records how it ended first | - |
| `--json` | Output as JSON (for scripting) | - |

### `remote-host install`, `remote-host status`, and `remote-host start`

Install, check, and start the `maestro-cli host` on an SSH remote, for [Federation](https://docs.runmaestro.ai/federation.md) over SSH. Federation is opportunistic: every SSH remote takes part unless it opted out with `update-ssh-remote <id> --federation off`, and these verbs refuse a remote that opted out. The `<ssh-remote>` argument is the remote's name or its ID (a unique prefix works).

`remote-host install` copies this machine's `maestro-cli` to the remote over one SSH call, as the SSH user, and installs it under `~/.maestro`. The same version runs on both sides, so there is no version skew. The bundle is plain JavaScript; what differs per platform is Node.js and the SQLite module, and the remote picks both for its own OS and CPU:

| On the remote | What it uses |
| - | - |
| Operating system | Linux, macOS, or Windows through Git Bash or WSL (the same POSIX shell an SSH agent needs there) |
| CPU | x64 or arm64 |
| Node.js | Its own Node.js 22 or newer when it has one, else Node.js 24 from nodejs.org, checked against its SHA-256 list |
| SQLite (`better-sqlite3`) | Installed with npm for that Node.js. A prebuilt binary when one exists, else built from source (needs python3, make, and a C++ compiler) |

The new install is staged next to the old one and swapped in only once SQLite loads and the CLI runs, so a failed install leaves the old one working. A second run with the same version does nothing; an older install is upgraded; a newer one is left alone. `~/.maestro/bin` comes first on the PATH every SSH spawn gets, so the installed CLI wins over an older copy.

| Flag | Description | Default |
| - | - | - |
| `--start` | Start the host once the CLI is in place. A desktop app that runs on the remote tells it, too | - |
| `--force` | Install even when the remote has a `maestro-cli` Maestro did not install (Maestro.app, the server bundle). Maestro's copy then takes precedence; the other one is not touched | - |
| `--restart` | Replace a running host on an older version: stop it with `host stop --wait` (work in flight finishes first), upgrade, start it again. Without it, the install refuses with `host-running` | - |
| `--no-service` | Do not register the host with the remote's service manager. By default the install writes a systemd user unit (Linux) or a launchd agent (macOS without Maestro.app), turns lingering on where the SSH user may, and lets the service start the host | - |
| `--timeout <seconds>` | Give up on the install after this many seconds | `600` |
| `--json` | Output as JSON (for scripting), with the `cli` action (`installed`, `upgraded`, `current`, `newer`), the platform, the Node.js version and where it came from, and the start result | - |

```bash theme={"theme":"dracula"}
maestro-cli remote-host install build-box --start
maestro-cli remote-host install build-box --restart   # upgrade a running host
```

A refusal names its cause and the fix, with a `code` in `--json`: `unsupported-os`, `unsupported-arch`, `foreign-cli`, `host-running`, `node-download` (the remote cannot reach nodejs.org and has no Node.js 22+), `sqlite-install`, and so on. It never asks for sudo and runs only as the SSH user, and the install writes nothing outside `~/.maestro` (npm's cache goes to `~/.maestro/npm-cache` too). Registering the service adds `~/.config/systemd/user/maestro-host.service` or `~/Library/LaunchAgents/sh.maestro.host.plist`, unless `--no-service`. The launcher finds Node.js each time it runs (Maestro's own copy, then the one used at install time, then `node` on PATH), and an install whose launcher no longer runs is replaced by `remote-host install --force` (the desktop offers **Reinstall maestro-cli**). The new launcher is written before the swap, and the old install comes back if either step fails.

`remote-host status` makes one SSH call and reports whether Maestro is installed on the remote (with the fix when it is not), whether a host is running there (its pid, its port on the remote's loopback and its version), and the version skew against this CLI: `none`, `remote-older`, `remote-newer` or `unknown`. It exits `0` with a running host and `3` when no host runs or Maestro is not installed. `remote-host start` runs `maestro-cli host start` on the remote, as the SSH user, when no host is running there, then reports status the same way. It does nothing when a host already runs. The SSH calls run one after the other, never at the same time. Neither verb prints the host's token or CLI secret, with or without `--json`. A timeout exits `5`, and a remote CLI too old to know `host endpoint` exits `4`.

```bash theme={"theme":"dracula"}
maestro-cli remote-host status build-box
maestro-cli remote-host start build-box --json
```

| Flag | Description | Default |
| - | - | - |
| `--timeout <seconds>` | Give up on each SSH call after this many seconds | `60` |
| `--json` | Output as JSON (for scripting) | - |

### Agents on a Peer

A peer is an SSH remote that runs a `maestro-cli host` (and has not opted out of Federation). Its peer name is the remote's name, or the remote's ID when two remotes share a name. `list agents --peer <name>` reads the agents from that host over the SSH forward and prints them with the peer name beside each row. Each ID line reads `peer:agent-id`, the form other verbs take as a target. `list agents --all-peers` prints the local agents, then the agents on every enabled SSH remote that has not opted out of Federation. It visits the peers one after another, never at the same time. With `--json` each row has a `peer` field: the peer name, or `null` for a local agent in an `--all-peers` list.

The host is the only record of its agents: Maestro reads them fresh every time and never writes them to the local agent store. A peer that cannot be reached is an error that names the fix (`maestro-cli remote-host start <peer>` when no host runs). `--all-peers` lists the peers it reaches first, then reports each peer it could not reach on stderr and exits with that failure's code (`3` when a host is down). Neither flag combines with `--group`, which filters local agents.

These verbs take a `peer:agent` target (an agent ID, ID prefix, or name after the first colon) and act on the host's agent. Each prints what it prints for a local agent, plus a `peer` field in its JSON:

```bash theme={"theme":"dracula"}
maestro-cli show agent build-box:docs --json        # the host's record and its tabs; stats is null
maestro-cli send build-box:docs "Summarize the open PRs"
maestro-cli ask build-box:docs "Which branch is checked out?"
maestro-cli dispatch build-box:docs "Run the release checklist" --new-tab
maestro-cli interrupt build-box:docs
maestro-cli tab new --agent build-box:docs
maestro-cli tab rename <tab-id> "Release" --agent build-box:docs
maestro-cli tab star active --agent build-box:docs
maestro-cli queue list --agent build-box:docs
maestro-cli queue remove <item-id> --agent build-box:docs
```

| Verb | On a peer |
| - | - |
| `show agent` | Reads the agent from the host and lists its tabs with their state. `stats` and `recentHistory` come from the host's History, which includes the project's shared History. Each recent row has a `hostname` when another machine sent it. A host that cannot serve History gives `stats: null`. |
| `send` | Opens a new tab on the host (or the tab that holds `--session`, which must be idle), sends the message, and waits for the turn to end. The host records the turn in its own History. `--read-only`, `--tab`, `--no-system-prompt`, `--no-history`, `--no-synopsis` and the plugin-tool flags are refused (`PEER_UNSUPPORTED_OPTION`). |
| `ask` | Sends the same consult to the host. `--from` and `--with-context` name a local agent the host cannot see, so they are refused. |
| `dispatch` | Sends the same message as a local dispatch to the host. `--notify-on-complete`, the `--callback-*` flags and `--routing` are refused, because they name local agents. A lost acknowledgement is `DISPATCH_UNKNOWN`, as it is locally: reconcile with the same `--dispatch-id`. |
| `interrupt` | Stops every busy tab of the agent on the host, or the one `--tab` names. |
| `tab new`, `tab rename`, `tab star`, `tab unstar` | With `--agent <peer:agent>`, open, rename, star or unstar a tab of the host's agent. `<tab-id>` is an ID, a unique prefix, or `active`, matched against the host's tabs. `tab new --prompt` is refused: open the tab, then `send`, or use `dispatch`. |
| `queue list`, `queue remove`, `queue hold`, `queue resume` | With `--agent <peer:agent>`, read or change the messages waiting in the host's queue for that agent. `queue list` prints the local shape plus `peer`, with `sessionId` set to the `peer:agent` target. A message that already started is `ITEM_NOT_FOUND`, as it is locally. `queue merge` and `queue steer` are refused (`PEER_UNSUPPORTED_VERB`). |

`send`, `interrupt`, the tab verbs, and the queue verbs run the same shared action as the desktop's mirrored agent (its composer, Stop, the tab controls beside its tab strip, and its queued cards), so a script and the desktop reach the host the same way. Nothing is queued or retried on this machine. A peer that is down, or a forward that is dead, exits non-zero with a `PEER_*` code (`PEER_HOST_DOWN` exits `3`). If the forward drops while `send` waits, the turn keeps running on the host: `send` exits `3` with `PEER_CONNECTION_LOST`, the tab ID, and the command that shows the tab (`maestro-cli show agent <peer>:<agent>`). A colon target that names a local agent (a name like `Maestro: rc`) stays local.

### Lift an SSH Agent Onto Its Host

`maestro-cli lift <agent>` moves an SSH remote agent onto the `maestro-cli host` on its remote. The provider already ran on that box as the SSH user, so its session files are already there. The host gets an agent with the agent's remote working directory (not its local one), provider, model, effort and arguments, plus every visible tab with its transcript and the same provider session ID, so the next turn resumes the conversation. Queued messages move with it. After the lift, the local agent keeps every tab and transcript, but it is a pointer: `list agents` shows `moved to peer:agent-id`, and every send to it is refused with that target (`AGENT_LIFTED`).

Env vars: every non-secret custom env var moves. Secret ones stay here unless you pass `--with-env`. The variable that selects the provider's config or session directory (`CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `COPILOT_HOME`) always moves, and the host refuses the agent when that directory does not exist there, because the provider would start a new session instead of resuming.

Before it acts, `lift` prints what moves and what stays. `--json` gives the same plan, and `--dry-run` stops after it. It refuses, and moves nothing, when:

| Refusal | Code |
| - | - |
| The agent was already lifted | `LIFT_ALREADY_LIFTED` |
| The agent is not an SSH remote agent | `LIFT_NOT_SSH` |
| Its SSH remote opted out of Federation | `PEER_FEDERATION_OFF` |
| Its SSH remote is disabled | `LIFT_REMOTE_DISABLED` |
| A tab is running a turn | `LIFT_BUSY` |
| No host is running on the remote | `PEER_HOST_DOWN` (exit 3) |
| A local `maestro-cli host` owns this machine's agents | `LIFT_LOCAL_HOST` |

The host's copy is made first. If the local agent cannot then be marked as moved, the host's copy is removed again, so the agent never runs in two places. Hidden consult tabs, queued slash commands, and images in this machine's image store stay here.

```bash theme={"theme":"dracula"}
maestro-cli lift docs --dry-run
maestro-cli lift docs --with-env --json
maestro-cli send build-box:<new-agent-id> "Carry on"
```

The desktop app runs the same lift. Right-click the agent in the Left Bar and choose **Move to Host**, or run **Move to Host** from the command palette. The action shows while the agent's remote takes part in Federation. When the remote runs no host yet, the same action first runs `remote-host install --start` and then shows the lift plan. Either way the plan `--dry-run` prints, with a choice to send secret env vars, shows before anything moves. Afterwards the agent's row shows `on <peer>`: click it to open the agent on its host.

### One Host Per Data Directory

A data directory has one owner at a time: a lock file (`maestro-runtime.lock`) in the directory says who. `host start` refuses a directory the desktop app or another host already holds, and says which. The desktop app will not open on a directory a headless host holds: it shows a dialog naming the host and quits, because loading its stores on top of the host's would overwrite the host's writes. Stop the host with `maestro-cli host stop`, then open Maestro.

The data directory is resolved the way the desktop app resolves it (under `~/Library/Application Support` on macOS, `$XDG_CONFIG_HOME` or `~/.config` on Linux, `%APPDATA%` on Windows). `--data-dir <path>` or the `MAESTRO_USER_DATA` environment variable points the host somewhere else, and every other `maestro-cli` command honors the same variable, so set it in the environment of the commands that should reach that host. A directory that settings sync through a custom sync path is refused: the lock cannot see another machine writing there.

The host's log is `logs/maestro-host.log` inside the data directory. When `start` fails before the host is ready, it prints the last lines of that log.

### What the Host Does Not Do

The host refuses these in so many words, and nothing is started when it does:

| Request | Why |
| - | - |
| `update-agent --provider` or `--migration` | Native conversation translation requires the desktop app |
| Images on a turn | Not sent from a headless host yet. Send the message without them, or use the desktop app |
| A terminal-mode command | The host has no terminal. Only AI messages can be sent to it |
| `dispatch --notify-on-complete` | The host cannot arm a completion callback. Dispatch without it and poll the tab |
| `dispatch --held` | The host's queue would run the message as soon as the agent is free |
| Auto Run for an agent on an SSH remote | Runs on the desktop for now |
| `auto-run --worktree`, and Cue Auto Runs that target a worktree | The desktop app creates the worktree and its branch |
| `auto-run --save-as` | Playbooks are saved by the desktop app |
| `auto-run` without `--launch` | The host has no Auto Run panel to fill |

Commands that drive the desktop's window, such as opening a file or a browser tab, focusing an agent or tab, or raising a toast, fail with "The headless Maestro host (`maestro-cli host`) does not support the '...' command".

### Installing on a Machine With No Desktop

The host is the CLI bundle, run with Node.js. For a machine you reach over SSH, `maestro-cli remote-host install <ssh-remote>` (above) does all of this from your laptop. By hand, on a machine without the Maestro app:

* **Node.js 22 or newer.**
* **The CLI bundle with its prompts**: copy `maestro-cli.js` together with the `prompts/core` directory beside it. Without the prompts the host refuses to start, because a turn would have no Maestro system prompt and an Auto Run could not run.
* **`better-sqlite3` built for that Node**, installed next to the bundle: `npm install --prefix <dir of maestro-cli.js> better-sqlite3`. The host records usage and Cue history in SQLite.
* **The provider CLIs** your agents use (Claude Code, Codex, OpenCode, and so on), on the host's `PATH`.

To keep the host running across reboots, have your service manager run `maestro-cli host start --foreground` (with `--data-dir` if the directory is not the default) and stop it with SIGTERM, which drains as described above. [Run the Host as a Service](#run-the-host-as-a-service) has the unit files.

### Automatic Federation from the CLI

The desktop app keeps Federation hosts running and, with **Move SSH agents to their host automatically** on, installs hosts and moves SSH agents onto them by itself ([how it decides](https://docs.runmaestro.ai/federation.md#automatic-moves-and-their-sanity-checks)). Two verbs show and drive it:

```bash theme={"theme":"dracula"}
maestro-cli federation auto            # every remote and SSH agent, its state, and what needs you
maestro-cli federation auto run        # run a pass now (Run Now in Settings > SSH Hosts)
maestro-cli settings set federationAutoMove false   # turn automatic moves off
```

Both print each remote's state (`ready`, `setting-up`, `waiting`, `blocked`) with its service, and each SSH agent's state (`moved`, `pending`, `waiting`, `blocked`, `manual`) with its reason. Anything `blocked` carries a `To fix:` line. Both exit `1` when something needs a person: a `blocked` remote or agent, or a running host whose service still needs one step (lingering off, or a service that failed to register). A remote that can never have a service (Windows, Linux without a user session, a Mac with Maestro.app) shows its workaround as a note and does not make them exit `1`. `--json` prints the same snapshot. They need the desktop app: a headless host mirrors no peers.

## Run the Host as a Service

`maestro-cli host start` detaches, but nothing starts it again after a reboot or a crash. A service manager does both. For a host you set up from a laptop, `remote-host install` (and the desktop's automatic Federation) installs the service for you; see [Federation durability](https://docs.runmaestro.ai/federation.md#durability). The files below are for a host you set up by hand: copy the one for your platform and change the paths.

**Run the service as the user your SSH agents run as.** The host and the SSH agents then share one home directory, so the host reads the same provider logins and session files. A host that runs as another user cannot resume the provider sessions of an agent lifted onto it. This is not the `maestro` system user that the [server bundle](https://docs.runmaestro.ai/maestro-cue-server.md) creates for a dedicated Cue engine: that user is for an engine that owns its whole machine, and an SSH agent you start does not run as it.

The service manager starts the host with a small environment, not your login shell's. Put the directories of the provider CLIs your agents use (Claude Code, Codex, and so on) on the service's `PATH`, as both files below do. Run `command -v claude` (or the CLI you use) in your own shell to find them.

Do not run the service on a data directory the desktop app also opens. While the desktop app holds the directory, the host refuses to start, and the service manager starts it again and again.

### systemd (Linux)

Save this as `~/.config/systemd/user/maestro-host.service`. `ExecStart` takes the absolute path of your `maestro-cli` wrapper (`command -v maestro-cli` prints it; `%h` is your home directory):

```ini theme={"theme":"dracula"}
[Unit]
Description=Maestro headless host
After=network-online.target

[Service]
Type=simple
ExecStart=%h/.local/bin/maestro-cli host start --foreground
Environment=PATH=%h/.local/bin:/usr/local/bin:/usr/bin:/bin
Restart=on-failure
RestartSec=10
# Keep --stop-grace (30 s by default) below this, with a few seconds to spare
TimeoutStopSec=90

[Install]
WantedBy=default.target
```

Then enable it, and turn on lingering so the host keeps running after you log out and starts at boot before anyone logs in:

```bash theme={"theme":"dracula"}
systemctl --user daemon-reload
systemctl --user enable --now maestro-host
loginctl enable-linger "$USER"

systemctl --user status maestro-host
journalctl --user -u maestro-host
```

Without lingering, systemd-logind stops your user's services, the host with them, when your last session ends. `host start` and `host status` warn when lingering is off for your user (`linger: false` in `--json`), and `remote-host status` passes that warning through to the laptop.

### launchd (macOS)

Save this as `~/Library/LaunchAgents/sh.maestro.host.plist`. It runs the CLI under the app's own executable, the same command the wrapper runs:

```xml theme={"theme":"dracula"}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>Label</key>
	<string>sh.maestro.host</string>
	<key>ProgramArguments</key>
	<array>
		<string>/Applications/Maestro.app/Contents/MacOS/Maestro</string>
		<string>/Applications/Maestro.app/Contents/Resources/maestro-cli.js</string>
		<string>host</string>
		<string>start</string>
		<string>--foreground</string>
	</array>
	<key>EnvironmentVariables</key>
	<dict>
		<key>ELECTRON_RUN_AS_NODE</key>
		<string>1</string>
		<key>PATH</key>
		<string>/Users/you/.local/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin</string>
	</dict>
	<key>RunAtLoad</key>
	<true/>
	<key>KeepAlive</key>
	<dict>
		<key>SuccessfulExit</key>
		<false/>
	</dict>
	<key>ThrottleInterval</key>
	<integer>10</integer>
	<!-- Seconds launchd waits after SIGTERM before SIGKILL (default 20). Keep above stop-grace -->
	<key>ExitTimeOut</key>
	<integer>40</integer>
</dict>
</plist>
```

Replace `/Users/you` with your home directory: launchd does not expand `~` or `$HOME`. `KeepAlive` with `SuccessfulExit` set to false starts the host again when it exits with an error, and leaves it stopped after a clean stop. Load it, and check it:

```bash theme={"theme":"dracula"}
launchctl bootstrap "gui/$(id -u)" ~/Library/LaunchAgents/sh.maestro.host.plist
launchctl print "gui/$(id -u)/sh.maestro.host"

# Stop it (SIGTERM, which drains) and unload it
launchctl bootout "gui/$(id -u)/sh.maestro.host"
```

A LaunchAgent runs while you are logged in to the Mac. On a Mac mini host, turn on automatic login so the host starts after a reboot. The host keeps the Mac awake while work is in flight (see `--no-prevent-sleep` under [`host start`](#host-start)).

## Cue Automation

Interact with Maestro Cue subscriptions directly from the command line.

### Listing Subscriptions

List all Cue subscriptions across all agents:

```bash theme={"theme":"dracula"}
maestro-cli cue list

# JSON output (for scripting)
maestro-cli cue list --json
```

Shows each subscription's name, event type, agent, enabled status, and last trigger time.

### Recent Runs

```bash theme={"theme":"dracula"}
# The 20 newest runs across every agent
maestro-cli cue activity

# One agent's 5 newest, as JSON
maestro-cli cue activity --agent <agent-id> --limit 5 --json
```

Each line is a run's start time, status (`running`, `completed`, `failed`), subscription, event type, and duration (or how long a running one has run so far).

### Turning a Subscription On or Off

```bash theme={"theme":"dracula"}
maestro-cli cue disable nightly-report
maestro-cli cue enable nightly-report --agent <agent-id>
```

This writes the subscription's `enabled` flag into its cue.yaml, as the switch on the Cue dashboard does. Pass `--agent`, or the full id from `cue list --json`, when two agents share the name.

### Where the Answer Comes From

`cue list`, `cue activity`, `cue enable`, and `cue disable` ask whatever serves the data directory (`--data-dir`, or `MAESTRO_USER_DATA`, or the platform default):

| Serving the data directory | `cue list` / `cue activity` | `cue enable` / `cue disable` |
| - | - | - |
| The desktop app | The app's engine answers (run output included under `--json`) | The app's engine writes it |
| `maestro-cli host`, running Cue | The host's engine answers, the same rows the desktop shows (run output included under `--json`) | The host's engine writes it |
| `maestro-cli host`, not running Cue (another engine holds the Cue lock, or Cue did not start), or an older host | Read from each agent's cue.yaml and from `cue.db`. A run in flight in another engine still reads `running`. Run output is not included even under `--json`, and a line on stderr says where the list came from | Refused, with the reason and what to do |
| Nothing (`cue activity` only) | Read from `cue.db`, with the same stderr note. `cue list` reports that the app is not running (exit 3) | Reports that the app is not running (exit 3) |

A host draining after SIGTERM or SIGINT keeps answering reads (`cue list` and `cue activity`) and refuses `cue enable`, `cue disable`, and `cue trigger` until its Cue runs have finished. `host stop` (any form) unpublishes first, so from then on reads fall back as if no host were running (`cue list` reports exit 3, `cue activity` reads `cue.db`). If another engine takes the Cue lock over from a host, the host stops answering for Cue, so reads come from disk and a refused change names the engine that now holds the lock.

An older desktop build that does not know a command, or a peer that does not answer in time, is still reported as an error (exit 4 or 5): the CLI never covers a real failure with figures from disk. With Maestro Cue switched off in Encore Features every `cue` verb except `cue engine stop` is refused before it asks anyone (`cue engine stop` remains available so an existing standalone runner can be stopped). `cue pipeline` manages the desktop Pipeline Graph layout and is not served by a host; beside one it says so and points at cue.yaml.

### Scheduling Tasks

`cue schedule` is the command surface for anything time-driven: a one-shot reminder, a daily job, or a repeating check. It writes straight to the agent's `.maestro/cue.yaml`, so it works with the desktop app closed, and everything it creates shows up in the app under **Maestro Cue → Scheduled Tasks** (`maestro-cli open cue --tab scheduled`).

```bash theme={"theme":"dracula"}
# One-shot, relative
maestro-cli cue schedule --in 20m --agent "Cyber Stocks" --prompt "Check the deploy status."

# One-shot, absolute (local wall clock or ISO-8601 with an offset)
maestro-cli cue schedule --at "2026-08-20 16:00" --agent Pedsidian --notify --sticky --message "Push the rc branch"

# Every weekday at 9am
maestro-cli cue schedule --daily-at 09:00 --days mon,tue,wed,thu,fri --agent Pedsidian --prompt "Draft the standup notes."

# Twice a day, every day
maestro-cli cue schedule --daily-at 09:00,17:30 --agent Neema --prompt "Sweep the inbox."

# Every 30 minutes
maestro-cli cue schedule --every 30m --agent "ODIN Market" --prompt "Poll the market feed."

# Into an existing conversation: an agent scheduling its own follow-up from its tab
maestro-cli cue schedule --at "2026-11-11 15:00" --here --prompt "Find more candidates."

# Into a named tab of an agent
maestro-cli cue schedule --in 1d --agent Pedsidian --tab 810dda7e --prompt "Check the draft again."
```

By default a scheduled prompt runs as its own detached Cue turn, and its output lands in History and `cue activity`, not in any tab. `--tab` (or `--here`, for the tab the command runs from) delivers it into that tab instead, the same as `dispatch --tab --queue`: it waits behind a busy turn, the reply marks the tab unread, and the view never moves. If the tab was closed by the time the task fires, the prompt goes to a new tab of the agent and a toast says so. The tab keeps its own model, so `--tier`, `--model`, and `--effort` are refused with it.

Inspect and edit what is scheduled:

```bash theme={"theme":"dracula"}
# Everything, across every agent
maestro-cli cue schedule --list

# Only the repeating daily jobs, as JSON
maestro-cli cue schedule --list --kind daily --json

# Move a task's fire time (pass the timing flag that matches its kind)
maestro-cli cue schedule --reschedule standup --daily-at 09:15

# Stop it firing without deleting it, then bring it back
maestro-cli cue schedule --pause standup
maestro-cli cue schedule --resume standup

# Delete it
maestro-cli cue schedule --cancel standup
```

| Flag | Description |
| - | - |
| `--in <duration>` | One-shot, relative (`30s`, `20m`, `2h`, `1d`) |
| `--at <timestamp>` | One-shot, absolute (ISO-8601 with offset, or `"YYYY-MM-DD HH:MM"` local) |
| `--daily-at <times>` | Repeating at `HH:MM` times, comma separated |
| `--days <days>` | Restrict `--daily-at` to certain days (`mon,tue,...`) |
| `--every <duration>` | Repeating on an interval (1 minute to 7 days) |
| `--list` | List scheduled tasks across agents |
| `--kind <kind>` | Filter `--list`: `once`, `daily`, `interval`, `all` |
| `--reschedule <name>` | Change when an existing task fires |
| `--pause` / `--resume` | Flip `enabled` without deleting the task |
| `--cancel <name>` | Delete a task |
| `-a, --agent <id-or-name>` | Target agent (required when creating; scopes the other modes) |
| `-p, --prompt <text>` | Prompt to send when the task fires |
| `--tab <tab-id>` | Deliver the prompt into this AI tab of `--agent` (id or unique prefix) |
| `--here` | Deliver into the AI tab this command runs from; `--agent` defaults to it |
| `--notify` / `--sticky` | Also raise a toast; `--sticky` keeps it up until dismissed |
| `-m, --message <text>` | Toast body (defaults to the label, then the prompt) |
| `-n, --name <name>` | Custom subscription name (auto-generated when omitted) |
| `-l, --label <text>` | Human-readable label shown in the app |
| `--pipeline <name>` | Pipeline to file the task under (default: `Tasks`) |
| `--grace-minutes <n>` | One-shot only: how late a missed fire may still run (default 360) |
| `--keep-on-failure` | One-shot only: keep the task on disk after a failed run |
| `--tier <level>` | Model tier for the prompt run: `low`, `medium`, `high` |
| `--model <id>` | Exact model id for the prompt run (instead of `--tier`) |
| `--effort <level>` | Effort for the prompt run: `low`, `medium`, `high` |
| `--json` | Output as JSON (for scripting) |

Notes:

* `--in`, `--at`, `--daily-at`, and `--every` are mutually exclusive: a task fires once, on a daily clock, or on an interval.
* A task with both `--prompt` and `--notify` becomes two subscriptions sharing one fire time (`<name>-prompt` and `<name>-notify`).
* `--agent` is a hard scope on `--cancel`, `--reschedule`, `--pause`, and `--resume`. When one name exists on two agents the command refuses to guess and lists the candidates.
* One-shot tasks delete themselves from the YAML after they fire. Repeating tasks stay until you cancel them.
* `--tier`, `--model`, and `--effort` apply to the prompt run and need `--prompt`. To change them on a task that already exists, use `cue model` below.

### Setting a Subscription's Model

`cue model` shows or changes the model one Cue subscription runs on: a model tier or an exact model, plus an effort level. It works on any subscription that runs an agent, including scheduled tasks and pipeline steps, and it is the CLI twin of the **Model** and **Effort** selectors on a Pipeline Graph agent node and in the Scheduled Tasks form. Like `cue schedule`, it edits the agent's `.maestro/cue.yaml` directly, so it works with the desktop app closed.

```bash theme={"theme":"dracula"}
# Show the current choice and what it resolves to for that agent's provider
maestro-cli cue model nightly-review

# Run a step on the provider's top model at low effort
maestro-cli cue model nightly-review --tier high --effort low

# Pin an exact model (for providers with no tier mapping, such as Codex)
maestro-cli cue model triage --model gpt-5.5-codex

# Go back to the agent's own model and effort
maestro-cli cue model nightly-review --clear-model --clear-effort
```

| Flag | Description |
| - | - |
| `--tier <level>` | Model tier: `low`, `medium`, `high`, mapped per provider |
| `--model <id>` | Exact model id, passed to the agent as-is |
| `--effort <level>` | Effort: `low`, `medium`, `high`, mapped to the provider's ladder |
| `--clear-model` | Remove the tier or model and use the agent's own model |
| `--clear-effort` | Remove the effort and use the agent's own effort |
| `-a, --agent <id-or-name>` | Scope to one agent (required when the name exists on two) |
| `--json` | Output as JSON (for scripting) |
| `--data-dir <path>` | Read agents from this Maestro data directory (must already exist) |

Notes:

* On a server, pass `--data-dir` (or set `MAESTRO_USER_DATA`) so the command reads the same agents the Cue engine runs. A running engine picks the edited `cue.yaml` up on its own.
* With no setting flag the command only reads. Its output names the stored choice and the model and effort the run resolves to.
* `--tier` and `--model` are two spellings of one choice. Setting one removes the other.
* When the agent's provider cannot honor a tier or an effort, the command still saves it and prints a warning. The run then uses the agent's own value.
* Subscriptions with `action: command` or `action: notify` run no agent, so the command refuses to set a model on them.

### Triggering a Subscription

Manually trigger a Cue subscription by name, bypassing its normal event conditions.

A subscription in a pipeline fires together with its siblings: every subscription in the same pipeline whose trigger settings (event, schedule, interval, filter, and so on) are identical to its own. That is what a real tick does, since the pipeline editor writes a fan-out to several targets as one subscription per target, each repeating the trigger. To fire one subscription alone, give it a pipeline of its own or trigger settings that differ from the others'. A chain step (`agent.completed`), a subscription with no pipeline, and a trigger with `--prompt` fire only the named subscription.

```bash theme={"theme":"dracula"}
# Trigger a subscription
maestro-cli cue trigger <subscription-name>

# Trigger with a custom prompt (overrides the configured prompt)
maestro-cli cue trigger <subscription-name> --prompt "Deploy to staging only"

# JSON output (for scripting)
maestro-cli cue trigger <subscription-name> --json
```

| Flag | Description |
| - | - |
| `-p, --prompt <text>` | Override the subscription's configured prompt |
| `--source-agent-id <id>` | Identify the originating agent (populates `{{CUE_SOURCE_AGENT_ID}}`) |
| `--json` | Output as JSON (for scripting and CI/CD integration) |

The `--prompt` flag is especially useful for `cli.trigger` subscriptions, where the prompt text is available in the subscription's template as `{{CUE_CLI_PROMPT}}`.

**Examples:**

```bash theme={"theme":"dracula"}
# Trigger a review pipeline after finishing work
maestro-cli cue trigger "code-review" --prompt "Review the changes in the auth module"

# Trigger a deploy from CI
maestro-cli cue trigger "deploy" --prompt "Deploy commit abc123 to production" --json

# Re-run a failed automation
maestro-cli cue trigger "lint-on-save"
```

## Director's Notes

Director's Notes is an Encore feature (`encoreFeatures.directorNotes`) that builds a unified history view across every agent in your fleet, plus an AI-generated synopsis of recent activity.

```bash theme={"theme":"dracula"}
# Show recent unified history (last N days, default 7)
maestro-cli director-notes history -d 3

# Limit to user-initiated entries only
maestro-cli director-notes history --filter user -l 50

# Markdown output for piping into a doc
maestro-cli director-notes history -f markdown -d 1

# AI synopsis of the past day (requires the desktop app running)
maestro-cli director-notes synopsis -d 1
maestro-cli director-notes synopsis --json
```

| Subcommand | Flag | Description |
| - | - | - |
| both | `-d, --days <n>` | Lookback period in days (defaults to the app's Director's Notes setting) |
| both | `-f, --format <type>` | Output format: `json`, `markdown`, `text` (default `text`) |
| both | `--json` | Shorthand for `--format json` |
| `history` | `--filter <type>` | Filter by entry type: `auto`, `user`, `cue`, `agent` |
| `history` | `-l, --limit <n>` | Maximum entries to show (default 100) |

`synopsis` requires the desktop app to be running; `history` reads from disk and works offline. If `encoreFeatures.directorNotes` is disabled, enable it first with `maestro-cli settings set encoreFeatures.directorNotes true`.

The provider follows the app's Director's Notes setting. By default that is "use the first available provider", so the desktop picks an installed agent when the run starts and `--json` reports which one actually ran. Pin it with `maestro-cli settings set directorNotesSettings.autoSelectProvider false`.

## Publishing Session Transcripts to Gists

Publish an agent's session transcript to a GitHub gist so you can share it with collaborators or attach it to a bug report. Routes through the running Maestro desktop app (which holds the live transcript) and uses the user's authenticated `gh` CLI under the hood.

```bash theme={"theme":"dracula"}
# Create a private gist (default)
maestro-cli gist create <agent-id>

# Add a description
maestro-cli gist create <agent-id> -d "Auth refactor pairing session"

# Make it public
maestro-cli gist create <agent-id> --public -d "Repro for issue #1234"

# Publish one provider session instead of the agent's open tabs
maestro-cli gist create <agent-id> --session <session-id>
```

| Flag | Description | Default |
| - | - | - |
| `-d, --description <text>` | Gist description | - |
| `-p, --public` | Create a public gist (default private) | private |
| `-s, --session <id>` | Publish one provider session's transcript instead of the open tabs | the agent tabs |

Output is JSON with the gist URL on success:

```json theme={"theme":"dracula"}
{ "success": true, "agentId": "a1b2c3d4-...", "gistUrl": "https://gist.github.com/..." }
```

### Publishing a headless session

Without `--session`, `gist create` publishes the transcripts of the agent's **open AI tabs** in the desktop app. Headless callers (chat bridges, playbooks, Cue pipelines, CI) run their conversations with `maestro-cli send -s <session-id>` and have no tab, so for them that publishes an unrelated conversation - and a gist is readable by anyone holding the URL.

Pass the same session id you sent with:

```bash theme={"theme":"dracula"}
SESSION=$(maestro-cli send <agent-id> "..." | jq -r .sessionId)
maestro-cli send <agent-id> "follow-up" -s "$SESSION"
maestro-cli gist create <agent-id> --session "$SESSION"
```

The desktop app publishes that session and nothing else: it uses the open tab holding the session when there is one, otherwise it reads the provider's stored transcript (SSH remotes included). If the session cannot be found it fails with `GIST_CREATE_FAILED` rather than falling back to the open tabs. The response echoes `agentSessionId` so you can confirm what was published.

Requires the Maestro desktop app to be running and `gh` to be authenticated (`gh auth login`). Error codes: `AGENT_NOT_FOUND`, `INVALID_SESSION`, `MAESTRO_NOT_RUNNING`, `GIST_CREATE_FAILED`.

## Scheduling with Cron

```bash theme={"theme":"dracula"}
# Run a playbook every hour (use --json for log parsing)
0 * * * * /usr/local/bin/maestro-cli playbook <playbook-id> --json >> /var/log/maestro.jsonl 2>&1
```

## Agent Integration

Maestro agents are automatically informed about `maestro-cli` through the system prompt. Each agent receives the platform-appropriate CLI invocation command via the `{{MAESTRO_CLI_PATH}}` template variable, which resolves to the full `node "/path/to/maestro-cli.js"` command for the current OS. That form runs on whatever `node` is on the agent's `PATH`, which is enough for every command that talks to the running app or host. The Cue commands that open `cue.db` themselves (`cue engine`, `host start`, and `cue activity` when neither the app nor the host answers for Cue) need the app's runtime when using the bundled Electron-built SQLite module, or Node with a compatible `better-sqlite3` build as described under [Installing on a Machine With No Desktop](#installing-on-a-machine-with-no-desktop).

This means agents can:

* **Read settings** to understand the current Maestro configuration
* **Change settings** on behalf of the user (e.g., "switch to the nord theme", "increase font size")
* **Manage agent configs** (e.g., "set the Codex context window to 128000")
* **List resources** like agents, groups, and playbooks
* **Open files** in the Maestro file preview tab
* **Refresh the file tree** after creating or modifying files
* **Configure and launch auto-runs** with documents they create
* **Send messages** to other agents for inter-agent coordination
* **Discover Cue subscriptions** with `cue list` and **trigger automation pipelines** with `cue trigger`

When a user asks an agent to change a Maestro setting, the agent can use the CLI directly rather than instructing the user to navigate the settings modal. Changes take effect instantly.

The system prompt instructs agents to use `settings list -v` to discover available settings with descriptions, giving them full context to reason about configuration changes.

## Requirements

* At least one AI agent CLI must be installed and in PATH (Claude Code, Codex, or OpenCode)
* Maestro config files must exist (created automatically when you use the GUI)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.