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