rho-coding-agent 3.6.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
use std::{num::NonZeroUsize, path::PathBuf, time::Duration};

use clap::{Parser, Subcommand, ValueEnum};

use rho_providers::{credentials::CredentialStoreBackend, reasoning::ReasoningLevel};

use crate::{
    app::automation_protocol::parse_duration,
    permission::{PermissionMode, PermissionModeParseError},
};

#[path = "cli_daemon.rs"]
mod daemon;

pub use daemon::{DaemonCommand, DaemonServeArgs, DaemonTokenCommand};

fn parse_permission_mode(value: &str) -> Result<PermissionMode, PermissionModeParseError> {
    value.parse()
}

fn parse_credential_store_backend(value: &str) -> Result<CredentialStoreBackend, String> {
    CredentialStoreBackend::parse(value).map_err(|error| error.to_string())
}

fn parse_auth_profile(value: &str) -> Result<String, String> {
    let profiles = rho_providers::auth_profiles();
    if profiles.contains(&value) {
        return Ok(value.to_string());
    }
    if rho_providers::provider::is_custom_provider_api_key_auth(value) {
        return Ok(value.to_string());
    }
    Err(format!(
        "invalid value '{value}' for '--auth'; expected one of: {}",
        profiles.join(", ")
    ))
}

/// Output contract used by a non-interactive `rho run` invocation.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, ValueEnum)]
pub enum OutputFormat {
    /// Print only the authoritative final assistant answer.
    #[default]
    Text,
    /// Stream independently versioned JSON Lines events.
    Jsonl,
}

/// How `rho attach` writes a session's events.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, ValueEnum)]
pub enum AttachOutput {
    /// Stream the conversation to stdout, and notices to stderr.
    #[default]
    Text,
    /// Stream `rho run --output jsonl`'s JSON Lines events.
    Jsonl,
}

/// Where text-mode `rho attach` reads the lines that answer and steer.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, ValueEnum)]
pub enum AttachInput {
    /// Stdin, when it is the terminal and `rho attach` runs in its
    /// foreground; otherwise requests are only told.
    #[default]
    Terminal,
    /// Stdin, whatever it is, such as a pipe a script writes answers to.
    Stdin,
}

/// Output contract for workflow plans and snapshots.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, ValueEnum)]
pub enum WorkflowDocumentFormat {
    /// Print a human-readable document.
    #[default]
    Text,
    /// Print one JSON document.
    Json,
}

/// Output contract for workflow execution.
#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
pub enum WorkflowRunFormat {
    /// Print human-readable state changes.
    Text,
    /// Stream versioned JSON Lines events.
    Jsonl,
}

#[derive(Parser, Clone, Debug)]
#[command(name = "rho", version)]
pub struct Cli {
    #[arg(long)]
    pub provider: Option<String>,
    #[arg(long)]
    pub model: Option<String>,
    #[arg(long)]
    pub config: Option<PathBuf>,
    #[arg(long, value_parser = parse_auth_profile)]
    pub auth: Option<String>,
    /// Do not send rho's system prompt, including AGENTS.md and skill context.
    #[arg(long)]
    pub no_system_prompt: bool,
    /// Do not expose any tools to the model.
    #[arg(long)]
    pub no_tools: bool,
    /// Do not expose the delegated-agent tools (agent/agents) to the model.
    #[arg(long, global = true)]
    pub no_subagents: bool,
    /// Select the agent definition used for this session or automation run.
    #[arg(long, global = true, value_name = "ID")]
    pub agent: Option<String>,
    /// Override reasoning level: off, minimal, low, medium, high, xhigh, or max.
    #[arg(long)]
    pub reasoning: Option<ReasoningLevel>,
    /// Override permission mode: bypass, auto, allow_edits, plan, or supervised.
    #[arg(long, value_name = "MODE", value_parser = parse_permission_mode)]
    pub(crate) permission_mode: Option<PermissionMode>,
    /// Add a directory to the workspace scope. Repeat for more directories.
    ///
    /// Checked permission modes treat reads there like workspace reads, and
    /// its AGENTS.md files load with the project's. Interactive sessions save
    /// added directories and restore them on resume.
    #[arg(long = "add-dir", value_name = "PATH", global = true)]
    pub add_dirs: Vec<PathBuf>,
    /// Persist --provider/--model/--auth/--reasoning overrides to the config file.
    ///
    /// Without this flag, those overrides apply only to the current invocation.
    #[arg(long)]
    pub save: bool,
    /// Keep this interactive session in memory without saving its transcript or prompt history.
    #[arg(long, conflicts_with_all = ["resume", "continue_latest"])]
    pub no_save: bool,
    /// Resume an existing session by UUID or UUID prefix. Omit the ID to choose from a picker.
    #[arg(short = 'R', long, value_name = "ID", num_args = 0..=1)]
    pub resume: Option<Option<String>>,
    /// Resume the most recent session in the current workspace without a picker.
    ///
    /// Starts a new session when the workspace has no saved sessions yet.
    #[arg(short = 'c', long = "continue", conflicts_with = "resume")]
    pub continue_latest: bool,
    /// Open the interactive TUI with this prompt already submitted.
    ///
    /// This starts a normal session. Use `rho run` when you want one answer and
    /// then exit.
    #[arg(long, value_name = "PROMPT")]
    pub prompt: Option<String>,
    /// Draw the interactive TUI on the terminal's main screen so the
    /// transcript stays in native scrollback, for this launch.
    ///
    /// Turns off mouse capture, in-app scrolling, transcript search, and
    /// inline images. Set `minimal_mode = true` in `clients/tui.toml` to make
    /// it the default.
    #[arg(long)]
    pub minimal: bool,
    #[command(subcommand)]
    pub command: Option<Command>,
}

