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