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