Skip to main content

blyte_cli/
cli.rs

1use clap::Parser;
2use serde::{Deserialize, Serialize};
3use std::path::PathBuf;
4
5#[derive(clap::Subcommand, Debug, PartialEq, Clone)]
6#[allow(clippy::large_enum_variant)]
7pub enum Command {
8    /// Detect this repository's checks and write blyte.toml
9    Init(InitArgs),
10    /// Serve a local dashboard of running and recent jobs
11    Dashboard(DashboardArgs),
12    /// Combine a request's passed runs on a work branch and run the repository's check
13    Combine(CombineArgs),
14    /// Run one task in its own git worktree (.wt/<id>, branch wip/<id>) and print a JSON summary
15    Dispatch(DispatchArgs),
16    /// Start a direct edit in its own git worktree (.wt/<id>, branch wip/<id>)
17    #[command(hide = true)]
18    EditStart(EditStartArgs),
19    /// Verify and record a direct edit started with `blyte edit-start`
20    #[command(hide = true)]
21    EditFinish(EditFinishArgs),
22    /// Show what a dispatched run did: commits, files, tree state, report, and optionally the diff
23    Review(ReviewArgs),
24    /// Remove finished worktrees and merged branches
25    Clean(CleanArgs),
26    /// Show what a dispatch is doing
27    Status {
28        id: String,
29        #[arg(long)]
30        json: bool,
31    },
32    /// Wait until dispatched runs finish (all of them, or the first with --any) and print one line per finished run
33    Wait {
34        /// Run ids, as given to `blyte dispatch`
35        #[arg(required = true, num_args = 1..)]
36        ids: Vec<String>,
37        /// Return as soon as at least one run has finished
38        #[arg(long)]
39        any: bool,
40        /// Give up after this many seconds (exit 2); stays under the 300 s shell-command limit
41        #[arg(long, default_value_t = 280)]
42        timeout: u64,
43    },
44    /// Install or print the Claude Code skill for the plan, delegate, review workflow
45    Skill(SkillArgs),
46    /// Replace this binary with the latest release (the old one is kept as blyte.prev)
47    Update {
48        /// Only show the installed and latest versions
49        #[arg(long, conflicts_with = "rollback")]
50        check: bool,
51        /// Swap back to the previous build (blyte.prev)
52        #[arg(long)]
53        rollback: bool,
54    },
55    /// Show conversation model and implementer costs
56    Cost(CostArgs),
57    /// Print Claude Code's status line with blyte costs
58    Statusline(StatuslineArgs),
59    /// List a plan's tasks with their state and the command to dispatch each ready one
60    Plan(PlanArgs),
61    /// List the surfaces running on this machine
62    Surfaces {
63        #[arg(long)]
64        json: bool,
65        /// List the stopped surfaces of the current folder
66        #[arg(long)]
67        stopped: bool,
68    },
69    /// Open a running surface's page by name
70    Open {
71        name: String,
72        /// Open the surface in an app window (`app`, default) or the default browser (`browser`)
73        #[arg(long = "open-in", value_name = "app|browser")]
74        open_in: Option<String>,
75    },
76    /// Reload a running surface onto the installed blyte binary
77    Reload(ReloadArgs),
78    /// Send a message to a running surface
79    Tell {
80        name: String,
81        message: String,
82        #[arg(long, default_value = "terminal", value_name = "LABEL", value_parser = parse_from_label)]
83        from: String,
84    },
85    /// Fail when the working tree adds comments since a base commit
86    #[command(hide = true)]
87    Comments(CommentsArgs),
88    /// Print the instructions the conversation model is given
89    #[command(hide = true)]
90    Instructions(InstructionsArgs),
91    /// Restore a folder to its state before an in-place run
92    Undo(UndoArgs),
93}
94
95#[derive(clap::Args, Debug, PartialEq, Clone)]
96pub struct UndoArgs {
97    /// Run id to undo
98    pub id: String,
99}
100
101#[derive(clap::Args, Debug, PartialEq, Clone)]
102pub struct ReloadArgs {
103    /// Surface name or id (defaults to the current folder's running surface)
104    #[arg(value_name = "NAME", conflicts_with = "all")]
105    pub target: Option<String>,
106
107    /// Reload every running surface
108    #[arg(long)]
109    pub all: bool,
110}
111
112#[derive(clap::Args, Debug, PartialEq, Clone)]
113pub struct InitArgs {
114    /// Overwrite an existing blyte.toml
115    #[arg(long)]
116    pub force: bool,
117
118    /// Print the file instead of writing it
119    #[arg(long)]
120    pub print: bool,
121
122    /// Skip gate verification on HEAD
123    #[arg(long)]
124    pub no_verify: bool,
125
126    /// Sandbox local command execution: 'on' or 'off' (default 'on')
127    #[arg(
128        long,
129        default_value = "on",
130        value_parser = ["on", "off"]
131    )]
132    pub sandbox: String,
133
134    /// Timeout in seconds for each verification step (default 600)
135    #[arg(long, default_value = "600", value_name = "SECONDS")]
136    pub step_timeout: u64,
137}
138
139#[derive(clap::Args, Debug, PartialEq, Clone)]
140pub struct DashboardArgs {
141    /// Port to listen on (0 for a free port)
142    #[arg(long, default_value = "7171", value_name = "N")]
143    pub port: u16,
144
145    /// Directory holding repositories or worktrees (repeatable)
146    #[arg(long = "root", value_name = "DIR")]
147    pub roots: Vec<PathBuf>,
148
149    /// Directory holding run logs and reports (repeatable)
150    #[arg(long = "runs-dir", value_name = "DIR")]
151    pub runs_dirs: Vec<PathBuf>,
152
153    /// How far back finished jobs are listed, in hours
154    #[arg(long, default_value = "24", value_name = "N")]
155    pub hours: u64,
156
157    /// Open the dashboard in the default browser
158    #[arg(long)]
159    pub open: bool,
160}
161
162#[derive(Debug, PartialEq, Clone)]
163pub struct SurfaceArgs {
164    pub port: u16,
165    pub no_open: bool,
166    pub open_in: crate::open_window::OpenIn,
167    pub days: u64,
168    pub name: Option<String>,
169    pub resume: Option<String>,
170}
171
172impl Default for SurfaceArgs {
173    fn default() -> Self {
174        Self {
175            port: 0,
176            no_open: false,
177            open_in: crate::open_window::OpenIn::App,
178            days: 14,
179            name: None,
180            resume: None,
181        }
182    }
183}
184
185#[derive(clap::Args, Debug, PartialEq, Clone)]
186pub struct CombineArgs {
187    /// Request identifier whose passed runs should be combined
188    pub request: String,
189}
190
191#[derive(clap::Args, Debug, PartialEq, Clone)]
192pub struct EditStartArgs {
193    /// Identifier for this direct edit (used for worktree and branch wip/<id>)
194    pub id: String,
195
196    /// Short description of the requested change
197    #[arg(long, value_name = "TEXT")]
198    pub task: String,
199
200    /// The commit the new worktree starts from
201    #[arg(long, default_value = "HEAD")]
202    pub base: String,
203}
204
205#[derive(clap::Args, Debug, PartialEq, Clone)]
206pub struct EditFinishArgs {
207    /// Identifier given to `blyte edit-start`
208    pub id: String,
209
210    /// Request identifier this edit belongs to
211    #[arg(long, value_name = "ID")]
212    pub request: Option<String>,
213
214    /// Surface identifier that started this edit
215    #[arg(long, value_name = "ID")]
216    pub surface: Option<String>,
217
218    #[arg(long, hide = true, value_name = "NAME")]
219    pub started_by: Option<String>,
220
221    /// Commit message used to commit uncommitted or untracked changes in the worktree
222    #[arg(long, value_name = "TEXT")]
223    pub message: Option<String>,
224}
225
226#[derive(clap::Args, Debug, PartialEq, Clone)]
227pub struct DispatchArgs {
228    /// Identifier for this dispatch (used for worktree and branch wip/<id>)
229    pub id: String,
230
231    /// Path to the task description markdown file; optional with --plan and --plan-task, which take the task from the plan
232    pub task_file: Option<PathBuf>,
233
234    /// The check command; several lines are several steps, all of which must pass
235    #[arg(short, long)]
236    pub gate: Option<String>,
237
238    /// Tag for this dispatch (repeatable)
239    #[arg(long = "tag", value_name = "TEXT")]
240    pub tags: Vec<String>,
241
242    /// Path to the plan file this dispatch belongs to
243    #[arg(long, value_name = "PATH")]
244    pub plan: Option<String>,
245
246    /// Plan task this dispatch implements
247    #[arg(long, value_name = "TEXT")]
248    pub plan_task: Option<String>,
249
250    /// Request identifier this dispatch belongs to
251    #[arg(long, value_name = "ID")]
252    pub request: Option<String>,
253
254    /// Surface identifier that started this dispatch
255    #[arg(long, value_name = "ID")]
256    pub surface: Option<String>,
257
258    #[arg(long, hide = true, value_name = "NAME")]
259    pub started_by: Option<String>,
260
261    /// The commit a new worktree starts from
262    #[arg(long, default_value = "HEAD")]
263    pub base: String,
264
265    /// Run read-only research: scratch repository, report gate, findings in report.md
266    #[arg(long, conflicts_with = "gate", conflicts_with = "base")]
267    pub research: bool,
268
269    /// Copy the finished research report to this path (only with --research)
270    #[arg(long = "report-to", requires = "research", value_name = "PATH")]
271    pub report_to: Option<PathBuf>,
272
273    /// Model identifier or provider selection
274    #[arg(short, long)]
275    pub model: Option<String>,
276
277    /// Wall-clock budget in seconds (default 3600)
278    #[arg(long)]
279    pub max_seconds: Option<u64>,
280
281    /// Maximum turn budget (default 300)
282    #[arg(long)]
283    pub max_turns: Option<u32>,
284
285    /// Maximum spend in USD (default 25)
286    #[arg(long = "max-cost")]
287    pub max_cost_usd: Option<f64>,
288
289    /// Approximate token budget for the verbatim tail before folding
290    #[arg(long)]
291    pub fold_budget: Option<usize>,
292
293    /// Sandbox local command execution: 'on' or 'off' (default 'on')
294    #[arg(
295        long,
296        default_value = "on",
297        value_parser = ["on", "off"]
298    )]
299    pub sandbox: String,
300
301    /// Outbound network mode: 'on' or 'off' (default 'on')
302    #[arg(
303        long,
304        value_parser = ["on", "off"]
305    )]
306    pub network: Option<String>,
307
308    /// Let sandboxed commands read this path despite credential deny-list (repeatable)
309    #[arg(long = "allow-read")]
310    pub allow_read: Vec<PathBuf>,
311
312    /// Start even if the task names paths outside the workspace and --allow-read
313    #[arg(long = "no-path-check")]
314    pub no_path_check: bool,
315
316    /// Research runs: no warning for missing brief sections, and allow a question that names an unverified report
317    #[arg(long = "no-brief-check")]
318    pub no_brief_check: bool,
319
320    /// Skip the model claim check on report.md for research runs
321    #[arg(long = "no-claim-check")]
322    pub no_claim_check: bool,
323
324    /// Skip the pre-run gate check on the untouched worktree
325    #[arg(long = "no-base-check")]
326    pub no_base_check: bool,
327
328    /// Pass this environment variable to commands (repeatable)
329    #[arg(long = "pass-env")]
330    pub pass_env: Vec<String>,
331}
332
333#[derive(clap::ValueEnum, Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
334#[value(rename_all = "lowercase")]
335#[serde(rename_all = "lowercase")]
336pub enum ReviewVerdict {
337    Accepted,
338    Fixed,
339    Redone,
340}
341
342impl ReviewVerdict {
343    pub fn as_str(&self) -> &'static str {
344        match self {
345            Self::Accepted => "accepted",
346            Self::Fixed => "fixed",
347            Self::Redone => "redone",
348        }
349    }
350}
351
352impl std::fmt::Display for ReviewVerdict {
353    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
354        write!(f, "{}", self.as_str())
355    }
356}
357
358#[derive(clap::Args, Debug, PartialEq, Clone)]
359pub struct ReviewArgs {
360    pub id: String,
361
362    #[arg(long)]
363    pub diff: bool,
364
365    #[arg(long, value_enum)]
366    pub verdict: Option<ReviewVerdict>,
367
368    #[arg(long, value_name = "TEXT", requires = "verdict")]
369    pub notes: Option<String>,
370
371    /// Ask the implementer model for a first review of the diff against the task (trial)
372    #[arg(long, conflicts_with = "verdict")]
373    pub model_review: bool,
374}
375
376#[derive(clap::Args, Debug, PartialEq, Clone)]
377pub struct CleanArgs {
378    /// Show what would be removed without deleting anything
379    #[arg(long)]
380    pub dry_run: bool,
381
382    /// Worktrees older than this many days are removable without a verdict (default 14)
383    #[arg(long, default_value = "14", value_name = "DAYS")]
384    pub older_than: u64,
385
386    /// Clean every repository in the registry
387    #[arg(long)]
388    pub all: bool,
389
390    #[arg(long, hide = true, conflicts_with_all = ["all", "dry_run"])]
391    pub quiet: bool,
392
393    #[arg(long, hide = true, value_name = "ID", conflicts_with_all = ["all", "dry_run"])]
394    pub skip: Option<String>,
395}
396
397#[derive(clap::Args, Debug, PartialEq, Clone)]
398pub struct CostArgs {
399    /// Session identifier to filter by (an unknown session prints zero totals and exits 0)
400    #[arg(long, value_name = "ID")]
401    pub session: Option<String>,
402
403    /// Break down totals by session id
404    #[arg(long)]
405    pub by_session: bool,
406
407    /// Filter runs at or after this Unix timestamp in seconds
408    #[arg(long, value_name = "UNIX_SECS")]
409    pub since: Option<u64>,
410
411    /// Repository path to filter by
412    #[arg(long, value_name = "PATH")]
413    pub repo: Option<PathBuf>,
414
415    /// Output totals as JSON
416    #[arg(long)]
417    pub json: bool,
418}
419
420#[derive(clap::Args, Debug, PartialEq, Clone)]
421pub struct StatuslineArgs {
422    /// Command to generate the base line before appending blyte costs (5 s timeout; override in ms with BLYTE_STATUSLINE_AFTER_TIMEOUT_MS)
423    #[arg(long, value_name = "COMMAND")]
424    pub after: Option<String>,
425}
426
427#[derive(clap::Args, Debug, PartialEq, Clone)]
428pub struct PlanArgs {
429    /// Path to the plan markdown file
430    pub plan: PathBuf,
431
432    /// Output task statuses as JSON
433    #[arg(long)]
434    pub json: bool,
435}
436
437#[derive(clap::Args, Debug, PartialEq, Clone)]
438pub struct CommentsArgs {
439    /// Base commit or revision to compare the working tree against
440    #[arg(long, value_name = "REV")]
441    pub base: String,
442}
443
444#[derive(clap::Args, Debug, PartialEq, Clone)]
445pub struct InstructionsArgs {
446    /// Print the built-in default process and exit
447    #[arg(long, conflicts_with_all = ["one_shot", "dispatch_tool"])]
448    pub default_process: bool,
449
450    /// Show the instructions for a one-shot run
451    #[arg(long)]
452    pub one_shot: bool,
453
454    /// Show the instructions for `--dispatch-cmd` mode
455    #[arg(long)]
456    pub dispatch_tool: bool,
457
458    /// Show the instructions for sandbox 'on' or 'off'
459    #[arg(long, value_parser = ["on", "off"])]
460    pub sandbox: Option<String>,
461}
462
463#[derive(clap::Subcommand, Debug, PartialEq, Clone)]
464pub enum SkillAction {
465    /// Install the Claude Code skill
466    Install {
467        /// Install to repository instead of personal ~/.claude
468        #[arg(long)]
469        project: bool,
470
471        /// Overwrite even if existing skill was modified
472        #[arg(long)]
473        force: bool,
474
475        /// Also tell Claude Code to delegate implementation to blyte by default, in CLAUDE.md
476        #[arg(long, hide = true)]
477        default: bool,
478
479        /// Install the skill without making blyte the default in CLAUDE.md
480        #[arg(long)]
481        no_default: bool,
482
483        /// Do not set Claude Code's status line
484        #[arg(long)]
485        no_statusline: bool,
486
487        /// Do not set Claude Code's auto-compact window
488        #[arg(long)]
489        no_autocompact: bool,
490
491        /// Which conversation model to set up: claude (Claude Code), codex (Codex CLI) or all
492        #[arg(
493            long,
494            default_value = "claude",
495            value_parser = ["claude", "codex", "all"]
496        )]
497        harness: String,
498
499        /// Default implementer model to write to the env file
500        #[arg(long, value_name = "ID")]
501        model: Option<String>,
502    },
503
504    /// Remove the skill and the CLAUDE.md block
505    Uninstall {
506        /// Remove from repository instead of personal ~/.claude
507        #[arg(long)]
508        project: bool,
509
510        /// Which conversation model to set up: claude (Claude Code), codex (Codex CLI) or all
511        #[arg(
512            long,
513            default_value = "claude",
514            value_parser = ["claude", "codex", "all"]
515        )]
516        harness: String,
517    },
518
519    /// Print the skill markdown to stdout
520    Print,
521}
522
523#[derive(clap::Args, Debug, PartialEq, Clone)]
524pub struct SkillArgs {
525    #[command(subcommand)]
526    pub action: SkillAction,
527}
528
529#[derive(Parser, Debug, PartialEq)]
530#[command(
531    name = "blyte",
532    version = concat!(env!("CARGO_PKG_VERSION"), " (", env!("BLYTE_BUILD"), ")"),
533    about = "A lean coding-agent harness with a sealed verification gate\nBare `blyte` starts the live surface for the current repository.",
534    subcommand_precedence_over_arg = true
535)]
536pub struct Cli {
537    #[command(subcommand)]
538    pub command: Option<Command>,
539
540    /// Direct task prompt to run in single-shot / headless mode
541    #[arg(index = 1)]
542    pub prompt: Option<String>,
543
544    /// Verification gate command (e.g. 'pytest', 'cargo test'). Several steps may be given one per line: every step runs and all failures are reported together.
545    #[arg(short, long)]
546    pub gate: Option<String>,
547
548    /// Run blyte as the conversation model: plan, dispatch implementers with `blyte dispatch`, review and merge
549    #[arg(long, conflicts_with = "gate")]
550    pub converse: bool,
551
552    /// Command to run on the host when the conversation model delegates work via the `dispatch` tool
553    #[arg(long, requires = "converse")]
554    pub dispatch_cmd: Option<String>,
555
556    /// Context strategy: 'conversational' (append-all chat) or 'folded' (append-only chat, oldest half folded into digests past a budget)
557    #[arg(
558        long,
559        default_value = "folded",
560        value_parser = ["conversational", "folded"]
561    )]
562    pub context: String,
563
564    /// Model identifier or provider selection
565    #[arg(short, long)]
566    pub model: Option<String>,
567
568    /// Run inside an isolated container workspace instead of local host
569    #[arg(long)]
570    pub container: Option<String>,
571
572    /// Maximum turn budget
573    #[arg(long, default_value = "25")]
574    pub max_turns: usize,
575
576    /// Maximum verification gate attempts before failing
577    #[arg(long, default_value = "5")]
578    pub max_gates: usize,
579
580    /// Enable automatic rollback to baseline git commit if gate fails (disable with --rollback=false)
581    #[arg(
582        long,
583        default_value_t = true,
584        action = clap::ArgAction::Set,
585        num_args = 0..=1,
586        require_equals = true,
587        default_missing_value = "true",
588        value_parser = clap::builder::BoolishValueParser::new()
589    )]
590    pub rollback: bool,
591
592    /// Working directory inside the container when --container is set
593    #[arg(long, default_value = "/workspace")]
594    pub container_workdir: String,
595
596    /// Wall-clock budget in seconds; the run stops itself and reports when it is spent
597    #[arg(long)]
598    pub max_seconds: Option<u64>,
599
600    /// Maximum spend in USD; the run stops before a model call once reached
601    #[arg(long = "max-cost")]
602    pub max_cost_usd: Option<f64>,
603
604    /// Write a JSON run report to this path when the headless run exits
605    #[arg(long)]
606    pub report: Option<PathBuf>,
607
608    /// Approximate token budget for the verbatim tail before folding (folded context; default 48000)
609    #[arg(long)]
610    pub fold_budget: Option<usize>,
611
612    /// Sandbox the commands blyte runs on this machine (macOS Seatbelt, Linux Landlock): 'on' or 'off'
613    #[arg(
614        long,
615        default_value = "on",
616        value_parser = ["on", "off"]
617    )]
618    pub sandbox: String,
619
620    /// Let commands blyte runs connect out: 'on' or 'off' (default 'on', or 'off' under --converse). 'off' needs the sandbox
621    #[arg(
622        long,
623        value_parser = ["on", "off"]
624    )]
625    pub network: Option<String>,
626
627    /// Let sandboxed commands read this path despite the credential deny-list (repeatable)
628    #[arg(long = "allow-read")]
629    pub allow_read: Vec<PathBuf>,
630
631    /// Pass this environment variable to commands even though it looks like a credential (repeatable)
632    #[arg(long = "pass-env")]
633    pub pass_env: Vec<String>,
634
635    /// Directory allowed for reading with the read and grep tools (repeatable)
636    #[arg(long = "read-root", value_name = "DIR")]
637    pub read_roots: Vec<PathBuf>,
638
639    /// Gates in this run do not take a machine-wide slot
640    #[arg(long)]
641    pub no_gate_slot: bool,
642
643    #[arg(
644        long = "snapshot-dir",
645        hide = true,
646        value_name = "DIR",
647        requires = "snapshot_manifest",
648        conflicts_with_all = ["container", "converse"]
649    )]
650    pub snapshot_dir: Option<PathBuf>,
651
652    #[arg(
653        long = "snapshot-manifest",
654        hide = true,
655        value_name = "FILE",
656        requires = "snapshot_dir",
657        conflicts_with_all = ["container", "converse"]
658    )]
659    pub snapshot_manifest: Option<PathBuf>,
660
661    /// Whether this is a research run: periodically remind the model to keep report.md updated
662    #[arg(long)]
663    pub research: bool,
664
665    /// Research run: check report.md's claims against their cited lines
666    #[arg(long = "claim-check")]
667    pub claim_check: bool,
668
669    /// Run the verification gate once before the first model call and stop as blocked if it fails
670    #[arg(long = "base-check")]
671    pub base_check: bool,
672
673    /// Directory containing an untouched checkout of the base commit for running the base check beside the model's first turns
674    #[arg(long = "base-check-dir", value_name = "DIR")]
675    pub base_check_dir: Option<PathBuf>,
676
677    #[arg(
678        long,
679        help = "Run the surface in the terminal instead of opening the page"
680    )]
681    pub terminal: bool,
682
683    #[arg(
684        long,
685        value_name = "N",
686        help = "Port to listen on (default: a free port)"
687    )]
688    pub port: Option<u16>,
689
690    #[arg(long = "no-open", help = "Do not open the live surface in the browser")]
691    pub no_open: bool,
692
693    #[arg(
694        long = "open-in",
695        value_name = "app|browser",
696        help = "Open the live surface in an app window (`app`, default) or the default browser (`browser`)"
697    )]
698    pub open_in: Option<String>,
699
700    #[arg(
701        long,
702        value_name = "N",
703        value_parser = clap::value_parser!(u64).range(1..=31),
704        help = "How many days back to include finished runs in the live surface (1 to 31, default 14)"
705    )]
706    pub days: Option<u64>,
707
708    #[arg(
709        long,
710        value_name = "NAME",
711        help = "Name for this surface (default: the repository directory name)"
712    )]
713    pub name: Option<String>,
714
715    #[arg(
716        long,
717        value_name = "NAME",
718        conflicts_with = "name",
719        help = "Restart a stopped surface, by name or id, with its transcript"
720    )]
721    pub resume: Option<String>,
722}
723
724fn parse_from_label(raw: &str) -> Result<String, String> {
725    crate::surface_dir::validate_surface_name(raw)?;
726    Ok(raw.to_string())
727}
728
729/// Turn and context defaults for `--converse`. A flag the user gave explicitly wins.
730pub fn apply_converse_defaults(cli: &mut Cli, matches: &clap::ArgMatches) {
731    if !cli.converse {
732        return;
733    }
734    if matches.value_source("max_turns") == Some(clap::parser::ValueSource::DefaultValue) {
735        cli.max_turns = 1000;
736    }
737    if cli.fold_budget.is_none() {
738        cli.fold_budget = Some(100_000);
739    }
740}