#[derive(Subcommand, Clone, Debug)]
pub enum ModelPromptCommand {
    /// Open custom system instructions for a model in $VISUAL or $EDITOR.
    #[command(after_help = "Examples:
  rho model-prompt edit
      Choose a model from a searchable picker, then edit its instructions.
  rho model-prompt edit --provider openai-codex
      Choose from locally known models for one provider.
  rho model-prompt edit --provider openai-codex --model gpt-6-astra
      Edit instructions for an exact provider/model pair.
  rho model-prompt edit --model @local
      Resolve a model alias from your config.
  VISUAL='code --wait' rho model-prompt edit
      Use an editor that waits until you close the file.
  rho --config /path/to/config.toml model-prompt edit
      Use a different configuration file.

Editing:
  Without --model, opens a picker. Type to filter, Enter to edit, Esc to cancel.
  The picker uses local catalogs without requiring login or fetching models.
  Non-interactive callers must pass --model explicitly.
  Uses $VISUAL, falling back to $EDITOR. Set one before running this command.
  Opens a private draft of the matching file in ~/.rho/model-prompts/.
  If none exists, starts a draft with provider, model, and mode frontmatter.
  Keep provider/model unchanged and write Markdown instructions below the
  closing --- line. Save and exit the editor to validate and install the file.
  Leaving the draft unchanged cancels. Invalid edits preserve a recovery draft.

Modes:
  mode: append   Add to Rho's default behavioral instructions. This is the default.
  mode: replace  Replace only that behavioral block, not tool instructions,
                 AGENTS.md, skills, or permission rules.

Scope:
  Instructions are global for the exact provider/model pair, not project-local.
  Editing works offline and does not start a session or change your default model.
  Sessions load changes at startup, model switch, /new, or resume, not each turn.")]
    Edit {
        /// Filter the picker by provider; with --model, override the configured provider.
        #[arg(long)]
        provider: Option<String>,
        /// Exact model ID or @alias. Omit to choose from an interactive picker.
        #[arg(long)]
        model: Option<String>,
    },
}

