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