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