#[derive(Subcommand, Clone, Debug)]
pub enum Command {
    /// Run one non-interactive automation prompt and print the final answer.
    Run {
        /// Read additional prompt text from stdin.
        ///
        /// Required when stdin is a pipe or redirected file. Without this flag,
        /// redirected stdin is rejected so prompt text is not silently dropped.
        #[arg(long)]
        stdin: bool,
        /// Write a structured status/result file (JSON) that is updated during
        /// the run and finalized on exit. With `--output text` (the default),
        /// progress and streamed assistant text go to stdout and the run ends
        /// with a completion marker; the result file is the durable final
        /// answer. With `--output jsonl`, stdout stays the JSONL event stream.
        #[arg(long, value_name = "PATH")]
        output_file: Option<PathBuf>,
        /// Select plain final-answer output or a JSON Lines event stream.
        #[arg(long, value_enum, default_value_t)]
        output: OutputFormat,
        /// Override the model-step budget for this run.
        #[arg(long, value_name = "N")]
        max_steps: Option<NonZeroUsize>,
        /// Cancel the run after this wall-clock duration.
        #[arg(long, value_name = "DURATION", value_parser = parse_duration)]
        timeout: Option<Duration>,
        /// Do not save the run's session or its Rho and Claude subagents'
        /// sessions, so none is left to export or resume.
        ///
        /// Cursor and Antigravity subagents keep their own CLI sessions, and
        /// workflow nodes the run starts save theirs as part of the workflow
        /// run's record.
        #[arg(long)]
        no_save: bool,
        /// Start the run in the rho daemon, starting one if none runs, and
        /// exit once its prompt is saved, printing the session's id. The
        /// turn runs on; `rho attach <ID>` follows it and answers its
        /// approvals and questions. `--timeout` is enforced by the daemon.
        #[arg(long, conflicts_with_all = ["output_file", "output", "max_steps", "no_save"])]
        detach: bool,
        /// Run in a new git worktree of the current directory's repository,
        /// on a new branch from `origin`'s default branch, fetched first, or
        /// from the repository's HEAD when there is no `origin`, the fetch
        /// fails or takes over 30 seconds, or `git.worktree_from_remote` is
        /// off, so runs in one repository cannot overwrite each other's
        /// edits. The worktree is made under the rho
        /// home, and the run works at the current directory's place in it.
        /// The daemon removes it once it is clean and merged, nothing has
        /// worked in it for a day, and no process works in it; the branch
        /// stays (see `rho worktrees`).
        #[arg(long)]
        worktree: bool,
        /// Prompt text to send to the agent.
        #[arg(value_name = "PROMPT", num_args = 0..)]
        prompt: Vec<String>,
    },
    /// Follow a daemon session's turn until it ends, and exit as it ended.
    ///
    /// Without a turn under way, report the session's last turn. In text
    /// mode, lines typed at the terminal answer the turn's requests, steer
    /// it, or cancel it with `/cancel`. Ctrl+C detaches; the turn runs on in
    /// the daemon.
    Attach {
        /// The session's id, or its job's.
        #[arg(value_name = "ID")]
        id: String,
        /// Write the session's events as text or as the JSON Lines stream
        /// `rho run --output jsonl` writes.
        #[arg(long, value_enum, default_value_t)]
        output: AttachOutput,
        /// In text mode, where to read the lines that answer the turn's
        /// requests and steer it.
        #[arg(long, value_enum, default_value_t)]
        input: AttachInput,
    },
    /// Log in to a provider with an API key, browser, or device-code flow.
    Login {
        /// Provider to authenticate, for example openai-codex or github-copilot,
        /// or `antigravity` to run agy's own sign-in for Antigravity subagents.
        #[arg(value_name = "PROVIDER")]
        provider: String,
        /// Use device-code login instead of opening a local browser callback.
        #[arg(long)]
        device_auth: bool,
    },
    /// Configure or probe provider credential storage.
    CredentialStore {
        #[command(subcommand)]
        command: CredentialStoreCommand,
    },
    /// Customize system instructions for an exact provider/model pair.
    #[command(after_help = "Quick start:
  rho model-prompt edit
  rho model-prompt edit --provider openai-codex --model gpt-6-astra
  rho model-prompt edit --model @local

Uses $VISUAL, falling back to $EDITOR, to edit Markdown instructions stored in
~/.rho/model-prompts/. With no --model, opens a searchable model picker.
Use --provider to narrow the list, or --model to skip the picker.
Non-interactive callers must pass --model explicitly.
New files append to Rho's default behavioral instructions; mode: replace replaces
only that behavioral block. Instructions apply globally, not just to this project.
This edits instructions offline; it does not send a prompt or start a session.

Run rho model-prompt edit --help for editor setup, saving, and reload behavior.")]
    ModelPrompt {
        #[command(subcommand)]
        command: ModelPromptCommand,
    },
    /// Update rho using the detected installation method.
    Update {
        /// Report whether an update exists and how rho would install it,
        /// without installing anything. Exits with status 1 when the
        /// latest release cannot be looked up.
        #[arg(long)]
        check: bool,
        /// Print the `--check` report as one JSON object.
        #[arg(long, requires = "check")]
        json: bool,
    },
    /// Uninstall Rho after confirmation, preserving user data by default.
    Uninstall {
        /// Also permanently delete local Rho user data under ~/.rho.
        #[arg(long)]
        purge: bool,
        /// Preview removal paths without changing anything or prompting.
        #[arg(long)]
        dry_run: bool,
    },
    /// List, rename, or delete saved sessions.
    Sessions {
        #[command(subcommand)]
        command: SessionsCommand,
    },
    /// Inspect configured Model Context Protocol servers, or serve rho's
    /// sessions as one.
    Mcp {
        #[command(subcommand)]
        command: McpCommand,
    },
    /// List, inspect, install, and activate local Agent Plugin packages.
    Plugins {
        #[command(subcommand)]
        command: PluginsCommand,
    },
    /// Validate, plan, run, and inspect deterministic workflows.
    Workflow {
        #[command(subcommand)]
        command: WorkflowCommand,
    },
    /// Run local setup diagnostics and print a report.
    ///
    /// Same checks as the interactive `/doctor` overlay. Exits with status 1
    /// when any check fails; warnings exit 0.
    Doctor {
        /// Print the report as JSON.
        #[arg(long)]
        json: bool,
    },
    /// Serve the Agent Client Protocol over stdio for editor/host integration.
    Acp(AcpArgs),
    /// Run or control the rho daemon for this rho home.
    ///
    /// Without a subcommand, runs the daemon in the foreground.
    Daemon {
        #[command(subcommand)]
        command: Option<DaemonCommand>,
    },
    /// Inspect and clean up the git worktrees under the rho home.
    Worktrees {
        #[command(subcommand)]
        command: WorktreesCommand,
    },
    /// Internal supervised workflow planner worker. Not a public command.
    #[command(name = "__workflow_planner_worker", hide = true)]
    WorkflowPlannerWorker,
    /// Debug-only scripted ACP agent on stdio for offline external-runtime
    /// E2E tests. Refuses to run outside `RHO_TUI_TEST_MODE=matrix`.
    #[cfg(debug_assertions)]
    #[command(name = "__acp-fixture-agent", hide = true)]
    AcpFixtureAgent(AcpFixtureAgentArgs),
}

