Skip to main content

rho_coding_agent/
cli.rs

1use std::{num::NonZeroUsize, path::PathBuf, time::Duration};
2
3use clap::{Parser, Subcommand, ValueEnum};
4
5use rho_providers::{credentials::CredentialStoreBackend, reasoning::ReasoningLevel};
6
7use crate::{
8    app::automation_protocol::parse_duration,
9    permission::{PermissionMode, PermissionModeParseError},
10};
11
12#[path = "cli_daemon.rs"]
13mod daemon;
14
15pub use daemon::{
16    BridgeSetupArgs, DaemonBridgeCommand, DaemonCommand, DaemonServeArgs, DaemonTokenCommand,
17};
18
19fn parse_permission_mode(value: &str) -> Result<PermissionMode, PermissionModeParseError> {
20    value.parse()
21}
22
23fn parse_credential_store_backend(value: &str) -> Result<CredentialStoreBackend, String> {
24    CredentialStoreBackend::parse(value).map_err(|error| error.to_string())
25}
26
27fn parse_auth_profile(value: &str) -> Result<String, String> {
28    let profiles = rho_providers::auth_profiles();
29    if profiles.contains(&value) {
30        return Ok(value.to_string());
31    }
32    if rho_providers::provider::is_custom_provider_api_key_auth(value) {
33        return Ok(value.to_string());
34    }
35    Err(format!(
36        "invalid value '{value}' for '--auth'; expected one of: {}",
37        profiles.join(", ")
38    ))
39}
40
41/// Output contract used by a non-interactive `rho run` invocation.
42#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, ValueEnum)]
43pub enum OutputFormat {
44    /// Print only the authoritative final assistant answer.
45    #[default]
46    Text,
47    /// Stream independently versioned JSON Lines events.
48    Jsonl,
49}
50
51/// How `rho attach` writes a session's events.
52#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, ValueEnum)]
53pub enum AttachOutput {
54    /// Stream the conversation to stdout, and notices to stderr.
55    #[default]
56    Text,
57    /// Stream `rho run --output jsonl`'s JSON Lines events.
58    Jsonl,
59}
60
61/// Where text-mode `rho attach` reads the lines that answer and steer.
62#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, ValueEnum)]
63pub enum AttachInput {
64    /// Stdin, when it is the terminal and `rho attach` runs in its
65    /// foreground; otherwise requests are only told.
66    #[default]
67    Terminal,
68    /// Stdin, whatever it is, such as a pipe a script writes answers to.
69    Stdin,
70}
71
72/// Output contract for workflow plans and snapshots.
73#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, ValueEnum)]
74pub enum WorkflowDocumentFormat {
75    /// Print a human-readable document.
76    #[default]
77    Text,
78    /// Print one JSON document.
79    Json,
80}
81
82/// Output contract for workflow execution.
83#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
84pub enum WorkflowRunFormat {
85    /// Print human-readable state changes.
86    Text,
87    /// Stream versioned JSON Lines events.
88    Jsonl,
89}
90
91#[derive(Parser, Clone, Debug)]
92#[command(name = "rho", version)]
93pub struct Cli {
94    #[arg(long)]
95    pub provider: Option<String>,
96    #[arg(long)]
97    pub model: Option<String>,
98    #[arg(long)]
99    pub config: Option<PathBuf>,
100    #[arg(long, value_parser = parse_auth_profile)]
101    pub auth: Option<String>,
102    /// Do not send rho's system prompt, including AGENTS.md and skill context.
103    #[arg(long)]
104    pub no_system_prompt: bool,
105    /// Do not expose any tools to the model.
106    #[arg(long)]
107    pub no_tools: bool,
108    /// Do not expose the delegated-agent tools (agent/agents) to the model.
109    #[arg(long, global = true)]
110    pub no_subagents: bool,
111    /// Select the agent definition used for this session or automation run.
112    #[arg(long, global = true, value_name = "ID")]
113    pub agent: Option<String>,
114    /// Override reasoning level: off, minimal, low, medium, high, xhigh, or max.
115    #[arg(long)]
116    pub reasoning: Option<ReasoningLevel>,
117    /// Override permission mode: bypass, auto, allow_edits, plan, or supervised.
118    #[arg(long, value_name = "MODE", value_parser = parse_permission_mode)]
119    pub(crate) permission_mode: Option<PermissionMode>,
120    /// Add a directory to the workspace scope. Repeat for more directories.
121    ///
122    /// Checked permission modes treat reads there like workspace reads, and
123    /// its AGENTS.md files load with the project's. Interactive sessions save
124    /// added directories and restore them on resume.
125    #[arg(long = "add-dir", value_name = "PATH", global = true)]
126    pub add_dirs: Vec<PathBuf>,
127    /// Persist --provider/--model/--auth/--reasoning overrides to the config file.
128    ///
129    /// Without this flag, those overrides apply only to the current invocation.
130    #[arg(long)]
131    pub save: bool,
132    /// Keep this interactive session in memory without saving its transcript or prompt history.
133    #[arg(long, conflicts_with_all = ["resume", "continue_latest"])]
134    pub no_save: bool,
135    /// Resume an existing session by UUID or UUID prefix. Omit the ID to choose from a picker.
136    #[arg(short = 'R', long, value_name = "ID", num_args = 0..=1)]
137    pub resume: Option<Option<String>>,
138    /// Resume the most recent session in the current workspace without a picker.
139    ///
140    /// Starts a new session when the workspace has no saved sessions yet.
141    #[arg(short = 'c', long = "continue", conflicts_with = "resume")]
142    pub continue_latest: bool,
143    /// Open the interactive TUI with this prompt already submitted.
144    ///
145    /// This starts a normal session. Use `rho run` when you want one answer and
146    /// then exit.
147    #[arg(long, value_name = "PROMPT")]
148    pub prompt: Option<String>,
149    /// Draw the interactive TUI on the terminal's main screen so the
150    /// transcript stays in native scrollback, for this launch.
151    ///
152    /// Turns off mouse capture, in-app scrolling, transcript search, and
153    /// inline images. Set `minimal_mode = true` in `clients/tui.toml` to make
154    /// it the default.
155    #[arg(long)]
156    pub minimal: bool,
157    #[command(subcommand)]
158    pub command: Option<Command>,
159}
160
161#[derive(Subcommand, Clone, Debug)]
162pub enum ModelPromptCommand {
163    /// Open custom system instructions for a model in $VISUAL or $EDITOR.
164    #[command(after_help = "Examples:
165  rho model-prompt edit
166      Choose a model from a searchable picker, then edit its instructions.
167  rho model-prompt edit --provider openai-codex
168      Choose from locally known models for one provider.
169  rho model-prompt edit --provider openai-codex --model gpt-6-astra
170      Edit instructions for an exact provider/model pair.
171  rho model-prompt edit --model @local
172      Resolve a model alias from your config.
173  VISUAL='code --wait' rho model-prompt edit
174      Use an editor that waits until you close the file.
175  rho --config /path/to/config.toml model-prompt edit
176      Use a different configuration file.
177
178Editing:
179  Without --model, opens a picker. Type to filter, Enter to edit, Esc to cancel.
180  The picker uses local catalogs without requiring login or fetching models.
181  Non-interactive callers must pass --model explicitly.
182  Uses $VISUAL, falling back to $EDITOR. Set one before running this command.
183  Opens a private draft of the matching file in ~/.rho/model-prompts/.
184  If none exists, starts a draft with provider, model, and mode frontmatter.
185  Keep provider/model unchanged and write Markdown instructions below the
186  closing --- line. Save and exit the editor to validate and install the file.
187  Leaving the draft unchanged cancels. Invalid edits preserve a recovery draft.
188
189Modes:
190  mode: append   Add to Rho's default behavioral instructions. This is the default.
191  mode: replace  Replace only that behavioral block, not tool instructions,
192                 AGENTS.md, skills, or permission rules.
193
194Scope:
195  Instructions are global for the exact provider/model pair, not project-local.
196  Editing works offline and does not start a session or change your default model.
197  Sessions load changes at startup, model switch, /new, or resume, not each turn.")]
198    Edit {
199        /// Filter the picker by provider; with --model, override the configured provider.
200        #[arg(long)]
201        provider: Option<String>,
202        /// Exact model ID or @alias. Omit to choose from an interactive picker.
203        #[arg(long)]
204        model: Option<String>,
205    },
206}
207
208#[derive(Subcommand, Clone, Debug)]
209pub enum Command {
210    /// Run one non-interactive automation prompt and print the final answer.
211    Run {
212        /// Read additional prompt text from stdin.
213        ///
214        /// Required when stdin is a pipe or redirected file. Without this flag,
215        /// redirected stdin is rejected so prompt text is not silently dropped.
216        #[arg(long)]
217        stdin: bool,
218        /// Write a structured status/result file (JSON) that is updated during
219        /// the run and finalized on exit. With `--output text` (the default),
220        /// progress and streamed assistant text go to stdout and the run ends
221        /// with a completion marker; the result file is the durable final
222        /// answer. With `--output jsonl`, stdout stays the JSONL event stream.
223        #[arg(long, value_name = "PATH")]
224        output_file: Option<PathBuf>,
225        /// Select plain final-answer output or a JSON Lines event stream.
226        #[arg(long, value_enum, default_value_t)]
227        output: OutputFormat,
228        /// Override the model-step budget for this run.
229        #[arg(long, value_name = "N")]
230        max_steps: Option<NonZeroUsize>,
231        /// Cancel the run after this wall-clock duration.
232        #[arg(long, value_name = "DURATION", value_parser = parse_duration)]
233        timeout: Option<Duration>,
234        /// Do not save the run's session or its Rho and Claude subagents'
235        /// sessions, so none is left to export or resume.
236        ///
237        /// Antigravity subagents keep their own CLI sessions, and
238        /// workflow nodes the run starts save theirs as part of the workflow
239        /// run's record.
240        #[arg(long)]
241        no_save: bool,
242        /// Start the run in the rho daemon, starting one if none runs, and
243        /// exit once its prompt is saved, printing the session's id. The
244        /// turn runs on; `rho attach <ID>` follows it and answers its
245        /// approvals and questions. `--timeout` is enforced by the daemon.
246        #[arg(long, conflicts_with_all = ["output_file", "output", "max_steps", "no_save"])]
247        detach: bool,
248        /// Run in a new git worktree of the current directory's repository,
249        /// on a new branch from `origin`'s default branch, fetched first, or
250        /// from the repository's HEAD when there is no `origin`, the fetch
251        /// fails or takes over 30 seconds, or `git.worktree_from_remote` is
252        /// off, so runs in one repository cannot overwrite each other's
253        /// edits. The worktree is made under the rho
254        /// home, and the run works at the current directory's place in it.
255        /// The daemon removes it once it is clean and merged, nothing has
256        /// worked in it for a day, and no process works in it; the branch
257        /// stays (see `rho worktrees`).
258        #[arg(long)]
259        worktree: bool,
260        /// Prompt text to send to the agent.
261        #[arg(value_name = "PROMPT", num_args = 0..)]
262        prompt: Vec<String>,
263    },
264    /// Follow a daemon session's turn until it ends, and exit as it ended.
265    ///
266    /// Without a turn under way, report the session's last turn. In text
267    /// mode, lines typed at the terminal answer the turn's requests, steer
268    /// it, or cancel it with `/cancel`. Ctrl+C detaches; the turn runs on in
269    /// the daemon.
270    Attach {
271        /// The session's id, or its job's.
272        #[arg(value_name = "ID")]
273        id: String,
274        /// Write the session's events as text or as the JSON Lines stream
275        /// `rho run --output jsonl` writes.
276        #[arg(long, value_enum, default_value_t)]
277        output: AttachOutput,
278        /// In text mode, where to read the lines that answer the turn's
279        /// requests and steer it.
280        #[arg(long, value_enum, default_value_t)]
281        input: AttachInput,
282    },
283    /// Log in to a provider with an API key, browser, or device-code flow.
284    Login {
285        /// Provider to authenticate, for example openai-codex or github-copilot,
286        /// or `antigravity` to run agy's own sign-in for Antigravity subagents.
287        #[arg(value_name = "PROVIDER")]
288        provider: String,
289        /// Use device-code login instead of opening a local browser callback.
290        #[arg(long)]
291        device_auth: bool,
292    },
293    /// Configure or probe provider credential storage.
294    CredentialStore {
295        #[command(subcommand)]
296        command: CredentialStoreCommand,
297    },
298    /// Customize system instructions for an exact provider/model pair.
299    #[command(after_help = "Quick start:
300  rho model-prompt edit
301  rho model-prompt edit --provider openai-codex --model gpt-6-astra
302  rho model-prompt edit --model @local
303
304Uses $VISUAL, falling back to $EDITOR, to edit Markdown instructions stored in
305~/.rho/model-prompts/. With no --model, opens a searchable model picker.
306Use --provider to narrow the list, or --model to skip the picker.
307Non-interactive callers must pass --model explicitly.
308New files append to Rho's default behavioral instructions; mode: replace replaces
309only that behavioral block. Instructions apply globally, not just to this project.
310This edits instructions offline; it does not send a prompt or start a session.
311
312Run rho model-prompt edit --help for editor setup, saving, and reload behavior.")]
313    ModelPrompt {
314        #[command(subcommand)]
315        command: ModelPromptCommand,
316    },
317    /// Update rho using the detected installation method.
318    Update {
319        /// Report whether an update exists and how rho would install it,
320        /// without installing anything. Exits with status 1 when the
321        /// latest release cannot be looked up.
322        #[arg(long)]
323        check: bool,
324        /// Print the `--check` report as one JSON object.
325        #[arg(long, requires = "check")]
326        json: bool,
327    },
328    /// Uninstall Rho after confirmation, preserving user data by default.
329    Uninstall {
330        /// Also permanently delete local Rho user data under ~/.rho.
331        #[arg(long)]
332        purge: bool,
333        /// Preview removal paths without changing anything or prompting.
334        #[arg(long)]
335        dry_run: bool,
336    },
337    /// List, rename, or delete saved sessions.
338    Sessions {
339        #[command(subcommand)]
340        command: SessionsCommand,
341    },
342    /// Inspect configured Model Context Protocol servers, or serve rho's
343    /// sessions as one.
344    Mcp {
345        #[command(subcommand)]
346        command: McpCommand,
347    },
348    /// List, inspect, install, and activate local Agent Plugin packages.
349    Plugins {
350        #[command(subcommand)]
351        command: PluginsCommand,
352    },
353    /// Validate, plan, run, and inspect deterministic workflows.
354    Workflow {
355        #[command(subcommand)]
356        command: WorkflowCommand,
357    },
358    /// Run local setup diagnostics and print a report.
359    ///
360    /// Same checks as the interactive `/doctor` overlay. Exits with status 1
361    /// when any check fails; warnings exit 0.
362    Doctor {
363        /// Print the report as JSON.
364        #[arg(long)]
365        json: bool,
366    },
367    /// Serve the Agent Client Protocol over stdio for editor/host integration.
368    Acp(AcpArgs),
369    /// Run or control the rho daemon for this rho home.
370    ///
371    /// Without a subcommand, runs the daemon in the foreground.
372    Daemon {
373        #[command(subcommand)]
374        command: Option<DaemonCommand>,
375    },
376    /// Install and check the browser that browser tools drive.
377    #[cfg(feature = "browser")]
378    Browser {
379        #[command(subcommand)]
380        command: BrowserCommand,
381    },
382    /// Inspect and clean up the git worktrees under the rho home.
383    Worktrees {
384        #[command(subcommand)]
385        command: WorktreesCommand,
386    },
387    /// Internal supervised workflow planner worker. Not a public command.
388    #[command(name = "__workflow_planner_worker", hide = true)]
389    WorkflowPlannerWorker,
390    /// Internal relay between an agent's MCP client and the tools a daemon
391    /// session serves it for one turn. Not a public command.
392    #[command(name = "__session-tools", hide = true)]
393    SessionTools(SessionToolsArgs),
394    /// Debug-only scripted ACP agent on stdio for offline external-runtime
395    /// E2E tests. Refuses to run outside `RHO_TUI_TEST_MODE=matrix`.
396    #[cfg(debug_assertions)]
397    #[command(name = "__acp-fixture-agent", hide = true)]
398    AcpFixtureAgent(AcpFixtureAgentArgs),
399}
400
401/// Options for `rho acp`.
402#[derive(clap::Args, Clone, Debug, Default)]
403pub struct AcpArgs {
404    /// Mark the host as T3 Code: subagents run as T3 child threads through
405    /// its `t3-code` MCP server, and a background process or workflow that
406    /// finishes after a prompt ended wakes the idle thread with its result.
407    #[arg(long)]
408    pub t3code: bool,
409    /// Run terminal authentication for an auth profile instead of serving ACP.
410    /// Hosts append this option to the configured agent invocation.
411    #[arg(long, value_name = "AUTH")]
412    pub login: Option<String>,
413}
414
415/// Inputs for the internal session tools relay
416/// (`acp_runtime::agent_tools::bridge`).
417#[derive(clap::Args, Clone, Debug)]
418pub struct SessionToolsArgs {
419    /// Where the turn's tools listen.
420    #[arg(value_name = "ENDPOINT")]
421    pub endpoint: std::ffi::OsString,
422}
423
424/// Inputs for the debug-only scripted ACP agent.
425#[cfg(debug_assertions)]
426#[derive(clap::Args, Clone, Debug)]
427pub struct AcpFixtureAgentArgs {
428    /// Script JSON: handshake outcomes, session modes, and per-turn steps.
429    #[arg(long, value_name = "PATH")]
430    pub script: PathBuf,
431    /// Append every request Rho sends and every reply it gives here (JSONL).
432    #[arg(long, value_name = "PATH")]
433    pub journal: PathBuf,
434}
435
436/// Argv entry for the internal supervised planner worker process.
437pub const WORKFLOW_PLANNER_WORKER_COMMAND: &str = "__workflow_planner_worker";
438
439#[derive(Subcommand, Clone, Debug)]
440pub enum WorkflowCommand {
441    /// List saved workflow plans and runs for the current workspace.
442    List {
443        /// Include only saved plans.
444        #[arg(long, conflicts_with = "runs")]
445        plans: bool,
446        /// Include only runs.
447        #[arg(long, conflicts_with = "plans")]
448        runs: bool,
449        /// Limit how many rows to print per section.
450        #[arg(long, value_name = "N")]
451        limit: Option<NonZeroUsize>,
452        /// Print one JSON document instead of text rows.
453        #[arg(long)]
454        json: bool,
455    },
456    /// Validate a Starlark workflow without creating durable state.
457    Validate {
458        /// Workflow entry file under the current workspace.
459        #[arg(value_name = "FILE")]
460        file: PathBuf,
461        /// Supply one non-secret workflow input as KEY=JSON. May be repeated.
462        #[arg(long, value_name = "KEY=JSON")]
463        input: Vec<String>,
464    },
465    /// Validate, freeze, and persist an immutable workflow plan.
466    Plan {
467        /// Workflow entry file under the current workspace.
468        #[arg(value_name = "FILE")]
469        file: PathBuf,
470        /// Supply one non-secret workflow input as KEY=JSON. May be repeated.
471        #[arg(long, value_name = "KEY=JSON")]
472        input: Vec<String>,
473        /// Select human-readable or machine-readable plan output.
474        #[arg(long, value_enum, default_value_t)]
475        output: WorkflowDocumentFormat,
476    },
477    /// Create and run a workflow from an immutable plan.
478    Run {
479        /// Full plan UUID or unique UUID prefix.
480        #[arg(value_name = "PLAN_ID")]
481        plan_id: String,
482        /// Confirm the exact plan digest without an interactive prompt.
483        #[arg(long)]
484        yes: bool,
485        /// Select text or JSON Lines instead of the workflow TUI.
486        #[arg(long, value_enum)]
487        output: Option<WorkflowRunFormat>,
488    },
489    /// Read one durable workflow run snapshot.
490    Status {
491        /// Full run UUID or unique UUID prefix.
492        #[arg(value_name = "RUN_ID")]
493        run_id: String,
494        /// Select human-readable or machine-readable snapshot output.
495        #[arg(long, value_enum, default_value_t)]
496        output: WorkflowDocumentFormat,
497    },
498    /// Request cancellation of a durable workflow run.
499    Cancel {
500        /// Full run UUID or unique UUID prefix.
501        #[arg(value_name = "RUN_ID")]
502        run_id: String,
503    },
504    /// Resume a durable workflow run from its frozen graph.
505    Resume {
506        /// Full run UUID or unique UUID prefix.
507        #[arg(value_name = "RUN_ID")]
508        run_id: String,
509        /// Confirm the frozen graph without an interactive prompt.
510        #[arg(long)]
511        yes: bool,
512        /// Confirm that no prior process remains and recover uncertain attempts.
513        /// A Rho agent attempt continues its saved session; others restart.
514        #[arg(long)]
515        recover_uncertain: bool,
516        /// Report how each uncertain attempt would recover without changing the run.
517        #[arg(long)]
518        dry_run: bool,
519        /// Select text or JSON Lines instead of the workflow TUI.
520        #[arg(long, value_enum)]
521        output: Option<WorkflowRunFormat>,
522    },
523}
524
525#[cfg(feature = "browser")]
526#[derive(Subcommand, Clone, Debug)]
527pub enum BrowserCommand {
528    /// Download the pinned chrome-headless-shell into the rho home, verify
529    /// it, and start it once to check that it runs here.
530    ///
531    /// The daemon downloads it on first use too; installing ahead of time
532    /// saves that wait and shows any problem now. With `executable` set under
533    /// `[browser]`, nothing is downloaded and that browser is checked
534    /// instead. When the browser cannot start, the error names the cause rho
535    /// found and how to fix it.
536    Install,
537}
538
539#[derive(Subcommand, Clone, Debug)]
540pub enum WorktreesCommand {
541    /// Remove each worktree that is clean and merged, keeping its branch,
542    /// and say why each other one stays.
543    ///
544    /// A worktree is removed when nothing uses it, it has no uncommitted or
545    /// untracked changes, and its branch is merged into the current HEAD of
546    /// the checkout it was added from or the remote's default branch, by a
547    /// merge, rebase, or squash. Nothing uses a session's worktree when the
548    /// session is neither loaded nor running; nothing uses one no session
549    /// owns, as `rho run --worktree` and `git worktree add` make, when no
550    /// process works in it. The daemon does the same soon after it starts
551    /// and once a day, for worktrees unused for a day. Starts the daemon
552    /// when none is running.
553    Prune {
554        /// List what would be removed, and why, without removing anything.
555        #[arg(long)]
556        dry_run: bool,
557    },
558    /// List each worktree, largest first, with the space it takes and
559    /// whether `rho worktrees prune` would remove it, then the totals.
560    ///
561    /// Changes nothing, and needs the daemon running.
562    Status,
563}
564
565#[derive(Subcommand, Clone, Debug)]
566pub enum SessionsCommand {
567    /// List saved sessions for the current workspace (or all projects).
568    List {
569        /// Include sessions from every workspace, not only the current directory.
570        #[arg(long)]
571        all_projects: bool,
572        /// Case-insensitive filter over id, title, and first user message.
573        #[arg(long, short = 'q', value_name = "TEXT")]
574        search: Option<String>,
575        /// Limit how many sessions to print.
576        #[arg(long, value_name = "N")]
577        limit: Option<NonZeroUsize>,
578        /// Print one JSON document instead of text rows.
579        #[arg(long)]
580        json: bool,
581    },
582    /// Export a saved session transcript by UUID or UUID prefix.
583    Export {
584        /// Session UUID or unique prefix.
585        #[arg(value_name = "ID")]
586        id_prefix: String,
587        /// Output path. Omit to write under ~/.rho/exports/.
588        #[arg(long, short = 'o', value_name = "PATH")]
589        output: Option<PathBuf>,
590        /// Explicit format. When omitted, the path extension selects html, md, or json.
591        #[arg(long, value_enum)]
592        format: Option<crate::export::ExportFormat>,
593        /// Overwrite an existing file.
594        #[arg(long)]
595        force: bool,
596    },
597    /// Delete one or more sessions by UUID or UUID prefix.
598    Rm {
599        /// Session UUID or unique prefix. May be repeated.
600        #[arg(value_name = "ID", required = true, num_args = 1..)]
601        ids: Vec<String>,
602        /// Delete even when a parent-linked run is still non-terminal.
603        ///
604        /// Use only for stale Starting/Running artifacts left after a crash.
605        #[arg(long)]
606        force: bool,
607        /// Skip the confirmation prompt for cross-project deletes.
608        #[arg(short = 'y', long)]
609        yes: bool,
610    },
611    /// Delete sessions whose workspace directories no longer exist.
612    Cleanup {
613        /// Delete even when a parent-linked run is still non-terminal.
614        ///
615        /// Use only for stale Starting/Running artifacts left after a crash.
616        #[arg(long)]
617        force: bool,
618        /// Skip the confirmation prompt.
619        #[arg(short = 'y', long)]
620        yes: bool,
621    },
622    /// Rename a session by UUID or UUID prefix.
623    Rename {
624        /// Session UUID or unique prefix.
625        #[arg(value_name = "ID")]
626        id_prefix: String,
627        /// New session title. Multiple words are joined with spaces.
628        #[arg(value_name = "TITLE", required = true, num_args = 1.., trailing_var_arg = true)]
629        title: Vec<String>,
630    },
631}
632
633#[derive(Subcommand, Clone, Debug)]
634pub enum McpCommand {
635    /// List configured MCP servers from the selected config and plugins.
636    List {
637        /// Print one JSON document instead of text rows.
638        #[arg(long)]
639        json: bool,
640        /// Start enabled servers and report live connection status.
641        #[arg(long)]
642        connect: bool,
643    },
644    /// Show one MCP server by identity.
645    Show {
646        /// Server table key from `[mcp.servers.<id>]`.
647        #[arg(value_name = "ID")]
648        id: String,
649        /// Print one JSON document instead of text.
650        #[arg(long)]
651        json: bool,
652        /// Start enabled servers and report live connection status.
653        #[arg(long)]
654        connect: bool,
655    },
656    /// Serve the rho daemon's sessions as an MCP server: list, read, start,
657    /// prompt, steer, cancel, and wait for them, and answer their questions.
658    ///
659    /// Over stdio by default, for a host that starts it as a command. With
660    /// `--http`, over streamable HTTP on a loopback or private network
661    /// address, for hosts that reach MCP servers by URL; every request then
662    /// needs a bearer token from `rho mcp token rotate`, and the server can
663    /// POST watched sessions' news to webhooks from `rho mcp webhook add`.
664    /// With remotes from `rho mcp remote add`, it drives their sessions
665    /// too, and every tool takes `server`. No tool answers a session's
666    /// approvals or plan approvals: those wait for a person.
667    Serve(McpServeArgs),
668    /// Manage the bearer tokens `rho mcp serve --http` accepts.
669    Token {
670        #[command(subcommand)]
671        command: McpTokenCommand,
672    },
673    /// Manage the webhooks `rho mcp serve --http` POSTs watched sessions'
674    /// news to.
675    Webhook {
676        #[command(subcommand)]
677        command: McpWebhookCommand,
678    },
679    /// Manage the other machines' `rho mcp serve --http` that this
680    /// machine's `rho mcp serve` drives as a hub.
681    Remote {
682        #[command(subcommand)]
683        command: McpRemoteCommand,
684    },
685    /// Store or delete the secrets MCP servers read through
686    /// `env_from_secret` and `headers_from_secret`, kept in the rho
687    /// daemon's credential store.
688    Secret {
689        #[command(subcommand)]
690        command: McpSecretCommand,
691    },
692}
693
694#[derive(Subcommand, Clone, Debug)]
695pub enum McpSecretCommand {
696    /// Store secret NAME of server ID, replacing any. The value is read
697    /// hidden from the terminal, or from standard input when it is not one.
698    /// Sessions' servers read it when they next connect.
699    Set {
700        /// Server table key from `[mcp.servers.<id>]`.
701        #[arg(value_name = "ID")]
702        id: String,
703        /// The secret's name, as `env_from_secret` or
704        /// `headers_from_secret` lists it.
705        #[arg(value_name = "NAME")]
706        name: String,
707    },
708    /// Delete secret NAME of server ID.
709    #[command(visible_alias = "rm")]
710    Delete {
711        #[arg(value_name = "ID")]
712        id: String,
713        #[arg(value_name = "NAME")]
714        name: String,
715    },
716}
717
718#[derive(clap::Args, Clone, Debug)]
719pub struct McpServeArgs {
720    /// Serve streamable HTTP on this address instead of stdio: a loopback
721    /// one, such as 127.0.0.1:8765, or this machine's address on a private
722    /// network, such as a NetBird or Tailscale peer's 100.x.y.z:8765, where
723    /// requests travel as plain HTTP.
724    #[arg(long, value_name = "ADDR")]
725    pub http: Option<std::net::SocketAddr>,
726    /// With `--http`, also accept this `Host` header, such as the tunnel's
727    /// public hostname. May be repeated.
728    #[arg(long, value_name = "HOST", requires = "http")]
729    pub allow_host: Vec<String>,
730    /// With `--http`, accept requests from this browser origin, such as
731    /// https://app.example.com. Any other `Origin` is refused. May be
732    /// repeated.
733    #[arg(long, value_name = "ORIGIN", requires = "http")]
734    pub allow_origin: Vec<String>,
735    /// The deepest a session this server starts or prompts may run: 1 for
736    /// a session started by a person's or an outside agent's call, one more
737    /// for each session in between. Defaults to 3.
738    #[arg(long, value_name = "N")]
739    pub max_depth: Option<u32>,
740    /// How many sessions each caller (each token, over HTTP) may have
741    /// running at once. Defaults to 10.
742    #[arg(long, value_name = "N")]
743    pub max_sessions: Option<u32>,
744    /// Over stdio, what the host may do: `read` lists, reads, and waits
745    /// for sessions and refuses every other tool; `write`, the default,
746    /// also starts, prompts, steers, and cancels them. With `--http` each
747    /// token carries its own scope instead.
748    #[arg(long, value_enum, conflicts_with = "http")]
749    pub scope: Option<McpTokenScope>,
750    /// The name this machine goes by: what webhook news says it is from,
751    /// and what `server` names it when the server has remotes. Defaults to
752    /// the host name.
753    #[arg(long, value_name = "NAME")]
754    pub name: Option<String>,
755    /// With `--http`, how many sessions each token may watch at once,
756    /// stalled watches included. Defaults to 5 times --max-sessions (50
757    /// by default). `rho mcp webhook list` shows each token's count.
758    #[arg(long, value_name = "N", requires = "http")]
759    pub max_watches: Option<u32>,
760    /// Internal: the listening socket a server that upgraded in place
761    /// handed this one.
762    #[arg(long, value_name = "FD", requires = "http", hide = true)]
763    pub listener_fd: Option<i32>,
764    /// Internal: on Windows, the server that upgraded in place to this one,
765    /// whose exit this one waits for before it listens.
766    #[arg(long, value_name = "PID", requires = "http", hide = true)]
767    pub predecessor: Option<u32>,
768}
769
770#[derive(Subcommand, Clone, Debug)]
771pub enum McpTokenCommand {
772    /// Create token NAME, or give it a new secret, and print the secret
773    /// once. The old secret stops working at once.
774    Rotate {
775        /// The token's name, which refusals and `list` show.
776        #[arg(value_name = "NAME")]
777        name: String,
778        /// What the token may do: `read` lists, reads, and waits for
779        /// sessions; `write` also starts, prompts, steers, and cancels
780        /// them. A new token defaults to `read`; rotating keeps the
781        /// token's scope unless given.
782        #[arg(long, value_enum)]
783        scope: Option<McpTokenScope>,
784        /// A directory whose sessions, and those of everything under it,
785        /// the token may reach. May be repeated; a new token needs at least
786        /// one, and rotating keeps the token's list unless given.
787        #[arg(long, value_name = "DIR")]
788        workspace: Vec<PathBuf>,
789    },
790    /// List the tokens: their names, scopes, and workspaces.
791    List {
792        /// Print one JSON document instead of text rows.
793        #[arg(long)]
794        json: bool,
795    },
796    /// Delete token NAME; requests with it are refused at once.
797    Revoke {
798        #[arg(value_name = "NAME")]
799        name: String,
800    },
801}
802
803#[derive(Subcommand, Clone, Debug)]
804pub enum McpWebhookCommand {
805    /// Create webhook NAME, or replace it, reading its bearer secret from
806    /// stdin: `printf %s "$KEY" | rho mcp webhook add NAME --url URL
807    /// --token TOKEN`.
808    Add {
809        /// The webhook's name, which `watch` and `notify` take.
810        #[arg(value_name = "NAME")]
811        name: String,
812        /// Where to POST: an https URL, or http to a loopback host.
813        #[arg(long, value_name = "URL")]
814        url: String,
815        /// A token whose watches may use the webhook. May be repeated; at
816        /// least one.
817        #[arg(long, value_name = "TOKEN", required = true)]
818        token: Vec<String>,
819    },
820    /// List the webhooks: their names, URLs, tokens, last delivery, and
821    /// stalled watches. Never their secrets.
822    List {
823        /// Print one JSON document instead of text rows.
824        #[arg(long)]
825        json: bool,
826    },
827    /// Delete webhook NAME; watches that use it are dropped before their
828    /// next POST.
829    Remove {
830        #[arg(value_name = "NAME")]
831        name: String,
832    },
833}
834
835#[derive(Subcommand, Clone, Debug)]
836pub enum McpRemoteCommand {
837    /// Add remote NAME, or replace it, reading the secret of the token it
838    /// issued this machine from stdin, and check that it answers:
839    /// `ssh NAME '~/.local/bin/rho mcp token rotate hub --scope write
840    /// --workspace DIR' | rho mcp remote add NAME --url URL`, with the full
841    /// path of `rho` on NAME, which a non-interactive SSH shell may not
842    /// have on its PATH.
843    Add {
844        /// The remote's name, which `server` takes and webhook news names.
845        #[arg(value_name = "NAME")]
846        name: String,
847        /// The remote's MCP endpoint, such as
848        /// http://100.92.10.4:8765/mcp: https, or http to a loopback or
849        /// private network address.
850        #[arg(long, value_name = "URL")]
851        url: String,
852    },
853    /// List the remotes: their names and URLs. Never their secrets.
854    List {
855        /// Print one JSON document instead of text rows.
856        #[arg(long)]
857        json: bool,
858    },
859    /// Delete remote NAME; watches of its sessions are dropped before
860    /// their next POST.
861    Remove {
862        #[arg(value_name = "NAME")]
863        name: String,
864    },
865}
866
867/// What a caller of the MCP server may do: an HTTP token, or the host of a
868/// stdio server.
869#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
870pub enum McpTokenScope {
871    Read,
872    Write,
873}
874
875/// Target scope for plugin install and link.
876#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, ValueEnum)]
877pub enum PluginsScope {
878    /// User root: `~/.agents/plugins`.
879    #[default]
880    User,
881    /// Project root: `<repository>/.agents/plugins`.
882    Project,
883}
884
885#[derive(Subcommand, Clone, Debug)]
886pub enum PluginsCommand {
887    /// List discovered Agent Plugin packages.
888    List {
889        /// Print one JSON document instead of text rows.
890        #[arg(long)]
891        json: bool,
892    },
893    /// Inspect one plugin by package name without executing package code.
894    Inspect {
895        /// Plugin package name from `plugin.json`.
896        #[arg(value_name = "NAME")]
897        name: String,
898        /// Print one JSON document instead of text.
899        #[arg(long)]
900        json: bool,
901    },
902    /// Copy a plugin package from a local path or git repository into a managed plugins root.
903    Install {
904        /// Local directory with `plugin.json`, a GitHub link
905        /// (`https://github.com/<owner>/<repo>[/tree/<ref>/<path>]`), or a git URL.
906        #[arg(value_name = "SOURCE")]
907        source: std::ffi::OsString,
908        /// Install under the user or project plugins root.
909        #[arg(long, value_enum, default_value_t = PluginsScope::User)]
910        scope: PluginsScope,
911        /// Replace an existing package at the destination.
912        #[arg(long)]
913        force: bool,
914    },
915    /// Symlink a local plugin package into a managed plugins root.
916    Link {
917        /// Path to a directory that contains `plugin.json`.
918        #[arg(value_name = "PATH")]
919        path: PathBuf,
920        /// Link under the user or project plugins root.
921        #[arg(long, value_enum, default_value_t = PluginsScope::User)]
922        scope: PluginsScope,
923        /// Replace an existing package at the destination.
924        #[arg(long)]
925        force: bool,
926    },
927    /// Refetch git-installed plugins and replace them when their ref moved.
928    Update {
929        /// Plugin package name; omit to update every git-installed plugin.
930        #[arg(value_name = "NAME")]
931        name: Option<String>,
932    },
933    /// Enable a discovered plugin for new sessions.
934    Enable {
935        /// Plugin package name from `plugin.json`.
936        #[arg(value_name = "NAME")]
937        name: String,
938    },
939    /// Disable a discovered plugin without deleting package files.
940    Disable {
941        /// Plugin package name from `plugin.json`.
942        #[arg(value_name = "NAME")]
943        name: String,
944    },
945    /// Remove an installed or linked package from a managed plugins root.
946    Remove {
947        /// Plugin package name from `plugin.json`.
948        #[arg(value_name = "NAME")]
949        name: String,
950        /// Skip the confirmation prompt.
951        #[arg(short = 'y', long)]
952        yes: bool,
953    },
954}
955
956#[derive(Subcommand, Clone, Debug)]
957pub enum CredentialStoreCommand {
958    /// Test a credential backend by writing and deleting a temporary secret.
959    Probe {
960        /// Backend to test: os or file (`auto` is accepted as an alias for os).
961        #[arg(
962            value_name = "BACKEND",
963            default_value = "os",
964            value_parser = parse_credential_store_backend
965        )]
966        backend: CredentialStoreBackend,
967    },
968    /// Show the configured credential backend (unset, os, or file).
969    Status,
970    /// Save the credential backend used by future rho processes.
971    Set {
972        /// Backend to use: os or file (`auto` is accepted as an alias for os).
973        #[arg(value_name = "BACKEND", value_parser = parse_credential_store_backend)]
974        backend: CredentialStoreBackend,
975    },
976}
977
978#[cfg(test)]
979#[path = "cli_tests.rs"]
980mod tests;