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