/// Options for `rho acp`.
#[derive(clap::Args, Clone, Debug, Default)]
pub struct AcpArgs {
    /// Mark the host as T3 Code: subagents run as T3 child threads through
    /// its `t3-code` MCP server, and a background process or workflow that
    /// finishes after a prompt ended wakes the idle thread with its result.
    #[arg(long)]
    pub t3code: bool,
    /// Run terminal authentication for an auth profile instead of serving ACP.
    /// Hosts append this option to the configured agent invocation.
    #[arg(long, value_name = "AUTH")]
    pub login: Option<String>,
}

/// Inputs for the debug-only scripted ACP agent.
#[cfg(debug_assertions)]
#[derive(clap::Args, Clone, Debug)]
pub struct AcpFixtureAgentArgs {
    /// Script JSON: handshake outcomes, session modes, and per-turn steps.
    #[arg(long, value_name = "PATH")]
    pub script: PathBuf,
    /// Append every request Rho sends and every reply it gives here (JSONL).
    #[arg(long, value_name = "PATH")]
    pub journal: PathBuf,
}

/// Argv entry for the internal supervised planner worker process.
pub const WORKFLOW_PLANNER_WORKER_COMMAND: &str = "__workflow_planner_worker";

#[derive(Subcommand, Clone, Debug)]
pub enum WorkflowCommand {
    /// List saved workflow plans and runs for the current workspace.
    List {
        /// Include only saved plans.
        #[arg(long, conflicts_with = "runs")]
        plans: bool,
        /// Include only runs.
        #[arg(long, conflicts_with = "plans")]
        runs: bool,
        /// Limit how many rows to print per section.
        #[arg(long, value_name = "N")]
        limit: Option<NonZeroUsize>,
        /// Print one JSON document instead of text rows.
        #[arg(long)]
        json: bool,
    },
    /// Validate a Starlark workflow without creating durable state.
    Validate {
        /// Workflow entry file under the current workspace.
        #[arg(value_name = "FILE")]
        file: PathBuf,
        /// Supply one non-secret workflow input as KEY=JSON. May be repeated.
        #[arg(long, value_name = "KEY=JSON")]
        input: Vec<String>,
    },
    /// Validate, freeze, and persist an immutable workflow plan.
    Plan {
        /// Workflow entry file under the current workspace.
        #[arg(value_name = "FILE")]
        file: PathBuf,
        /// Supply one non-secret workflow input as KEY=JSON. May be repeated.
        #[arg(long, value_name = "KEY=JSON")]
        input: Vec<String>,
        /// Select human-readable or machine-readable plan output.
        #[arg(long, value_enum, default_value_t)]
        output: WorkflowDocumentFormat,
    },
    /// Create and run a workflow from an immutable plan.
    Run {
        /// Full plan UUID or unique UUID prefix.
        #[arg(value_name = "PLAN_ID")]
        plan_id: String,
        /// Confirm the exact plan digest without an interactive prompt.
        #[arg(long)]
        yes: bool,
        /// Select text or JSON Lines instead of the workflow TUI.
        #[arg(long, value_enum)]
        output: Option<WorkflowRunFormat>,
    },
    /// Read one durable workflow run snapshot.
    Status {
        /// Full run UUID or unique UUID prefix.
        #[arg(value_name = "RUN_ID")]
        run_id: String,
        /// Select human-readable or machine-readable snapshot output.
        #[arg(long, value_enum, default_value_t)]
        output: WorkflowDocumentFormat,
    },
    /// Request cancellation of a durable workflow run.
    Cancel {
        /// Full run UUID or unique UUID prefix.
        #[arg(value_name = "RUN_ID")]
        run_id: String,
    },
    /// Resume a durable workflow run from its frozen graph.
    Resume {
        /// Full run UUID or unique UUID prefix.
        #[arg(value_name = "RUN_ID")]
        run_id: String,
        /// Confirm the frozen graph without an interactive prompt.
        #[arg(long)]
        yes: bool,
        /// Confirm that no prior process remains and recover uncertain attempts.
        /// A Rho agent attempt continues its saved session; others restart.
        #[arg(long)]
        recover_uncertain: bool,
        /// Report how each uncertain attempt would recover without changing the run.
        #[arg(long)]
        dry_run: bool,
        /// Select text or JSON Lines instead of the workflow TUI.
        #[arg(long, value_enum)]
        output: Option<WorkflowRunFormat>,
    },
}

