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