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