#[derive(Subcommand, Clone, Debug)]
pub enum WorktreesCommand {
    /// Remove each worktree that is clean and merged, keeping its branch,
    /// and say why each other one stays.
    ///
    /// A worktree is removed when nothing uses it, it has no uncommitted or
    /// untracked changes, and its branch is merged into the current HEAD of
    /// the checkout it was added from or the remote's default branch, by a
    /// merge, rebase, or squash. Nothing uses a session's worktree when the
    /// session is neither loaded nor running; nothing uses one no session
    /// owns, as `rho run --worktree` and `git worktree add` make, when no
    /// process works in it. The daemon does the same soon after it starts
    /// and once a day, for worktrees unused for a day. Starts the daemon
    /// when none is running.
    Prune {
        /// List what would be removed, and why, without removing anything.
        #[arg(long)]
        dry_run: bool,
    },
    /// List each worktree, largest first, with the space it takes and
    /// whether `rho worktrees prune` would remove it, then the totals.
    ///
    /// Changes nothing, and needs the daemon running.
    Status,
}

#[derive(Subcommand, Clone, Debug)]
pub enum SessionsCommand {
    /// List saved sessions for the current workspace (or all projects).
    List {
        /// Include sessions from every workspace, not only the current directory.
        #[arg(long)]
        all_projects: bool,
        /// Case-insensitive filter over id, title, and first user message.
        #[arg(long, short = 'q', value_name = "TEXT")]
        search: Option<String>,
        /// Limit how many sessions to print.
        #[arg(long, value_name = "N")]
        limit: Option<NonZeroUsize>,
        /// Print one JSON document instead of text rows.
        #[arg(long)]
        json: bool,
    },
    /// Export a saved session transcript by UUID or UUID prefix.
    Export {
        /// Session UUID or unique prefix.
        #[arg(value_name = "ID")]
        id_prefix: String,
        /// Output path. Omit to write under ~/.rho/exports/.
        #[arg(long, short = 'o', value_name = "PATH")]
        output: Option<PathBuf>,
        /// Explicit format. When omitted, the path extension selects html, md, or json.
        #[arg(long, value_enum)]
        format: Option<crate::export::ExportFormat>,
        /// Overwrite an existing file.
        #[arg(long)]
        force: bool,
    },
    /// Delete one or more sessions by UUID or UUID prefix.
    Rm {
        /// Session UUID or unique prefix. May be repeated.
        #[arg(value_name = "ID", required = true, num_args = 1..)]
        ids: Vec<String>,
        /// Delete even when a parent-linked run is still non-terminal.
        ///
        /// Use only for stale Starting/Running artifacts left after a crash.
        #[arg(long)]
        force: bool,
        /// Skip the confirmation prompt for cross-project deletes.
        #[arg(short = 'y', long)]
        yes: bool,
    },
    /// Delete sessions whose workspace directories no longer exist.
    Cleanup {
        /// Delete even when a parent-linked run is still non-terminal.
        ///
        /// Use only for stale Starting/Running artifacts left after a crash.
        #[arg(long)]
        force: bool,
        /// Skip the confirmation prompt.
        #[arg(short = 'y', long)]
        yes: bool,
    },
    /// Rename a session by UUID or UUID prefix.
    Rename {
        /// Session UUID or unique prefix.
        #[arg(value_name = "ID")]
        id_prefix: String,
        /// New session title. Multiple words are joined with spaces.
        #[arg(value_name = "TITLE", required = true, num_args = 1.., trailing_var_arg = true)]
        title: Vec<String>,
    },
}

