1use std::io::Write;
7use std::path::PathBuf;
8use std::sync::{Arc, Mutex};
9
10pub const RESEARCH_FOLD_BUDGET: usize = 180_000;
14
15#[derive(Debug, Default, Clone, Copy)]
17pub struct Progress {
18 pub turns: u32,
19 pub gate_attempts: u32,
20 pub in_gate: bool,
21 pub gate_wait_ms: u64,
22 pub usage: blyte_provider::Usage,
23}
24
25#[derive(Debug, Clone)]
27pub struct TaskConfig {
28 pub prompt: String,
30 pub gate: Option<String>,
32 pub context_strategy: String,
33 pub model: Option<String>,
35 pub container: Option<String>,
37 pub max_turns: usize,
39 pub max_gates: usize,
41 pub rollback: bool,
43 pub root: PathBuf,
45 pub container_workdir: String,
47 pub max_seconds: Option<u64>,
49 pub max_cost_usd: Option<f64>,
51 pub report: Option<PathBuf>,
53 pub fold_budget: Option<usize>,
55 pub sandbox: String,
57 pub network: String,
59 pub allow_read: Vec<PathBuf>,
61 pub pass_env: Vec<String>,
63 pub research: bool,
65 pub claim_check: bool,
67 pub base_check: bool,
69 pub orchestrate: bool,
71 pub dispatch_cmd: Option<String>,
73}
74
75impl From<&crate::cli::Cli> for TaskConfig {
76 fn from(cli: &crate::cli::Cli) -> Self {
78 blyte_agent::tools::set_read_roots(cli.read_roots.clone());
79 let root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
81
82 Self {
83 prompt: cli.prompt.clone().unwrap_or_default(),
84 gate: cli.gate.clone(),
85 context_strategy: cli.context.clone(),
86 model: cli.model.clone(),
87 container: cli.container.clone(),
88 max_turns: cli.max_turns,
89 max_gates: cli.max_gates,
90 rollback: cli.rollback,
91 root,
92 container_workdir: cli.container_workdir.clone(),
93 max_seconds: cli.max_seconds,
94 max_cost_usd: cli.max_cost_usd,
95 report: cli.report.clone(),
96 fold_budget: cli.fold_budget,
97 sandbox: if cli.orchestrate {
98 "off".into()
99 } else {
100 cli.sandbox.clone()
101 },
102 network: cli.network.clone(),
103 allow_read: cli.allow_read.clone(),
104 pass_env: cli.pass_env.clone(),
105 research: cli.research,
106 claim_check: cli.claim_check,
107 base_check: cli.base_check,
108 orchestrate: cli.orchestrate,
109 dispatch_cmd: cli.dispatch_cmd.clone(),
110 }
111 }
112}
113
114pub fn check_network_mode(config: &TaskConfig) -> Result<(), String> {
119 if config.network == "off" {
120 if config.container.is_some() {
121 return Err(
122 "--network=off is not supported with --container; set the container's network instead"
123 .into(),
124 );
125 }
126 if config.sandbox != "on" {
127 return Err("--network=off needs the sandbox".into());
128 }
129 #[cfg(target_os = "linux")]
130 if blyte_agent::sandbox::landlock_abi() < 4 {
131 return Err("--network=off on Linux needs Linux 6.7 or later".into());
132 }
133 if !blyte_agent::sandbox::available() {
134 return Err("--network=off needs the sandbox, but the sandbox is unavailable".into());
135 }
136 }
137 Ok(())
138}
139
140pub fn run_task(
154 config: TaskConfig,
155) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
156 let started = std::time::Instant::now();
157 let progress = Arc::new(Mutex::new(Progress::default()));
158 if let Some(s) = config.max_seconds {
159 let grace_secs: u64 = std::env::var("BLYTE_WATCHDOG_GRACE_SECS")
161 .ok()
162 .and_then(|v| v.trim().parse().ok())
163 .unwrap_or(30);
164 let watchdog_config = config.clone();
165 let watchdog_progress = Arc::clone(&progress);
166 std::thread::spawn(move || {
167 loop {
168 let wait_ms = match watchdog_progress.lock() {
169 Ok(g) => g.gate_wait_ms,
170 Err(e) => e.into_inner().gate_wait_ms,
171 };
172 let deadline = started
173 + std::time::Duration::from_secs(s.saturating_add(grace_secs))
174 + std::time::Duration::from_millis(wait_ms);
175 match deadline.checked_duration_since(std::time::Instant::now()) {
176 Some(remaining) if !remaining.is_zero() => {
177 std::thread::sleep(remaining.min(std::time::Duration::from_millis(500)));
178 }
179 _ => break,
180 }
181 }
182 let p = match watchdog_progress.lock() {
183 Ok(g) => *g,
184 Err(e) => *e.into_inner(),
185 };
186 let msg = if p.in_gate {
187 format!(
188 "stopped {grace_secs} s past --max-seconds {s}: gate attempt {} was still running",
189 p.gate_attempts
190 )
191 } else {
192 format!(
193 "stopped {grace_secs} s past --max-seconds {s} during turn {}: a model call or command never returned",
194 p.turns
195 )
196 };
197 if let Some(path) = &watchdog_config.report {
198 let mut record =
199 crate::report::RunRecord::from_error(&watchdog_config, &msg, started.elapsed());
200 record.turns = p.turns;
201 record.gate_attempts = p.gate_attempts;
202 record.usage = crate::report::UsageRecord {
203 input: p.usage.input,
204 cached: p.usage.cached,
205 output: p.usage.output,
206 thinking: p.usage.thinking,
207 };
208 let model_id = blyte_provider::resolve_provider(watchdog_config.model.as_deref())
209 .map(|pr| pr.model_id())
210 .ok()
211 .or_else(|| watchdog_config.model.clone())
212 .unwrap_or_default();
213 record.cost_usd = blyte_provider::pricing(&model_id).map(|pr| pr.cost(&p.usage));
214 let _ = crate::report::write(path, &record);
215 }
216 eprintln!("blyte: {msg}");
217 std::process::exit(1);
218 });
219 }
220 let verification_cmd = config.gate.as_deref().unwrap_or("");
221 let mut state = blyte_agent::state::State::new(&config.prompt, verification_cmd);
222 state.orchestrator.max_cost_usd = config.max_cost_usd;
223 let mut stdout = std::io::stdout();
224 let result =
225 run_task_with_state_writer_and_progress(&config, &mut state, &mut stdout, progress);
226 if let (Err(e), Some(path)) = (&result, &config.report) {
229 crate::report::write(
230 path,
231 &crate::report::RunRecord::from_error(&config, e, started.elapsed()),
232 )?;
233 }
234 result
235}
236
237pub fn run_task_with_state_and_writer<W: Write>(
251 config: &TaskConfig,
252 state: &mut blyte_agent::state::State,
253 writer: &mut W,
254) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
255 let progress = Arc::new(Mutex::new(Progress::default()));
256 run_task_with_state_writer_and_progress(config, state, writer, progress)
257}
258
259pub fn run_task_with_state_and_events(
262 config: &TaskConfig,
263 state: &mut blyte_agent::state::State,
264 on_event: &(dyn Fn(&blyte_agent::run::Event<'_>) + Sync),
265) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
266 run_task_with_event_callback(config, state, &|event| on_event(event))
267}
268
269pub fn run_task_with_state_writer_and_progress<W: Write>(
272 config: &TaskConfig,
273 state: &mut blyte_agent::state::State,
274 writer: &mut W,
275 progress: Arc<Mutex<Progress>>,
276) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
277 let writer_mutex = Mutex::new(writer);
278 let on_event = |event: &blyte_agent::run::Event<'_>| {
279 {
280 let mut p = match progress.lock() {
281 Ok(g) => g,
282 Err(e) => e.into_inner(),
283 };
284 match event {
285 blyte_agent::run::Event::Turn { n, usage, .. } => {
286 p.turns = *n;
287 p.usage.input += usage.input;
288 p.usage.cached += usage.cached;
289 p.usage.output += usage.output;
290 p.usage.thinking += usage.thinking;
291 p.in_gate = false;
292 }
293 blyte_agent::run::Event::GateStart { attempt } => {
294 p.gate_attempts = *attempt;
295 p.in_gate = true;
296 }
297 blyte_agent::run::Event::GateSlotWait { ms } => {
298 p.gate_wait_ms += ms;
299 }
300 blyte_agent::run::Event::Gate { .. } => {
301 p.in_gate = false;
302 }
303 _ => {}
304 }
305 }
306 let line = crate::repl::format_event(event);
307 if !line.is_empty() {
308 if let Ok(mut w) = writer_mutex.lock() {
309 let _ = writeln!(w, "{line}");
310 }
311 }
312 };
313 run_task_with_event_callback(config, state, &on_event)
314}
315
316fn build_usage_entry(
317 config: &TaskConfig,
318 model_id: &str,
319 outcome: String,
320 turns: u32,
321 usage: &blyte_provider::Usage,
322) -> crate::usage_log::Entry {
323 crate::usage_log::Entry {
324 ts: std::time::SystemTime::now()
325 .duration_since(std::time::UNIX_EPOCH)
326 .map(|d| d.as_secs())
327 .unwrap_or(0),
328 repo: crate::usage_log::repo_of(&config.root),
329 session: crate::usage_log::session_from(
330 std::env::var("BLYTE_SESSION").ok(),
331 std::env::var("CLAUDE_CODE_SESSION_ID").ok(),
332 ),
333 dispatch: std::env::var("BLYTE_DISPATCH_ID")
334 .ok()
335 .filter(|s| !s.is_empty()),
336 research: config.research,
337 model: model_id.to_string(),
338 outcome,
339 turns,
340 input: usage.input,
341 cached: usage.cached,
342 output: usage.output,
343 thinking: usage.thinking,
344 cost_usd: blyte_provider::pricing(model_id).map(|p| p.cost(usage)),
345 }
346}
347
348#[derive(Debug, PartialEq, Eq)]
349struct ExceededField {
350 field: &'static str,
351 written: u64,
352 total: u64,
353}
354
355fn usage_remainder(
356 total_turns: u32,
357 total_usage: &blyte_provider::Usage,
358 written_turns: u32,
359 written_usage: &blyte_provider::Usage,
360) -> Result<(u32, blyte_provider::Usage), Vec<ExceededField>> {
361 let mut exceeded = Vec::new();
362 if written_turns > total_turns {
363 exceeded.push(ExceededField {
364 field: "turns",
365 written: u64::from(written_turns),
366 total: u64::from(total_turns),
367 });
368 }
369 if written_usage.input > total_usage.input {
370 exceeded.push(ExceededField {
371 field: "input",
372 written: written_usage.input,
373 total: total_usage.input,
374 });
375 }
376 if written_usage.cached > total_usage.cached {
377 exceeded.push(ExceededField {
378 field: "cached",
379 written: written_usage.cached,
380 total: total_usage.cached,
381 });
382 }
383 if written_usage.output > total_usage.output {
384 exceeded.push(ExceededField {
385 field: "output",
386 written: written_usage.output,
387 total: total_usage.output,
388 });
389 }
390 if written_usage.thinking > total_usage.thinking {
391 exceeded.push(ExceededField {
392 field: "thinking",
393 written: written_usage.thinking,
394 total: total_usage.thinking,
395 });
396 }
397 if !exceeded.is_empty() {
398 return Err(exceeded);
399 }
400 Ok((
401 total_turns - written_turns,
402 blyte_provider::Usage {
403 input: total_usage.input - written_usage.input,
404 cached: total_usage.cached - written_usage.cached,
405 output: total_usage.output - written_usage.output,
406 thinking: total_usage.thinking - written_usage.thinking,
407 },
408 ))
409}
410
411fn run_task_with_event_callback(
412 config: &TaskConfig,
413 state: &mut blyte_agent::state::State,
414 on_event: &dyn Fn(&blyte_agent::run::Event<'_>),
415) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
416 check_network_mode(config)?;
417 let started = std::time::Instant::now();
418 if config.orchestrate {
419 if std::env::var("BLYTE_SESSION")
420 .map(|v| v.is_empty())
421 .unwrap_or(true)
422 {
423 let now_secs = std::time::SystemTime::now()
424 .duration_since(std::time::UNIX_EPOCH)
425 .map(|d| d.as_secs())
426 .unwrap_or(0);
427 let id = crate::repl::new_session_id(now_secs, std::process::id());
428 std::env::set_var("BLYTE_SESSION", &id);
429 }
430 if state.orchestrator.instructions.is_none() {
431 let lines = crate::orchestrator_text::set_state_instructions(
432 state,
433 config.dispatch_cmd.is_some(),
434 &config.root,
435 )?;
436 if state.runtime.conversation.is_none() {
437 for line in &lines {
438 eprintln!("blyte: {line}");
439 }
440 }
441 }
442 }
443 blyte_agent::tools::set_dispatch_cmd(config.dispatch_cmd.clone());
444 let provider = match blyte_provider::resolve_provider(config.model.as_deref()) {
447 Ok(p) => p,
448 Err(blyte_provider::ProviderError::MissingKey(key)) => {
449 return Err(format!(
450 "Provider error: no API key: set {key} in environment"
451 ));
452 }
453 Err(e) => return Err(format!("Provider error: {e}")),
454 };
455
456 let model_id = provider.model_id();
457 if config.max_cost_usd.is_some() && blyte_provider::pricing(&model_id).is_none() {
458 return Err(format!(
459 "--max-cost needs a known price for {model_id}; none is known"
460 ));
461 }
462 state.orchestrator.max_cost_usd = config.max_cost_usd;
463
464 let folded = blyte_agent::context::Folded {
466 budget_tokens: config.fold_budget.unwrap_or(if config.research {
468 RESEARCH_FOLD_BUDGET
469 } else {
470 blyte_agent::context::Folded::default().budget_tokens
471 }),
472 };
473 let conversational = blyte_agent::context::Conversational;
474 let context_strategy: &dyn blyte_agent::context::ContextStrategy =
475 match config.context_strategy.as_str() {
476 "conversational" => &conversational,
477 _ => &folded,
478 };
479
480 let local_fs = blyte_agent::fs::LocalFs;
484 let (persistent, session_fs, root) = match &config.container {
485 Some(cid) => (
486 blyte_agent::shell::PersistentShell::container(
487 cid.clone(),
488 PathBuf::from(&config.container_workdir),
489 ),
490 Some(blyte_agent::fs::SessionFs::container(
491 cid.clone(),
492 PathBuf::from(&config.container_workdir),
493 )),
494 PathBuf::from(&config.container_workdir),
495 ),
496 None => {
497 blyte_agent::shell::set_pass_env(config.pass_env.clone());
498 if !config.orchestrate {
499 if let Some(r) = blyte_agent::rules::load(&config.root) {
500 eprintln!("blyte: repository rules from {}", r.source.display());
501 }
502 }
503 let withheld = blyte_agent::shell::withheld_env();
504 if !withheld.is_empty() {
505 eprintln!(
506 "blyte: withholding from commands: {} (keep one with --pass-env NAME)",
507 withheld.join(", ")
508 );
509 }
510 let shell = if config.sandbox == "on" {
511 if blyte_agent::sandbox::available() {
512 let profile = blyte_agent::sandbox::default_profile_net(
513 &config.root,
514 &config.allow_read,
515 config.network == "on",
516 );
517 if matches!(profile, blyte_agent::sandbox::Profile::Landlock(_)) {
518 eprintln!(
519 "blyte: on Linux the sandbox restricts writes only; credential reads are not blocked"
520 );
521 }
522 if matches!(profile, blyte_agent::sandbox::Profile::LandlockOffline(_)) {
523 eprintln!(
524 "blyte: on Linux --network=off blocks TCP connections only (localhost included); UDP and the Docker socket are not blocked"
525 );
526 }
527 if let blyte_agent::sandbox::Profile::LandlockConfined { block_tcp, .. } =
528 &profile
529 {
530 eprintln!(
531 "blyte: on Linux, commands can read only system directories, the workspace, tool caches and --allow-read paths"
532 );
533 if *block_tcp {
534 eprintln!(
535 "blyte: on Linux --network=off blocks TCP connections only (localhost included); UDP and the Docker socket are not blocked"
536 );
537 }
538 }
539 blyte_agent::shell::PersistentShell::local_sandboxed(
540 config.root.clone(),
541 profile,
542 )
543 } else {
544 eprintln!("warning: sandbox unavailable; running unsandboxed");
545 blyte_agent::shell::PersistentShell::local(config.root.clone())
546 }
547 } else {
548 blyte_agent::shell::PersistentShell::local(config.root.clone())
549 };
550 (shell, None, config.root.clone())
551 }
552 };
553 let shell: &dyn blyte_agent::shell::Shell = &persistent;
554 let fs: &dyn blyte_agent::fs::Fs = match &session_fs {
555 Some(f) => f,
556 None => &local_fs,
557 };
558
559 let usage_path = crate::usage_log::default_path();
560 let written = Mutex::new((0u32, blyte_provider::Usage::default()));
561 let runner_on_event = |event: blyte_agent::run::Event<'_>| {
562 if let blyte_agent::run::Event::Turn { usage, .. } = &event {
563 if let Some(path) = &usage_path {
564 let entry = build_usage_entry(config, &model_id, "turn".to_string(), 1, usage);
565 match crate::usage_log::append(path, &entry) {
566 Ok(()) => {
567 let mut w = match written.lock() {
568 Ok(g) => g,
569 Err(e) => e.into_inner(),
570 };
571 w.0 += 1;
572 w.1.input += usage.input;
573 w.1.cached += usage.cached;
574 w.1.output += usage.output;
575 w.1.thinking += usage.thinking;
576 }
577 Err(err) => eprintln!("warning: usage log: {err}"),
578 }
579 }
580 }
581 on_event(&event);
582 };
583
584 let runner = blyte_agent::run::Runner {
585 provider: provider.as_ref(),
586 shell,
587 fs,
588 context: context_strategy,
589 root,
590 budget: blyte_agent::run::Budget {
591 max_turns: config.max_turns as u32,
592 max_gate_attempts: config.max_gates as u32,
593 max_duration: config.max_seconds.map(std::time::Duration::from_secs),
594 },
595 rollback: config.rollback,
596 on_event: Some(&runner_on_event),
597 research: config.research,
598 claim_check: config.claim_check,
599 base_check: config.base_check,
600 };
601
602 let (outcome, report) = runner.run(state);
603
604 if let Some(path) = &usage_path {
605 let (written_turns, written_usage) = match written.lock() {
606 Ok(g) => *g,
607 Err(e) => *e.into_inner(),
608 };
609 let (closing_turns, closing_usage) = match usage_remainder(
610 report.outcome_turns,
611 &report.usage,
612 written_turns,
613 &written_usage,
614 ) {
615 Ok(rem) => rem,
616 Err(exceeded) => {
617 for ExceededField {
618 field,
619 written,
620 total,
621 } in exceeded
622 {
623 eprintln!(
624 "error: usage log: turn lines exceed the run's total ({field}: {written} > {total})"
625 );
626 }
627 (0, blyte_provider::Usage::default())
628 }
629 };
630 let entry = build_usage_entry(
631 config,
632 &model_id,
633 format!("{outcome:?}").to_lowercase(),
634 closing_turns,
635 &closing_usage,
636 );
637 if let Err(err) = crate::usage_log::append(path, &entry) {
638 eprintln!("warning: usage log: {err}");
639 }
640 }
641
642 if let Some(path) = &config.report {
643 let mut record = crate::report::RunRecord::from_run(
644 config,
645 &model_id,
646 &outcome,
647 &report,
648 state,
649 started.elapsed(),
650 );
651 record.effort = provider.effort();
652 crate::report::write(path, &record)?;
653 }
654 Ok((outcome, report))
655}
656
657#[cfg(test)]
658mod tests {
659 use super::*;
660
661 #[test]
662 fn usage_remainder_computes_exact_and_partial_remainders() {
663 let total = blyte_provider::Usage {
664 input: 600,
665 cached: 150,
666 output: 90,
667 thinking: 75,
668 };
669 let exact = usage_remainder(3, &total, 3, &total).unwrap();
670 assert_eq!(exact, (0, blyte_provider::Usage::default()));
671
672 let written = blyte_provider::Usage {
673 input: 500,
674 cached: 100,
675 output: 80,
676 thinking: 50,
677 };
678 let partial = usage_remainder(3, &total, 2, &written).unwrap();
679 assert_eq!(
680 partial,
681 (
682 1,
683 blyte_provider::Usage {
684 input: 100,
685 cached: 50,
686 output: 10,
687 thinking: 25,
688 }
689 )
690 );
691 }
692
693 #[test]
694 fn usage_remainder_reports_exceeding_fields() {
695 let total = blyte_provider::Usage {
696 input: 100,
697 cached: 20,
698 output: 30,
699 thinking: 10,
700 };
701 let written = blyte_provider::Usage {
702 input: 120,
703 cached: 20,
704 output: 35,
705 thinking: 10,
706 };
707 let err = usage_remainder(2, &total, 3, &written).unwrap_err();
708 assert_eq!(
709 err,
710 vec![
711 ExceededField {
712 field: "turns",
713 written: 3,
714 total: 2,
715 },
716 ExceededField {
717 field: "input",
718 written: 120,
719 total: 100,
720 },
721 ExceededField {
722 field: "output",
723 written: 35,
724 total: 30,
725 },
726 ]
727 );
728 }
729}