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        /// Cursor and 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    /// Inspect and clean up the git worktrees under the rho home.
375    Worktrees {
376        #[command(subcommand)]
377        command: WorktreesCommand,
378    },
379    /// Internal supervised workflow planner worker. Not a public command.
380    #[command(name = "__workflow_planner_worker", hide = true)]
381    WorkflowPlannerWorker,
382    /// Debug-only scripted ACP agent on stdio for offline external-runtime
383    /// E2E tests. Refuses to run outside `RHO_TUI_TEST_MODE=matrix`.
384    #[cfg(debug_assertions)]
385    #[command(name = "__acp-fixture-agent", hide = true)]
386    AcpFixtureAgent(AcpFixtureAgentArgs),
387}
388
389/// Options for `rho acp`.
390#[derive(clap::Args, Clone, Debug, Default)]
391pub struct AcpArgs {
392    /// Mark the host as T3 Code: subagents run as T3 child threads through
393    /// its `t3-code` MCP server, and a background process or workflow that
394    /// finishes after a prompt ended wakes the idle thread with its result.
395    #[arg(long)]
396    pub t3code: bool,
397    /// Run terminal authentication for an auth profile instead of serving ACP.
398    /// Hosts append this option to the configured agent invocation.
399    #[arg(long, value_name = "AUTH")]
400    pub login: Option<String>,
401}
402
403/// Inputs for the debug-only scripted ACP agent.
404#[cfg(debug_assertions)]
405#[derive(clap::Args, Clone, Debug)]
406pub struct AcpFixtureAgentArgs {
407    /// Script JSON: handshake outcomes, session modes, and per-turn steps.
408    #[arg(long, value_name = "PATH")]
409    pub script: PathBuf,
410    /// Append every request Rho sends and every reply it gives here (JSONL).
411    #[arg(long, value_name = "PATH")]
412    pub journal: PathBuf,
413}
414
415/// Argv entry for the internal supervised planner worker process.
416pub const WORKFLOW_PLANNER_WORKER_COMMAND: &str = "__workflow_planner_worker";
417
418#[derive(Subcommand, Clone, Debug)]
419pub enum WorkflowCommand {
420    /// List saved workflow plans and runs for the current workspace.
421    List {
422        /// Include only saved plans.
423        #[arg(long, conflicts_with = "runs")]
424        plans: bool,
425        /// Include only runs.
426        #[arg(long, conflicts_with = "plans")]
427        runs: bool,
428        /// Limit how many rows to print per section.
429        #[arg(long, value_name = "N")]
430        limit: Option<NonZeroUsize>,
431        /// Print one JSON document instead of text rows.
432        #[arg(long)]
433        json: bool,
434    },
435    /// Validate a Starlark workflow without creating durable state.
436    Validate {
437        /// Workflow entry file under the current workspace.
438        #[arg(value_name = "FILE")]
439        file: PathBuf,
440        /// Supply one non-secret workflow input as KEY=JSON. May be repeated.
441        #[arg(long, value_name = "KEY=JSON")]
442        input: Vec<String>,
443    },
444    /// Validate, freeze, and persist an immutable workflow plan.
445    Plan {
446        /// Workflow entry file under the current workspace.
447        #[arg(value_name = "FILE")]
448        file: PathBuf,
449        /// Supply one non-secret workflow input as KEY=JSON. May be repeated.
450        #[arg(long, value_name = "KEY=JSON")]
451        input: Vec<String>,
452        /// Select human-readable or machine-readable plan output.
453        #[arg(long, value_enum, default_value_t)]
454        output: WorkflowDocumentFormat,
455    },
456    /// Create and run a workflow from an immutable plan.
457    Run {
458        /// Full plan UUID or unique UUID prefix.
459        #[arg(value_name = "PLAN_ID")]
460        plan_id: String,
461        /// Confirm the exact plan digest without an interactive prompt.
462        #[arg(long)]
463        yes: bool,
464        /// Select text or JSON Lines instead of the workflow TUI.
465        #[arg(long, value_enum)]
466        output: Option<WorkflowRunFormat>,
467    },
468    /// Read one durable workflow run snapshot.
469    Status {
470        /// Full run UUID or unique UUID prefix.
471        #[arg(value_name = "RUN_ID")]
472        run_id: String,
473        /// Select human-readable or machine-readable snapshot output.
474        #[arg(long, value_enum, default_value_t)]
475        output: WorkflowDocumentFormat,
476    },
477    /// Request cancellation of a durable workflow run.
478    Cancel {
479        /// Full run UUID or unique UUID prefix.
480        #[arg(value_name = "RUN_ID")]
481        run_id: String,
482    },
483    /// Resume a durable workflow run from its frozen graph.
484    Resume {
485        /// Full run UUID or unique UUID prefix.
486        #[arg(value_name = "RUN_ID")]
487        run_id: String,
488        /// Confirm the frozen graph without an interactive prompt.
489        #[arg(long)]
490        yes: bool,
491        /// Confirm that no prior process remains and recover uncertain attempts.
492        /// A Rho agent attempt continues its saved session; others restart.
493        #[arg(long)]
494        recover_uncertain: bool,
495        /// Report how each uncertain attempt would recover without changing the run.
496        #[arg(long)]
497        dry_run: bool,
498        /// Select text or JSON Lines instead of the workflow TUI.
499        #[arg(long, value_enum)]
500        output: Option<WorkflowRunFormat>,
501    },
502}
503
504#[derive(Subcommand, Clone, Debug)]
505pub enum WorktreesCommand {
506    /// Remove each worktree that is clean and merged, keeping its branch,
507    /// and say why each other one stays.
508    ///
509    /// A worktree is removed when nothing uses it, it has no uncommitted or
510    /// untracked changes, and its branch is merged into the current HEAD of
511    /// the checkout it was added from or the remote's default branch, by a
512    /// merge, rebase, or squash. Nothing uses a session's worktree when the
513    /// session is neither loaded nor running; nothing uses one no session
514    /// owns, as `rho run --worktree` and `git worktree add` make, when no
515    /// process works in it. The daemon does the same soon after it starts
516    /// and once a day, for worktrees unused for a day. Starts the daemon
517    /// when none is running.
518    Prune {
519        /// List what would be removed, and why, without removing anything.
520        #[arg(long)]
521        dry_run: bool,
522    },
523    /// List each worktree, largest first, with the space it takes and
524    /// whether `rho worktrees prune` would remove it, then the totals.
525    ///
526    /// Changes nothing, and needs the daemon running.
527    Status,
528}
529
530#[derive(Subcommand, Clone, Debug)]
531pub enum SessionsCommand {
532    /// List saved sessions for the current workspace (or all projects).
533    List {
534        /// Include sessions from every workspace, not only the current directory.
535        #[arg(long)]
536        all_projects: bool,
537        /// Case-insensitive filter over id, title, and first user message.
538        #[arg(long, short = 'q', value_name = "TEXT")]
539        search: Option<String>,
540        /// Limit how many sessions to print.
541        #[arg(long, value_name = "N")]
542        limit: Option<NonZeroUsize>,
543        /// Print one JSON document instead of text rows.
544        #[arg(long)]
545        json: bool,
546    },
547    /// Export a saved session transcript by UUID or UUID prefix.
548    Export {
549        /// Session UUID or unique prefix.
550        #[arg(value_name = "ID")]
551        id_prefix: String,
552        /// Output path. Omit to write under ~/.rho/exports/.
553        #[arg(long, short = 'o', value_name = "PATH")]
554        output: Option<PathBuf>,
555        /// Explicit format. When omitted, the path extension selects html, md, or json.
556        #[arg(long, value_enum)]
557        format: Option<crate::export::ExportFormat>,
558        /// Overwrite an existing file.
559        #[arg(long)]
560        force: bool,
561    },
562    /// Delete one or more sessions by UUID or UUID prefix.
563    Rm {
564        /// Session UUID or unique prefix. May be repeated.
565        #[arg(value_name = "ID", required = true, num_args = 1..)]
566        ids: Vec<String>,
567        /// Delete even when a parent-linked run is still non-terminal.
568        ///
569        /// Use only for stale Starting/Running artifacts left after a crash.
570        #[arg(long)]
571        force: bool,
572        /// Skip the confirmation prompt for cross-project deletes.
573        #[arg(short = 'y', long)]
574        yes: bool,
575    },
576    /// Delete sessions whose workspace directories no longer exist.
577    Cleanup {
578        /// Delete even when a parent-linked run is still non-terminal.
579        ///
580        /// Use only for stale Starting/Running artifacts left after a crash.
581        #[arg(long)]
582        force: bool,
583        /// Skip the confirmation prompt.
584        #[arg(short = 'y', long)]
585        yes: bool,
586    },
587    /// Rename a session by UUID or UUID prefix.
588    Rename {
589        /// Session UUID or unique prefix.
590        #[arg(value_name = "ID")]
591        id_prefix: String,
592        /// New session title. Multiple words are joined with spaces.
593        #[arg(value_name = "TITLE", required = true, num_args = 1.., trailing_var_arg = true)]
594        title: Vec<String>,
595    },
596}
597
598#[derive(Subcommand, Clone, Debug)]
599pub enum McpCommand {
600    /// List configured MCP servers from the selected config and plugins.
601    List {
602        /// Print one JSON document instead of text rows.
603        #[arg(long)]
604        json: bool,
605        /// Start enabled servers and report live connection status.
606        #[arg(long)]
607        connect: bool,
608    },
609    /// Show one MCP server by identity.
610    Show {
611        /// Server table key from `[mcp.servers.<id>]`.
612        #[arg(value_name = "ID")]
613        id: String,
614        /// Print one JSON document instead of text.
615        #[arg(long)]
616        json: bool,
617        /// Start enabled servers and report live connection status.
618        #[arg(long)]
619        connect: bool,
620    },
621    /// Serve the rho daemon's sessions as an MCP server: list, read, start,
622    /// prompt, steer, cancel, and wait for them.
623    ///
624    /// Over stdio by default, for a host that starts it as a command. With
625    /// `--http`, over streamable HTTP on a loopback or private network
626    /// address, for hosts that reach MCP servers by URL; every request then
627    /// needs a bearer token from `rho mcp token rotate`, and the server can
628    /// POST watched sessions' news to webhooks from `rho mcp webhook add`.
629    /// With remotes from `rho mcp remote add`, it drives their sessions
630    /// too, and every tool takes `server`. No tool answers a session's
631    /// approvals or questions.
632    Serve(McpServeArgs),
633    /// Manage the bearer tokens `rho mcp serve --http` accepts.
634    Token {
635        #[command(subcommand)]
636        command: McpTokenCommand,
637    },
638    /// Manage the webhooks `rho mcp serve --http` POSTs watched sessions'
639    /// news to.
640    Webhook {
641        #[command(subcommand)]
642        command: McpWebhookCommand,
643    },
644    /// Manage the other machines' `rho mcp serve --http` that this
645    /// machine's `rho mcp serve` drives as a hub.
646    Remote {
647        #[command(subcommand)]
648        command: McpRemoteCommand,
649    },
650}
651
652#[derive(clap::Args, Clone, Debug)]
653pub struct McpServeArgs {
654    /// Serve streamable HTTP on this address instead of stdio: a loopback
655    /// one, such as 127.0.0.1:8765, or this machine's address on a private
656    /// network, such as a NetBird or Tailscale peer's 100.x.y.z:8765, where
657    /// requests travel as plain HTTP.
658    #[arg(long, value_name = "ADDR")]
659    pub http: Option<std::net::SocketAddr>,
660    /// With `--http`, also accept this `Host` header, such as the tunnel's
661    /// public hostname. May be repeated.
662    #[arg(long, value_name = "HOST", requires = "http")]
663    pub allow_host: Vec<String>,
664    /// With `--http`, accept requests from this browser origin, such as
665    /// https://app.example.com. Any other `Origin` is refused. May be
666    /// repeated.
667    #[arg(long, value_name = "ORIGIN", requires = "http")]
668    pub allow_origin: Vec<String>,
669    /// The deepest a session this server starts or prompts may run: 1 for
670    /// a session started by a person's or an outside agent's call, one more
671    /// for each session in between. Defaults to 3.
672    #[arg(long, value_name = "N")]
673    pub max_depth: Option<u32>,
674    /// How many sessions each caller (each token, over HTTP) may have
675    /// running at once. Defaults to 10.
676    #[arg(long, value_name = "N")]
677    pub max_sessions: Option<u32>,
678    /// Over stdio, what the host may do: `read` lists, reads, and waits
679    /// for sessions and refuses every other tool; `write`, the default,
680    /// also starts, prompts, steers, and cancels them. With `--http` each
681    /// token carries its own scope instead.
682    #[arg(long, value_enum, conflicts_with = "http")]
683    pub scope: Option<McpTokenScope>,
684    /// The name this machine goes by: what webhook news says it is from,
685    /// and what `server` names it when the server has remotes. Defaults to
686    /// the host name.
687    #[arg(long, value_name = "NAME")]
688    pub name: Option<String>,
689    /// With `--http`, how many sessions each token may watch at once,
690    /// stalled watches included. Defaults to 5 times --max-sessions (50
691    /// by default). `rho mcp webhook list` shows each token's count.
692    #[arg(long, value_name = "N", requires = "http")]
693    pub max_watches: Option<u32>,
694    /// Internal: the listening socket a server that upgraded in place
695    /// handed this one.
696    #[arg(long, value_name = "FD", requires = "http", hide = true)]
697    pub listener_fd: Option<i32>,
698}
699
700#[derive(Subcommand, Clone, Debug)]
701pub enum McpTokenCommand {
702    /// Create token NAME, or give it a new secret, and print the secret
703    /// once. The old secret stops working at once.
704    Rotate {
705        /// The token's name, which refusals and `list` show.
706        #[arg(value_name = "NAME")]
707        name: String,
708        /// What the token may do: `read` lists, reads, and waits for
709        /// sessions; `write` also starts, prompts, steers, and cancels
710        /// them. A new token defaults to `read`; rotating keeps the
711        /// token's scope unless given.
712        #[arg(long, value_enum)]
713        scope: Option<McpTokenScope>,
714        /// A directory whose sessions, and those of everything under it,
715        /// the token may reach. May be repeated; a new token needs at least
716        /// one, and rotating keeps the token's list unless given.
717        #[arg(long, value_name = "DIR")]
718        workspace: Vec<PathBuf>,
719    },
720    /// List the tokens: their names, scopes, and workspaces.
721    List {
722        /// Print one JSON document instead of text rows.
723        #[arg(long)]
724        json: bool,
725    },
726    /// Delete token NAME; requests with it are refused at once.
727    Revoke {
728        #[arg(value_name = "NAME")]
729        name: String,
730    },
731}
732
733#[derive(Subcommand, Clone, Debug)]
734pub enum McpWebhookCommand {
735    /// Create webhook NAME, or replace it, reading its bearer secret from
736    /// stdin: `printf %s "$KEY" | rho mcp webhook add NAME --url URL
737    /// --token TOKEN`.
738    Add {
739        /// The webhook's name, which `watch` and `notify` take.
740        #[arg(value_name = "NAME")]
741        name: String,
742        /// Where to POST: an https URL, or http to a loopback host.
743        #[arg(long, value_name = "URL")]
744        url: String,
745        /// A token whose watches may use the webhook. May be repeated; at
746        /// least one.
747        #[arg(long, value_name = "TOKEN", required = true)]
748        token: Vec<String>,
749    },
750    /// List the webhooks: their names, URLs, tokens, last delivery, and
751    /// stalled watches. Never their secrets.
752    List {
753        /// Print one JSON document instead of text rows.
754        #[arg(long)]
755        json: bool,
756    },
757    /// Delete webhook NAME; watches that use it are dropped before their
758    /// next POST.
759    Remove {
760        #[arg(value_name = "NAME")]
761        name: String,
762    },
763}
764
765#[derive(Subcommand, Clone, Debug)]
766pub enum McpRemoteCommand {
767    /// Add remote NAME, or replace it, reading the secret of the token it
768    /// issued this machine from stdin, and check that it answers:
769    /// `ssh NAME '~/.local/bin/rho mcp token rotate hub --scope write
770    /// --workspace DIR' | rho mcp remote add NAME --url URL`, with the full
771    /// path of `rho` on NAME, which a non-interactive SSH shell may not
772    /// have on its PATH.
773    Add {
774        /// The remote's name, which `server` takes and webhook news names.
775        #[arg(value_name = "NAME")]
776        name: String,
777        /// The remote's MCP endpoint, such as
778        /// http://100.92.10.4:8765/mcp: https, or http to a loopback or
779        /// private network address.
780        #[arg(long, value_name = "URL")]
781        url: String,
782    },
783    /// List the remotes: their names and URLs. Never their secrets.
784    List {
785        /// Print one JSON document instead of text rows.
786        #[arg(long)]
787        json: bool,
788    },
789    /// Delete remote NAME; watches of its sessions are dropped before
790    /// their next POST.
791    Remove {
792        #[arg(value_name = "NAME")]
793        name: String,
794    },
795}
796
797/// What a caller of the MCP server may do: an HTTP token, or the host of a
798/// stdio server.
799#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
800pub enum McpTokenScope {
801    Read,
802    Write,
803}
804
805/// Target scope for plugin install and link.
806#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, ValueEnum)]
807pub enum PluginsScope {
808    /// User root: `~/.agents/plugins`.
809    #[default]
810    User,
811    /// Project root: `<repository>/.agents/plugins`.
812    Project,
813}
814
815#[derive(Subcommand, Clone, Debug)]
816pub enum PluginsCommand {
817    /// List discovered Agent Plugin packages.
818    List {
819        /// Print one JSON document instead of text rows.
820        #[arg(long)]
821        json: bool,
822    },
823    /// Inspect one plugin by package name without executing package code.
824    Inspect {
825        /// Plugin package name from `plugin.json`.
826        #[arg(value_name = "NAME")]
827        name: String,
828        /// Print one JSON document instead of text.
829        #[arg(long)]
830        json: bool,
831    },
832    /// Copy a plugin package from a local path or git repository into a managed plugins root.
833    Install {
834        /// Local directory with `plugin.json`, a GitHub link
835        /// (`https://github.com/<owner>/<repo>[/tree/<ref>/<path>]`), or a git URL.
836        #[arg(value_name = "SOURCE")]
837        source: std::ffi::OsString,
838        /// Install under the user or project plugins root.
839        #[arg(long, value_enum, default_value_t = PluginsScope::User)]
840        scope: PluginsScope,
841        /// Replace an existing package at the destination.
842        #[arg(long)]
843        force: bool,
844    },
845    /// Symlink a local plugin package into a managed plugins root.
846    Link {
847        /// Path to a directory that contains `plugin.json`.
848        #[arg(value_name = "PATH")]
849        path: PathBuf,
850        /// Link under the user or project plugins root.
851        #[arg(long, value_enum, default_value_t = PluginsScope::User)]
852        scope: PluginsScope,
853        /// Replace an existing package at the destination.
854        #[arg(long)]
855        force: bool,
856    },
857    /// Refetch git-installed plugins and replace them when their ref moved.
858    Update {
859        /// Plugin package name; omit to update every git-installed plugin.
860        #[arg(value_name = "NAME")]
861        name: Option<String>,
862    },
863    /// Enable a discovered plugin for new sessions.
864    Enable {
865        /// Plugin package name from `plugin.json`.
866        #[arg(value_name = "NAME")]
867        name: String,
868    },
869    /// Disable a discovered plugin without deleting package files.
870    Disable {
871        /// Plugin package name from `plugin.json`.
872        #[arg(value_name = "NAME")]
873        name: String,
874    },
875    /// Remove an installed or linked package from a managed plugins root.
876    Remove {
877        /// Plugin package name from `plugin.json`.
878        #[arg(value_name = "NAME")]
879        name: String,
880        /// Skip the confirmation prompt.
881        #[arg(short = 'y', long)]
882        yes: bool,
883    },
884}
885
886#[derive(Subcommand, Clone, Debug)]
887pub enum CredentialStoreCommand {
888    /// Test a credential backend by writing and deleting a temporary secret.
889    Probe {
890        /// Backend to test: os or file (`auto` is accepted as an alias for os).
891        #[arg(
892            value_name = "BACKEND",
893            default_value = "os",
894            value_parser = parse_credential_store_backend
895        )]
896        backend: CredentialStoreBackend,
897    },
898    /// Show the configured credential backend (unset, os, or file).
899    Status,
900    /// Save the credential backend used by future rho processes.
901    Set {
902        /// Backend to use: os or file (`auto` is accepted as an alias for os).
903        #[arg(value_name = "BACKEND", value_parser = parse_credential_store_backend)]
904        backend: CredentialStoreBackend,
905    },
906}
907
908#[cfg(test)]
909#[path = "cli_tests.rs"]
910mod tests;