#[derive(Subcommand, Clone, Debug)]
pub enum McpCommand {
    /// List configured MCP servers from the selected config and plugins.
    List {
        /// Print one JSON document instead of text rows.
        #[arg(long)]
        json: bool,
        /// Start enabled servers and report live connection status.
        #[arg(long)]
        connect: bool,
    },
    /// Show one MCP server by identity.
    Show {
        /// Server table key from `[mcp.servers.<id>]`.
        #[arg(value_name = "ID")]
        id: String,
        /// Print one JSON document instead of text.
        #[arg(long)]
        json: bool,
        /// Start enabled servers and report live connection status.
        #[arg(long)]
        connect: bool,
    },
    /// Serve the rho daemon's sessions as an MCP server: list, read, start,
    /// prompt, steer, cancel, and wait for them.
    ///
    /// Over stdio by default, for a host that starts it as a command. With
    /// `--http`, over streamable HTTP on a loopback or private network
    /// address, for hosts that reach MCP servers by URL; every request then
    /// needs a bearer token from `rho mcp token rotate`, and the server can
    /// POST watched sessions' news to webhooks from `rho mcp webhook add`.
    /// With remotes from `rho mcp remote add`, it drives their sessions
    /// too, and every tool takes `server`. No tool answers a session's
    /// approvals or questions.
    Serve(McpServeArgs),
    /// Manage the bearer tokens `rho mcp serve --http` accepts.
    Token {
        #[command(subcommand)]
        command: McpTokenCommand,
    },
    /// Manage the webhooks `rho mcp serve --http` POSTs watched sessions'
    /// news to.
    Webhook {
        #[command(subcommand)]
        command: McpWebhookCommand,
    },
    /// Manage the other machines' `rho mcp serve --http` that this
    /// machine's `rho mcp serve` drives as a hub.
    Remote {
        #[command(subcommand)]
        command: McpRemoteCommand,
    },
}

