1use std::io::Write;
7use std::path::{Path, PathBuf};
8use std::sync::{Arc, Condvar, 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 base_check_dir: Option<PathBuf>,
71 pub converse: bool,
73 pub dispatch_cmd: Option<String>,
75}
76
77impl From<&crate::cli::Cli> for TaskConfig {
78 fn from(cli: &crate::cli::Cli) -> Self {
80 blyte_agent::tools::set_read_roots(cli.read_roots.clone());
81 let root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
83
84 let network = match &cli.network {
85 Some(v) => v.clone(),
86 None if cli.converse && cli.sandbox == "on" && cli.container.is_none() => "off".into(),
87 None => "on".into(),
88 };
89
90 Self {
91 prompt: cli.prompt.clone().unwrap_or_default(),
92 gate: cli.gate.clone(),
93 context_strategy: cli.context.clone(),
94 model: cli.model.clone(),
95 container: cli.container.clone(),
96 max_turns: cli.max_turns,
97 max_gates: cli.max_gates,
98 rollback: cli.rollback,
99 root,
100 container_workdir: cli.container_workdir.clone(),
101 max_seconds: cli.max_seconds,
102 max_cost_usd: cli.max_cost_usd,
103 report: cli.report.clone(),
104 fold_budget: cli.fold_budget,
105 sandbox: cli.sandbox.clone(),
106 network,
107 allow_read: cli.allow_read.clone(),
108 pass_env: cli.pass_env.clone(),
109 research: cli.research,
110 claim_check: cli.claim_check,
111 base_check: cli.base_check,
112 base_check_dir: cli.base_check_dir.clone(),
113 converse: cli.converse,
114 dispatch_cmd: cli.dispatch_cmd.clone(),
115 }
116 }
117}
118
119pub fn build_sandbox_profile(config: &TaskConfig) -> blyte_agent::sandbox::Profile {
120 build_sandbox_profile_for_root(config, &config.root)
121}
122
123fn build_sandbox_profile_for_root(
124 config: &TaskConfig,
125 root: &Path,
126) -> blyte_agent::sandbox::Profile {
127 if config.converse {
128 blyte_agent::sandbox::conversation_profile_net(
129 root,
130 &config.allow_read,
131 config.network == "on",
132 )
133 } else {
134 blyte_agent::sandbox::default_profile_net(root, &config.allow_read, config.network == "on")
135 }
136}
137
138pub fn configure_converse_policy(
139 converse: bool,
140 sandbox_on: bool,
141 root: &Path,
142 approver: Option<Arc<dyn blyte_agent::approval::Approver>>,
143 has_conversation: bool,
144) -> Result<usize, String> {
145 if !converse || !sandbox_on {
146 blyte_agent::tools::set_write_scope(None);
147 blyte_agent::tools::set_approval(None);
148 return Ok(0);
149 }
150 let tasks_dir = blyte_agent::sandbox::conversation_tasks_dir(root);
151 std::fs::create_dir_all(&tasks_dir)
152 .map_err(|e| format!("cannot create {}: {e}", tasks_dir.display()))?;
153 let tasks_canon = tasks_dir
154 .canonicalize()
155 .map_err(|e| format!("cannot canonicalize {}: {e}", tasks_dir.display()))?;
156 let edit_worktrees = tasks_canon
157 .parent()
158 .map(|p| {
159 p.canonicalize()
160 .map_err(|e| format!("cannot canonicalize {}: {e}", p.display()))
161 })
162 .transpose()?;
163 let mut allowed = vec![tasks_canon];
164 for dir in blyte_agent::sandbox::conversation_allowed(root) {
165 if let Ok(canon) = dir.canonicalize() {
166 if !allowed.contains(&canon) {
167 allowed.push(canon);
168 }
169 }
170 }
171 blyte_agent::tools::set_write_scope(Some(blyte_agent::tools::WriteScope {
172 allowed,
173 edit_worktrees,
174 }));
175 let rules = crate::approval_file::load()?;
176 let count = rules.len();
177 let approver: Arc<dyn blyte_agent::approval::Approver> = match approver {
178 Some(a) => a,
179 None if has_conversation => Arc::new(crate::tty_approver::TtyApprover),
180 None => Arc::new(blyte_agent::approval::NoApprover),
181 };
182 blyte_agent::tools::set_approval(Some(blyte_agent::approval::ApprovalConfig {
183 rules,
184 approver,
185 }));
186 Ok(count)
187}
188
189struct BackgroundBaseCheckData {
190 state: blyte_agent::run::BaseCheckState,
191 elapsed_seconds: Option<f64>,
192}
193
194pub struct BackgroundBaseCheck {
196 shared: Arc<(Mutex<BackgroundBaseCheckData>, Condvar)>,
197 cancel: Arc<blyte_agent::shell::CancelHandle>,
198 handle: Mutex<Option<std::thread::JoinHandle<()>>>,
199}
200
201impl BackgroundBaseCheck {
202 pub fn start(
205 config: &TaskConfig,
206 gate: String,
207 base_dir: PathBuf,
208 deadline: Option<std::time::Instant>,
209 ) -> Self {
210 let cancel = Arc::new(blyte_agent::shell::CancelHandle::new());
211 let shell: Box<dyn blyte_agent::shell::Shell + Send> = match &config.container {
212 Some(cid) => Box::new(blyte_agent::shell::CancellableContainerShell {
213 inner: blyte_agent::shell::ContainerShell {
214 container_id: cid.clone(),
215 workdir: base_dir.clone(),
216 },
217 cancel: Arc::clone(&cancel),
218 }),
219 None => {
220 let inner = if config.sandbox == "on" && blyte_agent::sandbox::available() {
221 blyte_agent::shell::LocalShell::sandboxed(build_sandbox_profile_for_root(
222 config, &base_dir,
223 ))
224 } else {
225 blyte_agent::shell::LocalShell::new()
226 };
227 Box::new(blyte_agent::shell::CancellableLocalShell {
228 inner,
229 cancel: Arc::clone(&cancel),
230 })
231 }
232 };
233 let shared = Arc::new((
234 Mutex::new(BackgroundBaseCheckData {
235 state: blyte_agent::run::BaseCheckState::Pending,
236 elapsed_seconds: None,
237 }),
238 Condvar::new(),
239 ));
240 let thread_shared = Arc::clone(&shared);
241 let thread_cancel = Arc::clone(&cancel);
242 let join = std::thread::spawn(move || {
243 let started = std::time::Instant::now();
244 let mut deadline = deadline;
245 let result = blyte_agent::run::run_gate_steps_cancellable(
246 shell.as_ref(),
247 &gate,
248 &base_dir,
249 &[],
250 &mut deadline,
251 |_| {},
252 &std::time::Instant::now,
253 Some(&thread_cancel),
254 );
255 if thread_cancel.is_cancelled() {
256 return;
257 }
258 let elapsed = started.elapsed().as_secs_f64();
259 let next_state = blyte_agent::run::base_check_state_from_gate(&result);
260 let (lock, cvar) = &*thread_shared;
261 let mut guard = match lock.lock() {
262 Ok(g) => g,
263 Err(e) => e.into_inner(),
264 };
265 guard.state = next_state;
266 guard.elapsed_seconds = Some(elapsed);
267 cvar.notify_all();
268 });
269 Self {
270 shared,
271 cancel,
272 handle: Mutex::new(Some(join)),
273 }
274 }
275}
276
277impl blyte_agent::run::BaseCheckHandle for BackgroundBaseCheck {
278 fn poll(&self) -> blyte_agent::run::BaseCheckState {
279 let (lock, _) = &*self.shared;
280 match lock.lock() {
281 Ok(g) => g.state.clone(),
282 Err(e) => e.into_inner().state.clone(),
283 }
284 }
285
286 fn wait(&self) -> blyte_agent::run::BaseCheckState {
287 let (lock, cvar) = &*self.shared;
288 let mut guard = match lock.lock() {
289 Ok(g) => g,
290 Err(e) => e.into_inner(),
291 };
292 while matches!(guard.state, blyte_agent::run::BaseCheckState::Pending) {
293 if self.cancel.is_cancelled() {
294 break;
295 }
296 guard = match cvar.wait(guard) {
297 Ok(g) => g,
298 Err(e) => e.into_inner(),
299 };
300 }
301 guard.state.clone()
302 }
303
304 fn stop(&self) {
305 self.cancel.cancel();
306 let (lock, cvar) = &*self.shared;
307 let guard = match lock.lock() {
308 Ok(g) => g,
309 Err(e) => e.into_inner(),
310 };
311 cvar.notify_all();
312 drop(guard);
313 let join = match self.handle.lock() {
314 Ok(mut g) => g.take(),
315 Err(e) => e.into_inner().take(),
316 };
317 if let Some(h) = join {
318 let _ = h.join();
319 }
320 }
321
322 fn elapsed_seconds(&self) -> Option<f64> {
323 let (lock, _) = &*self.shared;
324 match lock.lock() {
325 Ok(g) => g.elapsed_seconds,
326 Err(e) => e.into_inner().elapsed_seconds,
327 }
328 }
329}
330
331impl Drop for BackgroundBaseCheck {
332 fn drop(&mut self) {
333 blyte_agent::run::BaseCheckHandle::stop(self);
334 }
335}
336
337pub fn build_local_shell(config: &TaskConfig) -> blyte_agent::shell::PersistentShell {
338 if config.sandbox == "on" {
339 if blyte_agent::sandbox::available() {
340 let profile = build_sandbox_profile(config);
341 if matches!(profile, blyte_agent::sandbox::Profile::Landlock(_)) {
342 eprintln!(
343 "blyte: on Linux the sandbox restricts writes only; credential reads are not blocked"
344 );
345 }
346 if matches!(profile, blyte_agent::sandbox::Profile::LandlockOffline(_)) {
347 eprintln!(
348 "blyte: on Linux --network=off blocks TCP connections only (localhost included); UDP and the Docker socket are not blocked"
349 );
350 }
351 if let blyte_agent::sandbox::Profile::LandlockConfined { block_tcp, .. } = &profile {
352 eprintln!(
353 "blyte: on Linux, commands can read only system directories, the workspace, tool caches and --allow-read paths"
354 );
355 if *block_tcp {
356 eprintln!(
357 "blyte: on Linux --network=off blocks TCP connections only (localhost included); UDP and the Docker socket are not blocked"
358 );
359 }
360 }
361 let shell =
362 blyte_agent::shell::PersistentShell::local_sandboxed(config.root.clone(), profile);
363 if config.converse {
364 let root = config.root.clone();
365 let allow_read = config.allow_read.clone();
366 let network = config.network == "on";
367 shell.with_profile_builder(Arc::new(move || {
368 blyte_agent::sandbox::conversation_profile_for_open_edits(
369 &root,
370 &allow_read,
371 network,
372 )
373 }))
374 } else {
375 shell
376 }
377 } else {
378 eprintln!("warning: sandbox unavailable; running unsandboxed");
379 blyte_agent::shell::PersistentShell::local(config.root.clone())
380 }
381 } else {
382 blyte_agent::shell::PersistentShell::local(config.root.clone())
383 }
384}
385
386pub fn check_network_mode(config: &TaskConfig) -> Result<(), String> {
391 if config.network == "off" {
392 if config.container.is_some() {
393 return Err(
394 "--network=off is not supported with --container; set the container's network instead"
395 .into(),
396 );
397 }
398 if config.sandbox != "on" {
399 return Err("--network=off needs the sandbox".into());
400 }
401 #[cfg(target_os = "linux")]
402 if blyte_agent::sandbox::landlock_abi() < 4 {
403 return Err("--network=off on Linux needs Linux 6.7 or later".into());
404 }
405 if !blyte_agent::sandbox::available() {
406 return Err("--network=off needs the sandbox, but the sandbox is unavailable".into());
407 }
408 }
409 Ok(())
410}
411
412pub fn write_watchdog_report<F, W: Write>(
413 config: &TaskConfig,
414 progress: &Progress,
415 msg: &str,
416 elapsed: std::time::Duration,
417 resolve_model: F,
418 err_out: &mut W,
419) -> Result<Option<crate::report::RunRecord>, String>
420where
421 F: FnOnce(Option<&str>) -> Result<String, String>,
422{
423 let Some(path) = &config.report else {
424 return Ok(None);
425 };
426 let mut record = crate::report::RunRecord::from_error(config, msg, elapsed);
427 record.turns = progress.turns;
428 record.gate_attempts = progress.gate_attempts;
429 record.usage = crate::report::UsageRecord {
430 input: progress.usage.input,
431 cached: progress.usage.cached,
432 output: progress.usage.output,
433 thinking: progress.usage.thinking,
434 };
435 let model_id = match resolve_model(config.model.as_deref()) {
436 Ok(id) if !id.is_empty() => Some(id),
437 Ok(_) => {
438 let _ = writeln!(
439 err_out,
440 "blyte: watchdog warning: provider returned empty model id"
441 );
442 config.model.clone().filter(|m| !m.is_empty())
443 }
444 Err(err) => {
445 let _ = writeln!(
446 err_out,
447 "blyte: watchdog warning: could not resolve provider for cost lookup: {err}"
448 );
449 config.model.clone().filter(|m| !m.is_empty())
450 }
451 };
452 if let Some(id) = model_id {
453 record.cost_usd = blyte_provider::pricing(&id).map(|pr| pr.cost(&progress.usage));
454 record.model_id = Some(id);
455 }
456 crate::report::write(path, &record)?;
457 Ok(Some(record))
458}
459
460pub fn run_task(
474 config: TaskConfig,
475) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
476 let started = std::time::Instant::now();
477 let progress = Arc::new(Mutex::new(Progress::default()));
478 if let Some(s) = config.max_seconds {
479 let grace_secs: u64 = std::env::var("BLYTE_WATCHDOG_GRACE_SECS")
481 .ok()
482 .and_then(|v| v.trim().parse().ok())
483 .unwrap_or(30);
484 let watchdog_config = config.clone();
485 let watchdog_progress = Arc::clone(&progress);
486 std::thread::spawn(move || {
487 loop {
488 let wait_ms = match watchdog_progress.lock() {
489 Ok(g) => g.gate_wait_ms,
490 Err(e) => e.into_inner().gate_wait_ms,
491 };
492 let deadline = started
493 + std::time::Duration::from_secs(s.saturating_add(grace_secs))
494 + std::time::Duration::from_millis(wait_ms);
495 match deadline.checked_duration_since(std::time::Instant::now()) {
496 Some(remaining) if !remaining.is_zero() => {
497 std::thread::sleep(remaining.min(std::time::Duration::from_millis(500)));
498 }
499 _ => break,
500 }
501 }
502 let p = match watchdog_progress.lock() {
503 Ok(g) => *g,
504 Err(e) => *e.into_inner(),
505 };
506 let msg = if p.in_gate {
507 format!(
508 "stopped {grace_secs} s past --max-seconds {s}: gate attempt {} was still running",
509 p.gate_attempts
510 )
511 } else {
512 format!(
513 "stopped {grace_secs} s past --max-seconds {s} during turn {}: a model call or command never returned",
514 p.turns
515 )
516 };
517 let mut stderr = std::io::stderr();
518 if let Err(err) = write_watchdog_report(
519 &watchdog_config,
520 &p,
521 &msg,
522 started.elapsed(),
523 |m| {
524 blyte_provider::resolve_provider(m)
525 .map(|pr| pr.model_id())
526 .map_err(|e| e.to_string())
527 },
528 &mut stderr,
529 ) {
530 eprintln!("blyte: watchdog failed to write report: {err}");
531 }
532 eprintln!("blyte: {msg}");
533 std::process::exit(1);
534 });
535 }
536 let verification_cmd = config.gate.as_deref().unwrap_or("");
537 let mut state = blyte_agent::state::State::new(&config.prompt, verification_cmd);
538 state.brief.max_cost_usd = config.max_cost_usd;
539 let mut stdout = std::io::stdout();
540 let result =
541 run_task_with_state_writer_and_progress(&config, &mut state, &mut stdout, progress);
542 if let (Err(e), Some(path)) = (&result, &config.report) {
545 crate::report::write(
546 path,
547 &crate::report::RunRecord::from_error(&config, e, started.elapsed()),
548 )?;
549 }
550 result
551}
552
553pub fn run_task_with_state_and_writer<W: Write>(
567 config: &TaskConfig,
568 state: &mut blyte_agent::state::State,
569 writer: &mut W,
570) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
571 let progress = Arc::new(Mutex::new(Progress::default()));
572 run_task_with_state_writer_and_progress(config, state, writer, progress)
573}
574
575pub fn run_task_with_state_and_events(
578 config: &TaskConfig,
579 state: &mut blyte_agent::state::State,
580 on_event: &(dyn Fn(&blyte_agent::run::Event<'_>) + Sync),
581) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
582 let max_duration = config.max_seconds.map(std::time::Duration::from_secs);
583 run_task_with_event_callback(config, state, None, max_duration, &|event| on_event(event))
584}
585
586pub fn run_task_with_state_and_max_duration(
587 config: &TaskConfig,
588 state: &mut blyte_agent::state::State,
589 max_duration: Option<std::time::Duration>,
590 on_event: &(dyn Fn(&blyte_agent::run::Event<'_>) + Sync),
591) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
592 run_task_with_event_callback(config, state, None, max_duration, &|event| on_event(event))
593}
594
595pub fn run_task_with_approver(
597 config: &TaskConfig,
598 state: &mut blyte_agent::state::State,
599 approver: Option<Arc<dyn blyte_agent::approval::Approver>>,
600 on_event: &(dyn Fn(&blyte_agent::run::Event<'_>) + Sync),
601) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
602 let max_duration = config.max_seconds.map(std::time::Duration::from_secs);
603 run_task_with_event_callback(config, state, approver, max_duration, &|event| {
604 on_event(event)
605 })
606}
607
608pub fn run_task_with_state_writer_and_progress<W: Write>(
611 config: &TaskConfig,
612 state: &mut blyte_agent::state::State,
613 writer: &mut W,
614 progress: Arc<Mutex<Progress>>,
615) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
616 let writer_mutex = Mutex::new(writer);
617 let on_event = |event: &blyte_agent::run::Event<'_>| {
618 {
619 let mut p = match progress.lock() {
620 Ok(g) => g,
621 Err(e) => e.into_inner(),
622 };
623 match event {
624 blyte_agent::run::Event::Turn { n, usage, .. } => {
625 p.turns = *n;
626 p.usage.input += usage.input;
627 p.usage.cached += usage.cached;
628 p.usage.output += usage.output;
629 p.usage.thinking += usage.thinking;
630 p.in_gate = false;
631 }
632 blyte_agent::run::Event::GateStart { attempt } => {
633 p.gate_attempts = *attempt;
634 p.in_gate = true;
635 }
636 blyte_agent::run::Event::GateSlotWait { ms } => {
637 p.gate_wait_ms += ms;
638 }
639 blyte_agent::run::Event::Gate { .. } => {
640 p.in_gate = false;
641 }
642 _ => {}
643 }
644 }
645 let line = crate::repl::format_event(event);
646 if !line.is_empty() {
647 if let Ok(mut w) = writer_mutex.lock() {
648 let _ = writeln!(w, "{line}");
649 }
650 }
651 };
652 let max_duration = config.max_seconds.map(std::time::Duration::from_secs);
653 run_task_with_event_callback(config, state, None, max_duration, &on_event)
654}
655
656fn build_usage_entry(
657 config: &TaskConfig,
658 model_id: &str,
659 outcome: String,
660 turns: u32,
661 usage: &blyte_provider::Usage,
662) -> crate::usage_log::Entry {
663 crate::usage_log::Entry {
664 ts: std::time::SystemTime::now()
665 .duration_since(std::time::UNIX_EPOCH)
666 .map(|d| d.as_secs())
667 .unwrap_or(0),
668 repo: crate::usage_log::repo_of(&config.root),
669 session: crate::usage_log::session_from(
670 std::env::var("BLYTE_SESSION").ok(),
671 std::env::var("CLAUDE_CODE_SESSION_ID").ok(),
672 ),
673 dispatch: std::env::var("BLYTE_DISPATCH_ID")
674 .ok()
675 .filter(|s| !s.is_empty()),
676 research: config.research,
677 model: model_id.to_string(),
678 outcome,
679 turns,
680 input: usage.input,
681 cached: usage.cached,
682 output: usage.output,
683 thinking: usage.thinking,
684 cost_usd: blyte_provider::pricing(model_id).map(|p| p.cost(usage)),
685 }
686}
687
688#[derive(Debug, PartialEq, Eq)]
689struct ExceededField {
690 field: &'static str,
691 written: u64,
692 total: u64,
693}
694
695fn usage_remainder(
696 total_turns: u32,
697 total_usage: &blyte_provider::Usage,
698 written_turns: u32,
699 written_usage: &blyte_provider::Usage,
700) -> Result<(u32, blyte_provider::Usage), Vec<ExceededField>> {
701 let mut exceeded = Vec::new();
702 if written_turns > total_turns {
703 exceeded.push(ExceededField {
704 field: "turns",
705 written: u64::from(written_turns),
706 total: u64::from(total_turns),
707 });
708 }
709 if written_usage.input > total_usage.input {
710 exceeded.push(ExceededField {
711 field: "input",
712 written: written_usage.input,
713 total: total_usage.input,
714 });
715 }
716 if written_usage.cached > total_usage.cached {
717 exceeded.push(ExceededField {
718 field: "cached",
719 written: written_usage.cached,
720 total: total_usage.cached,
721 });
722 }
723 if written_usage.output > total_usage.output {
724 exceeded.push(ExceededField {
725 field: "output",
726 written: written_usage.output,
727 total: total_usage.output,
728 });
729 }
730 if written_usage.thinking > total_usage.thinking {
731 exceeded.push(ExceededField {
732 field: "thinking",
733 written: written_usage.thinking,
734 total: total_usage.thinking,
735 });
736 }
737 if !exceeded.is_empty() {
738 return Err(exceeded);
739 }
740 Ok((
741 total_turns - written_turns,
742 blyte_provider::Usage {
743 input: total_usage.input - written_usage.input,
744 cached: total_usage.cached - written_usage.cached,
745 output: total_usage.output - written_usage.output,
746 thinking: total_usage.thinking - written_usage.thinking,
747 },
748 ))
749}
750
751fn run_task_with_event_callback(
752 config: &TaskConfig,
753 state: &mut blyte_agent::state::State,
754 approver: Option<Arc<dyn blyte_agent::approval::Approver>>,
755 max_duration: Option<std::time::Duration>,
756 on_event: &dyn Fn(&blyte_agent::run::Event<'_>),
757) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
758 check_network_mode(config)?;
759 let started = std::time::Instant::now();
760 if config.converse {
761 if std::env::var("BLYTE_SESSION")
762 .map(|v| v.is_empty())
763 .unwrap_or(true)
764 {
765 let now_secs = std::time::SystemTime::now()
766 .duration_since(std::time::UNIX_EPOCH)
767 .map(|d| d.as_secs())
768 .unwrap_or(0);
769 let id = crate::repl::new_session_id(now_secs, std::process::id());
770 std::env::set_var("BLYTE_SESSION", &id);
771 }
772 let sandbox_on = config.sandbox == "on";
773 let allowed_count = configure_converse_policy(
774 true,
775 sandbox_on,
776 &config.root,
777 approver,
778 state.runtime.conversation.is_some(),
779 )?;
780 if state.brief.instructions.is_none() {
781 let lines = crate::conversation_text::set_state_instructions(
782 state,
783 config.dispatch_cmd.is_some(),
784 &config.root,
785 sandbox_on,
786 allowed_count,
787 )?;
788 if state.runtime.conversation.is_none() {
789 for line in &lines {
790 eprintln!("blyte: {line}");
791 }
792 }
793 }
794 let exe = std::env::current_exe()
795 .map_err(|e| format!("cannot locate blyte executable for the blyte tool: {e}"))?;
796 blyte_agent::tools::set_blyte_tool(Some(exe));
797 } else {
798 configure_converse_policy(false, false, &config.root, None, false)?;
799 blyte_agent::tools::set_blyte_tool(None);
800 }
801 blyte_agent::tools::set_dispatch_cmd(config.dispatch_cmd.clone());
802 let provider = match blyte_provider::resolve_provider(config.model.as_deref()) {
805 Ok(p) => p,
806 Err(blyte_provider::ProviderError::MissingKey(key)) => {
807 return Err(format!(
808 "Provider error: no API key: set {key} in environment"
809 ));
810 }
811 Err(e) => return Err(format!("Provider error: {e}")),
812 };
813
814 let model_id = provider.model_id();
815 if config.max_cost_usd.is_some() && blyte_provider::pricing(&model_id).is_none() {
816 return Err(format!(
817 "--max-cost needs a known price for {model_id}; none is known"
818 ));
819 }
820 state.brief.max_cost_usd = config.max_cost_usd;
821
822 let folded = blyte_agent::context::Folded {
824 budget_tokens: config.fold_budget.unwrap_or(if config.research {
826 RESEARCH_FOLD_BUDGET
827 } else {
828 blyte_agent::context::Folded::default().budget_tokens
829 }),
830 };
831 let conversational = blyte_agent::context::Conversational;
832 let context_strategy: &dyn blyte_agent::context::ContextStrategy =
833 match config.context_strategy.as_str() {
834 "conversational" => &conversational,
835 _ => &folded,
836 };
837
838 let local_fs = blyte_agent::fs::LocalFs;
842 let (persistent, session_fs, root) = match &config.container {
843 Some(cid) => (
844 blyte_agent::shell::PersistentShell::container(
845 cid.clone(),
846 PathBuf::from(&config.container_workdir),
847 ),
848 Some(blyte_agent::fs::SessionFs::container(
849 cid.clone(),
850 PathBuf::from(&config.container_workdir),
851 )),
852 PathBuf::from(&config.container_workdir),
853 ),
854 None => {
855 blyte_agent::shell::set_pass_env(config.pass_env.clone());
856 if !config.converse {
857 if let Some(r) = blyte_agent::rules::load(&config.root) {
858 eprintln!("blyte: repository rules from {}", r.source.display());
859 }
860 }
861 let withheld = blyte_agent::shell::withheld_env();
862 if !withheld.is_empty() {
863 eprintln!(
864 "blyte: withholding from commands: {} (keep one with --pass-env NAME)",
865 withheld.join(", ")
866 );
867 }
868 let shell = build_local_shell(config);
869 (shell, None, config.root.clone())
870 }
871 };
872 let shell: &dyn blyte_agent::shell::Shell = &persistent;
873 let fs: &dyn blyte_agent::fs::Fs = match &session_fs {
874 Some(f) => f,
875 None => &local_fs,
876 };
877
878 let usage_path = crate::usage_log::default_path();
879 let written = Mutex::new((0u32, blyte_provider::Usage::default()));
880 let runner_on_event = |event: blyte_agent::run::Event<'_>| {
881 if let blyte_agent::run::Event::Turn { usage, .. } = &event {
882 if let Some(path) = &usage_path {
883 let entry = build_usage_entry(config, &model_id, "turn".to_string(), 1, usage);
884 match crate::usage_log::append(path, &entry) {
885 Ok(()) => {
886 let mut w = match written.lock() {
887 Ok(g) => g,
888 Err(e) => e.into_inner(),
889 };
890 w.0 += 1;
891 w.1.input += usage.input;
892 w.1.cached += usage.cached;
893 w.1.output += usage.output;
894 w.1.thinking += usage.thinking;
895 }
896 Err(err) => eprintln!("warning: usage log: {err}"),
897 }
898 }
899 }
900 on_event(&event);
901 };
902
903 let bg_base_check = match &config.base_check_dir {
904 Some(base_dir)
905 if !blyte_agent::run::gate_steps(&state.brief.verification_cmd).is_empty() =>
906 {
907 let deadline = max_duration.map(|d| std::time::Instant::now() + d);
908 Some(BackgroundBaseCheck::start(
909 config,
910 state.brief.verification_cmd.clone(),
911 base_dir.clone(),
912 deadline,
913 ))
914 }
915 _ => None,
916 };
917 let base_check = if let Some(ref bg) = bg_base_check {
918 blyte_agent::run::BaseCheck::Polled(bg)
919 } else if config.base_check {
920 blyte_agent::run::BaseCheck::BeforeFirstTurn
921 } else {
922 blyte_agent::run::BaseCheck::None
923 };
924
925 let runner = blyte_agent::run::Runner {
926 provider: provider.as_ref(),
927 shell,
928 fs,
929 context: context_strategy,
930 root,
931 budget: blyte_agent::run::Budget {
932 max_turns: config.max_turns as u32,
933 max_gate_attempts: config.max_gates as u32,
934 max_duration,
935 },
936 rollback: config.rollback,
937 on_event: Some(&runner_on_event),
938 research: config.research,
939 claim_check: config.claim_check,
940 base_check,
941 };
942
943 let (outcome, report) = runner.run(state);
944 drop(bg_base_check);
945
946 if let Some(path) = &usage_path {
947 let (written_turns, written_usage) = match written.lock() {
948 Ok(g) => *g,
949 Err(e) => *e.into_inner(),
950 };
951 let (closing_turns, closing_usage) = match usage_remainder(
952 report.outcome_turns,
953 &report.usage,
954 written_turns,
955 &written_usage,
956 ) {
957 Ok(rem) => rem,
958 Err(exceeded) => {
959 for ExceededField {
960 field,
961 written,
962 total,
963 } in exceeded
964 {
965 eprintln!(
966 "error: usage log: turn lines exceed the run's total ({field}: {written} > {total})"
967 );
968 }
969 (0, blyte_provider::Usage::default())
970 }
971 };
972 let entry = build_usage_entry(
973 config,
974 &model_id,
975 format!("{outcome:?}").to_lowercase(),
976 closing_turns,
977 &closing_usage,
978 );
979 if let Err(err) = crate::usage_log::append(path, &entry) {
980 eprintln!("warning: usage log: {err}");
981 }
982 }
983
984 if let Some(path) = &config.report {
985 let mut record = crate::report::RunRecord::from_run(
986 config,
987 &model_id,
988 &outcome,
989 &report,
990 state,
991 started.elapsed(),
992 );
993 record.effort = provider.effort();
994 crate::report::write(path, &record)?;
995 }
996 Ok((outcome, report))
997}
998
999#[cfg(test)]
1000mod tests {
1001 use super::*;
1002
1003 #[test]
1004 fn usage_remainder_computes_exact_and_partial_remainders() {
1005 let total = blyte_provider::Usage {
1006 input: 600,
1007 cached: 150,
1008 output: 90,
1009 thinking: 75,
1010 };
1011 let exact = usage_remainder(3, &total, 3, &total).unwrap();
1012 assert_eq!(exact, (0, blyte_provider::Usage::default()));
1013
1014 let written = blyte_provider::Usage {
1015 input: 500,
1016 cached: 100,
1017 output: 80,
1018 thinking: 50,
1019 };
1020 let partial = usage_remainder(3, &total, 2, &written).unwrap();
1021 assert_eq!(
1022 partial,
1023 (
1024 1,
1025 blyte_provider::Usage {
1026 input: 100,
1027 cached: 50,
1028 output: 10,
1029 thinking: 25,
1030 }
1031 )
1032 );
1033 }
1034
1035 #[test]
1036 fn usage_remainder_reports_exceeding_fields() {
1037 let total = blyte_provider::Usage {
1038 input: 100,
1039 cached: 20,
1040 output: 30,
1041 thinking: 10,
1042 };
1043 let written = blyte_provider::Usage {
1044 input: 120,
1045 cached: 20,
1046 output: 35,
1047 thinking: 10,
1048 };
1049 let err = usage_remainder(2, &total, 3, &written).unwrap_err();
1050 assert_eq!(
1051 err,
1052 vec![
1053 ExceededField {
1054 field: "turns",
1055 written: 3,
1056 total: 2,
1057 },
1058 ExceededField {
1059 field: "input",
1060 written: 120,
1061 total: 100,
1062 },
1063 ExceededField {
1064 field: "output",
1065 written: 35,
1066 total: 30,
1067 },
1068 ]
1069 );
1070 }
1071
1072 fn test_task_config(root: &Path, report: Option<PathBuf>, model: Option<String>) -> TaskConfig {
1073 TaskConfig {
1074 prompt: "test".to_string(),
1075 gate: Some("true".to_string()),
1076 context_strategy: "folded".to_string(),
1077 model,
1078 container: None,
1079 max_turns: 10,
1080 max_gates: 3,
1081 rollback: false,
1082 root: root.to_path_buf(),
1083 container_workdir: "/workspace".to_string(),
1084 max_seconds: Some(10),
1085 max_cost_usd: None,
1086 report,
1087 fold_budget: None,
1088 sandbox: "off".to_string(),
1089 network: "on".to_string(),
1090 allow_read: Vec::new(),
1091 pass_env: Vec::new(),
1092 research: false,
1093 claim_check: false,
1094 base_check: false,
1095 base_check_dir: None,
1096 converse: false,
1097 dispatch_cmd: None,
1098 }
1099 }
1100
1101 #[test]
1102 fn watchdog_report_write_failure_names_path_and_model_id_is_never_empty() {
1103 let dir = tempfile::tempdir().unwrap();
1104 let report_dir = dir.path().join("unwritable.report.json");
1105 std::fs::create_dir_all(&report_dir).unwrap();
1106
1107 let cfg = test_task_config(dir.path(), Some(report_dir.clone()), None);
1108 let progress = Progress {
1109 turns: 2,
1110 gate_attempts: 1,
1111 in_gate: false,
1112 gate_wait_ms: 0,
1113 usage: blyte_provider::Usage {
1114 input: 1000,
1115 cached: 0,
1116 output: 500,
1117 thinking: 0,
1118 },
1119 };
1120 let mut err_buf = Vec::new();
1121 let err = write_watchdog_report(
1122 &cfg,
1123 &progress,
1124 "stopped past --max-seconds",
1125 std::time::Duration::from_secs(5),
1126 |_| Err("missing API key".to_string()),
1127 &mut err_buf,
1128 )
1129 .expect_err("writing watchdog report to a directory must fail");
1130
1131 assert!(
1132 err.contains(&report_dir.display().to_string()),
1133 "write error must name report path, got: {err}"
1134 );
1135 let warning = String::from_utf8(err_buf).unwrap();
1136 assert!(
1137 warning.contains("missing API key"),
1138 "provider resolution error must be logged, got: {warning}"
1139 );
1140
1141 let ok_report = dir.path().join("ok.report.json");
1142 let ok_cfg = test_task_config(dir.path(), Some(ok_report.clone()), None);
1143 let mut ok_err = Vec::new();
1144 let rec = write_watchdog_report(
1145 &ok_cfg,
1146 &progress,
1147 "stopped past --max-seconds",
1148 std::time::Duration::from_secs(5),
1149 |_| Ok("gemini-3.8-flash-high".to_string()),
1150 &mut ok_err,
1151 )
1152 .expect("writing watchdog report to file must succeed")
1153 .expect("record must be returned");
1154
1155 assert_eq!(rec.model_id.as_deref(), Some("gemini-3.8-flash-high"));
1156 assert!(rec.cost_usd.is_some());
1157
1158 let fallback_report = dir.path().join("fallback.report.json");
1159 let fallback_cfg = test_task_config(dir.path(), Some(fallback_report), None);
1160 let mut fallback_err = Vec::new();
1161 let fallback_rec = write_watchdog_report(
1162 &fallback_cfg,
1163 &progress,
1164 "stopped past --max-seconds",
1165 std::time::Duration::from_secs(5),
1166 |_| Err("no provider".to_string()),
1167 &mut fallback_err,
1168 )
1169 .expect("writing watchdog report must succeed")
1170 .expect("record must be returned");
1171
1172 assert_ne!(fallback_rec.model_id.as_deref(), Some(""));
1173 assert_eq!(fallback_rec.model_id, None);
1174 assert!(String::from_utf8(fallback_err)
1175 .unwrap()
1176 .contains("no provider"));
1177 }
1178}