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    /// Store or delete the secrets MCP servers read through
651    /// `env_from_secret` and `headers_from_secret`, kept in the rho
652    /// daemon's credential store.
653    Secret {
654        #[command(subcommand)]
655        command: McpSecretCommand,
656    },
657}
658
659#[derive(Subcommand, Clone, Debug)]
660pub enum McpSecretCommand {
661    /// Store secret NAME of server ID, replacing any. The value is read
662    /// hidden from the terminal, or from standard input when it is not one.
663    /// Sessions' servers read it when they next connect.
664    Set {
665        /// Server table key from `[mcp.servers.<id>]`.
666        #[arg(value_name = "ID")]
667        id: String,
668        /// The secret's name, as `env_from_secret` or
669        /// `headers_from_secret` lists it.
670        #[arg(value_name = "NAME")]
671        name: String,
672    },
673    /// Delete secret NAME of server ID.
674    #[command(visible_alias = "rm")]
675    Delete {
676        #[arg(value_name = "ID")]
677        id: String,
678        #[arg(value_name = "NAME")]
679        name: String,
680    },
681}
682
683#[derive(clap::Args, Clone, Debug)]
684pub struct McpServeArgs {
685    /// Serve streamable HTTP on this address instead of stdio: a loopback
686    /// one, such as 127.0.0.1:8765, or this machine's address on a private
687    /// network, such as a NetBird or Tailscale peer's 100.x.y.z:8765, where
688    /// requests travel as plain HTTP.
689    #[arg(long, value_name = "ADDR")]
690    pub http: Option<std::net::SocketAddr>,
691    /// With `--http`, also accept this `Host` header, such as the tunnel's
692    /// public hostname. May be repeated.
693    #[arg(long, value_name = "HOST", requires = "http")]
694    pub allow_host: Vec<String>,
695    /// With `--http`, accept requests from this browser origin, such as
696    /// https://app.example.com. Any other `Origin` is refused. May be
697    /// repeated.
698    #[arg(long, value_name = "ORIGIN", requires = "http")]
699    pub allow_origin: Vec<String>,
700    /// The deepest a session this server starts or prompts may run: 1 for
701    /// a session started by a person's or an outside agent's call, one more
702    /// for each session in between. Defaults to 3.
703    #[arg(long, value_name = "N")]
704    pub max_depth: Option<u32>,
705    /// How many sessions each caller (each token, over HTTP) may have
706    /// running at once. Defaults to 10.
707    #[arg(long, value_name = "N")]
708    pub max_sessions: Option<u32>,
709    /// Over stdio, what the host may do: `read` lists, reads, and waits
710    /// for sessions and refuses every other tool; `write`, the default,
711    /// also starts, prompts, steers, and cancels them. With `--http` each
712    /// token carries its own scope instead.
713    #[arg(long, value_enum, conflicts_with = "http")]
714    pub scope: Option<McpTokenScope>,
715    /// The name this machine goes by: what webhook news says it is from,
716    /// and what `server` names it when the server has remotes. Defaults to
717    /// the host name.
718    #[arg(long, value_name = "NAME")]
719    pub name: Option<String>,
720    /// With `--http`, how many sessions each token may watch at once,
721    /// stalled watches included. Defaults to 5 times --max-sessions (50
722    /// by default). `rho mcp webhook list` shows each token's count.
723    #[arg(long, value_name = "N", requires = "http")]
724    pub max_watches: Option<u32>,
725    /// Internal: the listening socket a server that upgraded in place
726    /// handed this one.
727    #[arg(long, value_name = "FD", requires = "http", hide = true)]
728    pub listener_fd: Option<i32>,
729}
730
731#[derive(Subcommand, Clone, Debug)]
732pub enum McpTokenCommand {
733    /// Create token NAME, or give it a new secret, and print the secret
734    /// once. The old secret stops working at once.
735    Rotate {
736        /// The token's name, which refusals and `list` show.
737        #[arg(value_name = "NAME")]
738        name: String,
739        /// What the token may do: `read` lists, reads, and waits for
740        /// sessions; `write` also starts, prompts, steers, and cancels
741        /// them. A new token defaults to `read`; rotating keeps the
742        /// token's scope unless given.
743        #[arg(long, value_enum)]
744        scope: Option<McpTokenScope>,
745        /// A directory whose sessions, and those of everything under it,
746        /// the token may reach. May be repeated; a new token needs at least
747        /// one, and rotating keeps the token's list unless given.
748        #[arg(long, value_name = "DIR")]
749        workspace: Vec<PathBuf>,
750    },
751    /// List the tokens: their names, scopes, and workspaces.
752    List {
753        /// Print one JSON document instead of text rows.
754        #[arg(long)]
755        json: bool,
756    },
757    /// Delete token NAME; requests with it are refused at once.
758    Revoke {
759        #[arg(value_name = "NAME")]
760        name: String,
761    },
762}
763
764#[derive(Subcommand, Clone, Debug)]
765pub enum McpWebhookCommand {
766    /// Create webhook NAME, or replace it, reading its bearer secret from
767    /// stdin: `printf %s "$KEY" | rho mcp webhook add NAME --url URL
768    /// --token TOKEN`.
769    Add {
770        /// The webhook's name, which `watch` and `notify` take.
771        #[arg(value_name = "NAME")]
772        name: String,
773        /// Where to POST: an https URL, or http to a loopback host.
774        #[arg(long, value_name = "URL")]
775        url: String,
776        /// A token whose watches may use the webhook. May be repeated; at
777        /// least one.
778        #[arg(long, value_name = "TOKEN", required = true)]
779        token: Vec<String>,
780    },
781    /// List the webhooks: their names, URLs, tokens, last delivery, and
782    /// stalled watches. Never their secrets.
783    List {
784        /// Print one JSON document instead of text rows.
785        #[arg(long)]
786        json: bool,
787    },
788    /// Delete webhook NAME; watches that use it are dropped before their
789    /// next POST.
790    Remove {
791        #[arg(value_name = "NAME")]
792        name: String,
793    },
794}
795
796#[derive(Subcommand, Clone, Debug)]
797pub enum McpRemoteCommand {
798    /// Add remote NAME, or replace it, reading the secret of the token it
799    /// issued this machine from stdin, and check that it answers:
800    /// `ssh NAME '~/.local/bin/rho mcp token rotate hub --scope write
801    /// --workspace DIR' | rho mcp remote add NAME --url URL`, with the full
802    /// path of `rho` on NAME, which a non-interactive SSH shell may not
803    /// have on its PATH.
804    Add {
805        /// The remote's name, which `server` takes and webhook news names.
806        #[arg(value_name = "NAME")]
807        name: String,
808        /// The remote's MCP endpoint, such as
809        /// http://100.92.10.4:8765/mcp: https, or http to a loopback or
810        /// private network address.
811        #[arg(long, value_name = "URL")]
812        url: String,
813    },
814    /// List the remotes: their names and URLs. Never their secrets.
815    List {
816        /// Print one JSON document instead of text rows.
817        #[arg(long)]
818        json: bool,
819    },
820    /// Delete remote NAME; watches of its sessions are dropped before
821    /// their next POST.
822    Remove {
823        #[arg(value_name = "NAME")]
824        name: String,
825    },
826}
827
828/// What a caller of the MCP server may do: an HTTP token, or the host of a
829/// stdio server.
830#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
831pub enum McpTokenScope {
832    Read,
833    Write,
834}
835
836/// Target scope for plugin install and link.
837#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, ValueEnum)]
838pub enum PluginsScope {
839    /// User root: `~/.agents/plugins`.
840    #[default]
841    User,
842    /// Project root: `<repository>/.agents/plugins`.
843    Project,
844}
845
846#[derive(Subcommand, Clone, Debug)]
847pub enum PluginsCommand {
848    /// List discovered Agent Plugin packages.
849    List {
850        /// Print one JSON document instead of text rows.
851        #[arg(long)]
852        json: bool,
853    },
854    /// Inspect one plugin by package name without executing package code.
855    Inspect {
856        /// Plugin package name from `plugin.json`.
857        #[arg(value_name = "NAME")]
858        name: String,
859        /// Print one JSON document instead of text.
860        #[arg(long)]
861        json: bool,
862    },
863    /// Copy a plugin package from a local path or git repository into a managed plugins root.
864    Install {
865        /// Local directory with `plugin.json`, a GitHub link
866        /// (`https://github.com/<owner>/<repo>[/tree/<ref>/<path>]`), or a git URL.
867        #[arg(value_name = "SOURCE")]
868        source: std::ffi::OsString,
869        /// Install under the user or project plugins root.
870        #[arg(long, value_enum, default_value_t = PluginsScope::User)]
871        scope: PluginsScope,
872        /// Replace an existing package at the destination.
873        #[arg(long)]
874        force: bool,
875    },
876    /// Symlink a local plugin package into a managed plugins root.
877    Link {
878        /// Path to a directory that contains `plugin.json`.
879        #[arg(value_name = "PATH")]
880        path: PathBuf,
881        /// Link under the user or project plugins root.
882        #[arg(long, value_enum, default_value_t = PluginsScope::User)]
883        scope: PluginsScope,
884        /// Replace an existing package at the destination.
885        #[arg(long)]
886        force: bool,
887    },
888    /// Refetch git-installed plugins and replace them when their ref moved.
889    Update {
890        /// Plugin package name; omit to update every git-installed plugin.
891        #[arg(value_name = "NAME")]
892        name: Option<String>,
893    },
894    /// Enable a discovered plugin for new sessions.
895    Enable {
896        /// Plugin package name from `plugin.json`.
897        #[arg(value_name = "NAME")]
898        name: String,
899    },
900    /// Disable a discovered plugin without deleting package files.
901    Disable {
902        /// Plugin package name from `plugin.json`.
903        #[arg(value_name = "NAME")]
904        name: String,
905    },
906    /// Remove an installed or linked package from a managed plugins root.
907    Remove {
908        /// Plugin package name from `plugin.json`.
909        #[arg(value_name = "NAME")]
910        name: String,
911        /// Skip the confirmation prompt.
912        #[arg(short = 'y', long)]
913        yes: bool,
914    },
915}
916
917#[derive(Subcommand, Clone, Debug)]
918pub enum CredentialStoreCommand {
919    /// Test a credential backend by writing and deleting a temporary secret.
920    Probe {
921        /// Backend to test: os or file (`auto` is accepted as an alias for os).
922        #[arg(
923            value_name = "BACKEND",
924            default_value = "os",
925            value_parser = parse_credential_store_backend
926        )]
927        backend: CredentialStoreBackend,
928    },
929    /// Show the configured credential backend (unset, os, or file).
930    Status,
931    /// Save the credential backend used by future rho processes.
932    Set {
933        /// Backend to use: os or file (`auto` is accepted as an alias for os).
934        #[arg(value_name = "BACKEND", value_parser = parse_credential_store_backend)]
935        backend: CredentialStoreBackend,
936    },
937}
938
939#[cfg(test)]
940#[path = "cli_tests.rs"]
941mod tests;