#[derive(clap::Args, Clone, Debug)]
pub struct McpServeArgs {
    /// Serve streamable HTTP on this address instead of stdio: a loopback
    /// one, such as 127.0.0.1:8765, or this machine's address on a private
    /// network, such as a NetBird or Tailscale peer's 100.x.y.z:8765, where
    /// requests travel as plain HTTP.
    #[arg(long, value_name = "ADDR")]
    pub http: Option<std::net::SocketAddr>,
    /// With `--http`, also accept this `Host` header, such as the tunnel's
    /// public hostname. May be repeated.
    #[arg(long, value_name = "HOST", requires = "http")]
    pub allow_host: Vec<String>,
    /// With `--http`, accept requests from this browser origin, such as
    /// https://app.example.com. Any other `Origin` is refused. May be
    /// repeated.
    #[arg(long, value_name = "ORIGIN", requires = "http")]
    pub allow_origin: Vec<String>,
    /// The deepest a session this server starts or prompts may run: 1 for
    /// a session started by a person's or an outside agent's call, one more
    /// for each session in between. Defaults to 3.
    #[arg(long, value_name = "N")]
    pub max_depth: Option<u32>,
    /// How many sessions each caller (each token, over HTTP) may have
    /// running at once. Defaults to 10.
    #[arg(long, value_name = "N")]
    pub max_sessions: Option<u32>,
    /// Over stdio, what the host may do: `read` lists, reads, and waits
    /// for sessions and refuses every other tool; `write`, the default,
    /// also starts, prompts, steers, and cancels them. With `--http` each
    /// token carries its own scope instead.
    #[arg(long, value_enum, conflicts_with = "http")]
    pub scope: Option<McpTokenScope>,
    /// The name this machine goes by: what webhook news says it is from,
    /// and what `server` names it when the server has remotes. Defaults to
    /// the host name.
    #[arg(long, value_name = "NAME")]
    pub name: Option<String>,
    /// With `--http`, how many sessions each token may watch at once,
    /// stalled watches included. Defaults to 5 times --max-sessions (50
    /// by default). `rho mcp webhook list` shows each token's count.
    #[arg(long, value_name = "N", requires = "http")]
    pub max_watches: Option<u32>,
    /// Internal: the listening socket a server that upgraded in place
    /// handed this one.
    #[arg(long, value_name = "FD", requires = "http", hide = true)]
    pub listener_fd: Option<i32>,
}

#[derive(Subcommand, Clone, Debug)]
pub enum McpTokenCommand {
    /// Create token NAME, or give it a new secret, and print the secret
    /// once. The old secret stops working at once.
    Rotate {
        /// The token's name, which refusals and `list` show.
        #[arg(value_name = "NAME")]
        name: String,
        /// What the token may do: `read` lists, reads, and waits for
        /// sessions; `write` also starts, prompts, steers, and cancels
        /// them. A new token defaults to `read`; rotating keeps the
        /// token's scope unless given.
        #[arg(long, value_enum)]
        scope: Option<McpTokenScope>,
        /// A directory whose sessions, and those of everything under it,
        /// the token may reach. May be repeated; a new token needs at least
        /// one, and rotating keeps the token's list unless given.
        #[arg(long, value_name = "DIR")]
        workspace: Vec<PathBuf>,
    },
    /// List the tokens: their names, scopes, and workspaces.
    List {
        /// Print one JSON document instead of text rows.
        #[arg(long)]
        json: bool,
    },
    /// Delete token NAME; requests with it are refused at once.
    Revoke {
        #[arg(value_name = "NAME")]
        name: String,
    },
}

#[derive(Subcommand, Clone, Debug)]
pub enum McpWebhookCommand {
    /// Create webhook NAME, or replace it, reading its bearer secret from
    /// stdin: `printf %s "$KEY" | rho mcp webhook add NAME --url URL
    /// --token TOKEN`.
    Add {
        /// The webhook's name, which `watch` and `notify` take.
        #[arg(value_name = "NAME")]
        name: String,
        /// Where to POST: an https URL, or http to a loopback host.
        #[arg(long, value_name = "URL")]
        url: String,
        /// A token whose watches may use the webhook. May be repeated; at
        /// least one.
        #[arg(long, value_name = "TOKEN", required = true)]
        token: Vec<String>,
    },
    /// List the webhooks: their names, URLs, tokens, last delivery, and
    /// stalled watches. Never their secrets.
    List {
        /// Print one JSON document instead of text rows.
        #[arg(long)]
        json: bool,
    },
    /// Delete webhook NAME; watches that use it are dropped before their
    /// next POST.
    Remove {
        #[arg(value_name = "NAME")]
        name: String,
    },
}

