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