Skip to main content

blyte_cli/
cli.rs

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