#[derive(Subcommand, Clone, Debug)]
pub enum McpRemoteCommand {
    /// Add remote NAME, or replace it, reading the secret of the token it
    /// issued this machine from stdin, and check that it answers:
    /// `ssh NAME '~/.local/bin/rho mcp token rotate hub --scope write
    /// --workspace DIR' | rho mcp remote add NAME --url URL`, with the full
    /// path of `rho` on NAME, which a non-interactive SSH shell may not
    /// have on its PATH.
    Add {
        /// The remote's name, which `server` takes and webhook news names.
        #[arg(value_name = "NAME")]
        name: String,
        /// The remote's MCP endpoint, such as
        /// http://100.92.10.4:8765/mcp: https, or http to a loopback or
        /// private network address.
        #[arg(long, value_name = "URL")]
        url: String,
    },
    /// List the remotes: their names and URLs. Never their secrets.
    List {
        /// Print one JSON document instead of text rows.
        #[arg(long)]
        json: bool,
    },
    /// Delete remote NAME; watches of its sessions are dropped before
    /// their next POST.
    Remove {
        #[arg(value_name = "NAME")]
        name: String,
    },
}

/// What a caller of the MCP server may do: an HTTP token, or the host of a
/// stdio server.
#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
pub enum McpTokenScope {
    Read,
    Write,
}

/// Target scope for plugin install and link.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, ValueEnum)]
pub enum PluginsScope {
    /// User root: `~/.agents/plugins`.
    #[default]
    User,
    /// Project root: `<repository>/.agents/plugins`.
    Project,
}

#[derive(Subcommand, Clone, Debug)]
pub enum PluginsCommand {
    /// List discovered Agent Plugin packages.
    List {
        /// Print one JSON document instead of text rows.
        #[arg(long)]
        json: bool,
    },
    /// Inspect one plugin by package name without executing package code.
    Inspect {
        /// Plugin package name from `plugin.json`.
        #[arg(value_name = "NAME")]
        name: String,
        /// Print one JSON document instead of text.
        #[arg(long)]
        json: bool,
    },
    /// Copy a plugin package from a local path or git repository into a managed plugins root.
    Install {
        /// Local directory with `plugin.json`, a GitHub link
        /// (`https://github.com/<owner>/<repo>[/tree/<ref>/<path>]`), or a git URL.
        #[arg(value_name = "SOURCE")]
        source: std::ffi::OsString,
        /// Install under the user or project plugins root.
        #[arg(long, value_enum, default_value_t = PluginsScope::User)]
        scope: PluginsScope,
        /// Replace an existing package at the destination.
        #[arg(long)]
        force: bool,
    },
    /// Symlink a local plugin package into a managed plugins root.
    Link {
        /// Path to a directory that contains `plugin.json`.
        #[arg(value_name = "PATH")]
        path: PathBuf,
        /// Link under the user or project plugins root.
        #[arg(long, value_enum, default_value_t = PluginsScope::User)]
        scope: PluginsScope,
        /// Replace an existing package at the destination.
        #[arg(long)]
        force: bool,
    },
    /// Refetch git-installed plugins and replace them when their ref moved.
    Update {
        /// Plugin package name; omit to update every git-installed plugin.
        #[arg(value_name = "NAME")]
        name: Option<String>,
    },
    /// Enable a discovered plugin for new sessions.
    Enable {
        /// Plugin package name from `plugin.json`.
        #[arg(value_name = "NAME")]
        name: String,
    },
    /// Disable a discovered plugin without deleting package files.
    Disable {
        /// Plugin package name from `plugin.json`.
        #[arg(value_name = "NAME")]
        name: String,
    },
    /// Remove an installed or linked package from a managed plugins root.
    Remove {
        /// Plugin package name from `plugin.json`.
        #[arg(value_name = "NAME")]
        name: String,
        /// Skip the confirmation prompt.
        #[arg(short = 'y', long)]
        yes: bool,
    },
}

#[derive(Subcommand, Clone, Debug)]
pub enum CredentialStoreCommand {
    /// Test a credential backend by writing and deleting a temporary secret.
    Probe {
        /// Backend to test: os or file (`auto` is accepted as an alias for os).
        #[arg(
            value_name = "BACKEND",
            default_value = "os",
            value_parser = parse_credential_store_backend
        )]
        backend: CredentialStoreBackend,
    },
    /// Show the configured credential backend (unset, os, or file).
    Status,
    /// Save the credential backend used by future rho processes.
    Set {
        /// Backend to use: os or file (`auto` is accepted as an alias for os).
        #[arg(value_name = "BACKEND", value_parser = parse_credential_store_backend)]
        backend: CredentialStoreBackend,
    },
}

#[cfg(test)]
#[path = "cli_tests.rs"]
mod tests;