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