1use std::io::Write;
7use std::path::PathBuf;
8use std::sync::{Arc, Mutex};
9
10pub const RESEARCH_FOLD_BUDGET: usize = 180_000;
14
15#[derive(Debug, Default, Clone, Copy)]
17pub struct Progress {
18 pub turns: u32,
19 pub gate_attempts: u32,
20 pub in_gate: bool,
21 pub gate_wait_ms: u64,
22 pub usage: blyte_provider::Usage,
23}
24
25#[derive(Debug, Clone)]
27pub struct TaskConfig {
28 pub prompt: String,
30 pub gate: Option<String>,
32 pub context_strategy: String,
33 pub model: Option<String>,
35 pub container: Option<String>,
37 pub max_turns: usize,
39 pub max_gates: usize,
41 pub rollback: bool,
43 pub root: PathBuf,
45 pub container_workdir: String,
47 pub max_seconds: Option<u64>,
49 pub max_cost_usd: Option<f64>,
51 pub report: Option<PathBuf>,
53 pub fold_budget: Option<usize>,
55 pub sandbox: String,
57 pub network: String,
59 pub allow_read: Vec<PathBuf>,
61 pub pass_env: Vec<String>,
63 pub research: bool,
65 pub claim_check: bool,
67 pub base_check: bool,
69 pub orchestrate: bool,
71 pub dispatch_cmd: Option<String>,
73}
74
75impl From<&crate::cli::Cli> for TaskConfig {
76 fn from(cli: &crate::cli::Cli) -> Self {
78 blyte_agent::tools::set_read_roots(cli.read_roots.clone());
79 let root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
81
82 Self {
83 prompt: cli.prompt.clone().unwrap_or_default(),
84 gate: cli.gate.clone(),
85 context_strategy: cli.context.clone(),
86 model: cli.model.clone(),
87 container: cli.container.clone(),
88 max_turns: cli.max_turns,
89 max_gates: cli.max_gates,
90 rollback: cli.rollback,
91 root,
92 container_workdir: cli.container_workdir.clone(),
93 max_seconds: cli.max_seconds,
94 max_cost_usd: cli.max_cost_usd,
95 report: cli.report.clone(),
96 fold_budget: cli.fold_budget,
97 sandbox: if cli.orchestrate {
98 "off".into()
99 } else {
100 cli.sandbox.clone()
101 },
102 network: cli.network.clone(),
103 allow_read: cli.allow_read.clone(),
104 pass_env: cli.pass_env.clone(),
105 research: cli.research,
106 claim_check: cli.claim_check,
107 base_check: cli.base_check,
108 orchestrate: cli.orchestrate,
109 dispatch_cmd: cli.dispatch_cmd.clone(),
110 }
111 }
112}
113
114pub fn check_network_mode(config: &TaskConfig) -> Result<(), String> {
119 if config.network == "off" {
120 if config.container.is_some() {
121 return Err(
122 "--network=off is not supported with --container; set the container's network instead"
123 .into(),
124 );
125 }
126 if config.sandbox != "on" {
127 return Err("--network=off needs the sandbox".into());
128 }
129 #[cfg(target_os = "linux")]
130 if blyte_agent::sandbox::landlock_abi() < 4 {
131 return Err("--network=off on Linux needs Linux 6.7 or later".into());
132 }
133 if !blyte_agent::sandbox::available() {
134 return Err("--network=off needs the sandbox, but the sandbox is unavailable".into());
135 }
136 }
137 Ok(())
138}
139
140pub fn run_task(
154 config: TaskConfig,
155) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
156 let started = std::time::Instant::now();
157 let progress = Arc::new(Mutex::new(Progress::default()));
158 if let Some(s) = config.max_seconds {
159 let grace_secs: u64 = std::env::var("BLYTE_WATCHDOG_GRACE_SECS")
161 .ok()
162 .and_then(|v| v.trim().parse().ok())
163 .unwrap_or(30);
164 let watchdog_config = config.clone();
165 let watchdog_progress = Arc::clone(&progress);
166 std::thread::spawn(move || {
167 loop {
168 let wait_ms = match watchdog_progress.lock() {
169 Ok(g) => g.gate_wait_ms,
170 Err(e) => e.into_inner().gate_wait_ms,
171 };
172 let deadline = started
173 + std::time::Duration::from_secs(s.saturating_add(grace_secs))
174 + std::time::Duration::from_millis(wait_ms);
175 match deadline.checked_duration_since(std::time::Instant::now()) {
176 Some(remaining) if !remaining.is_zero() => {
177 std::thread::sleep(remaining.min(std::time::Duration::from_millis(500)));
178 }
179 _ => break,
180 }
181 }
182 let p = match watchdog_progress.lock() {
183 Ok(g) => *g,
184 Err(e) => *e.into_inner(),
185 };
186 let msg = if p.in_gate {
187 format!(
188 "stopped {grace_secs} s past --max-seconds {s}: gate attempt {} was still running",
189 p.gate_attempts
190 )
191 } else {
192 format!(
193 "stopped {grace_secs} s past --max-seconds {s} during turn {}: a model call or command never returned",
194 p.turns
195 )
196 };
197 if let Some(path) = &watchdog_config.report {
198 let mut record =
199 crate::report::RunRecord::from_error(&watchdog_config, &msg, started.elapsed());
200 record.turns = p.turns;
201 record.gate_attempts = p.gate_attempts;
202 record.usage = crate::report::UsageRecord {
203 input: p.usage.input,
204 cached: p.usage.cached,
205 output: p.usage.output,
206 thinking: p.usage.thinking,
207 };
208 let model_id = blyte_provider::resolve_provider(watchdog_config.model.as_deref())
209 .map(|pr| pr.model_id())
210 .ok()
211 .or_else(|| watchdog_config.model.clone())
212 .unwrap_or_default();
213 record.cost_usd = blyte_provider::pricing(&model_id).map(|pr| pr.cost(&p.usage));
214 let _ = crate::report::write(path, &record);
215 }
216 eprintln!("blyte: {msg}");
217 std::process::exit(1);
218 });
219 }
220 let verification_cmd = config.gate.as_deref().unwrap_or("");
221 let mut state = blyte_agent::state::State::new(&config.prompt, verification_cmd);
222 state.orchestrator.max_cost_usd = config.max_cost_usd;
223 let mut stdout = std::io::stdout();
224 let result =
225 run_task_with_state_writer_and_progress(&config, &mut state, &mut stdout, progress);
226 if let (Err(e), Some(path)) = (&result, &config.report) {
229 crate::report::write(
230 path,
231 &crate::report::RunRecord::from_error(&config, e, started.elapsed()),
232 )?;
233 }
234 result
235}
236
237pub fn run_task_with_state_and_writer<W: Write>(
251 config: &TaskConfig,
252 state: &mut blyte_agent::state::State,
253 writer: &mut W,
254) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
255 let progress = Arc::new(Mutex::new(Progress::default()));
256 run_task_with_state_writer_and_progress(config, state, writer, progress)
257}
258
259pub fn run_task_with_state_and_events(
262 config: &TaskConfig,
263 state: &mut blyte_agent::state::State,
264 on_event: &(dyn Fn(&blyte_agent::run::Event<'_>) + Sync),
265) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
266 run_task_with_event_callback(config, state, &|event| on_event(event))
267}
268
269pub fn run_task_with_state_writer_and_progress<W: Write>(
272 config: &TaskConfig,
273 state: &mut blyte_agent::state::State,
274 writer: &mut W,
275 progress: Arc<Mutex<Progress>>,
276) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
277 let writer_mutex = Mutex::new(writer);
278 let on_event = |event: &blyte_agent::run::Event<'_>| {
279 {
280 let mut p = match progress.lock() {
281 Ok(g) => g,
282 Err(e) => e.into_inner(),
283 };
284 match event {
285 blyte_agent::run::Event::Turn { n, usage, .. } => {
286 p.turns = *n;
287 p.usage.input += usage.input;
288 p.usage.cached += usage.cached;
289 p.usage.output += usage.output;
290 p.usage.thinking += usage.thinking;
291 p.in_gate = false;
292 }
293 blyte_agent::run::Event::GateStart { attempt } => {
294 p.gate_attempts = *attempt;
295 p.in_gate = true;
296 }
297 blyte_agent::run::Event::GateSlotWait { ms } => {
298 p.gate_wait_ms += ms;
299 }
300 blyte_agent::run::Event::Gate { .. } => {
301 p.in_gate = false;
302 }
303 _ => {}
304 }
305 }
306 let line = crate::repl::format_event(event);
307 if !line.is_empty() {
308 if let Ok(mut w) = writer_mutex.lock() {
309 let _ = writeln!(w, "{line}");
310 }
311 }
312 };
313 run_task_with_event_callback(config, state, &on_event)
314}
315
316fn run_task_with_event_callback(
317 config: &TaskConfig,
318 state: &mut blyte_agent::state::State,
319 on_event: &dyn Fn(&blyte_agent::run::Event<'_>),
320) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
321 check_network_mode(config)?;
322 let started = std::time::Instant::now();
323 if config.orchestrate {
324 if std::env::var("BLYTE_SESSION")
325 .map(|v| v.is_empty())
326 .unwrap_or(true)
327 {
328 let now_secs = std::time::SystemTime::now()
329 .duration_since(std::time::UNIX_EPOCH)
330 .map(|d| d.as_secs())
331 .unwrap_or(0);
332 let id = crate::repl::new_session_id(now_secs, std::process::id());
333 std::env::set_var("BLYTE_SESSION", &id);
334 }
335 if state.orchestrator.instructions.is_none() {
336 let lines = crate::orchestrator_text::set_state_instructions(
337 state,
338 config.dispatch_cmd.is_some(),
339 &config.root,
340 )?;
341 if state.runtime.conversation.is_none() {
342 for line in &lines {
343 eprintln!("blyte: {line}");
344 }
345 }
346 }
347 }
348 blyte_agent::tools::set_dispatch_cmd(config.dispatch_cmd.clone());
349 let provider = match blyte_provider::resolve_provider(config.model.as_deref()) {
352 Ok(p) => p,
353 Err(blyte_provider::ProviderError::MissingKey(key)) => {
354 return Err(format!(
355 "Provider error: no API key: set {key} in environment"
356 ));
357 }
358 Err(e) => return Err(format!("Provider error: {e}")),
359 };
360
361 let model_id = provider.model_id();
362 if config.max_cost_usd.is_some() && blyte_provider::pricing(&model_id).is_none() {
363 return Err(format!(
364 "--max-cost needs a known price for {model_id}; none is known"
365 ));
366 }
367 state.orchestrator.max_cost_usd = config.max_cost_usd;
368
369 let folded = blyte_agent::context::Folded {
371 budget_tokens: config.fold_budget.unwrap_or(if config.research {
373 RESEARCH_FOLD_BUDGET
374 } else {
375 blyte_agent::context::Folded::default().budget_tokens
376 }),
377 };
378 let conversational = blyte_agent::context::Conversational;
379 let context_strategy: &dyn blyte_agent::context::ContextStrategy =
380 match config.context_strategy.as_str() {
381 "conversational" => &conversational,
382 _ => &folded,
383 };
384
385 let local_fs = blyte_agent::fs::LocalFs;
389 let (persistent, session_fs, root) = match &config.container {
390 Some(cid) => (
391 blyte_agent::shell::PersistentShell::container(
392 cid.clone(),
393 PathBuf::from(&config.container_workdir),
394 ),
395 Some(blyte_agent::fs::SessionFs::container(
396 cid.clone(),
397 PathBuf::from(&config.container_workdir),
398 )),
399 PathBuf::from(&config.container_workdir),
400 ),
401 None => {
402 blyte_agent::shell::set_pass_env(config.pass_env.clone());
403 if !config.orchestrate {
404 if let Some(r) = blyte_agent::rules::load(&config.root) {
405 eprintln!("blyte: repository rules from {}", r.source.display());
406 }
407 }
408 let withheld = blyte_agent::shell::withheld_env();
409 if !withheld.is_empty() {
410 eprintln!(
411 "blyte: withholding from commands: {} (keep one with --pass-env NAME)",
412 withheld.join(", ")
413 );
414 }
415 let shell = if config.sandbox == "on" {
416 if blyte_agent::sandbox::available() {
417 let profile = blyte_agent::sandbox::default_profile_net(
418 &config.root,
419 &config.allow_read,
420 config.network == "on",
421 );
422 if matches!(profile, blyte_agent::sandbox::Profile::Landlock(_)) {
423 eprintln!(
424 "blyte: on Linux the sandbox restricts writes only; credential reads are not blocked"
425 );
426 }
427 if matches!(profile, blyte_agent::sandbox::Profile::LandlockOffline(_)) {
428 eprintln!(
429 "blyte: on Linux --network=off blocks TCP connections only (localhost included); UDP and the Docker socket are not blocked"
430 );
431 }
432 if let blyte_agent::sandbox::Profile::LandlockConfined { block_tcp, .. } =
433 &profile
434 {
435 eprintln!(
436 "blyte: on Linux, commands can read only system directories, the workspace, tool caches and --allow-read paths"
437 );
438 if *block_tcp {
439 eprintln!(
440 "blyte: on Linux --network=off blocks TCP connections only (localhost included); UDP and the Docker socket are not blocked"
441 );
442 }
443 }
444 blyte_agent::shell::PersistentShell::local_sandboxed(
445 config.root.clone(),
446 profile,
447 )
448 } else {
449 eprintln!("warning: sandbox unavailable; running unsandboxed");
450 blyte_agent::shell::PersistentShell::local(config.root.clone())
451 }
452 } else {
453 blyte_agent::shell::PersistentShell::local(config.root.clone())
454 };
455 (shell, None, config.root.clone())
456 }
457 };
458 let shell: &dyn blyte_agent::shell::Shell = &persistent;
459 let fs: &dyn blyte_agent::fs::Fs = match &session_fs {
460 Some(f) => f,
461 None => &local_fs,
462 };
463
464 let runner_on_event = |event: blyte_agent::run::Event<'_>| on_event(&event);
465
466 let runner = blyte_agent::run::Runner {
467 provider: provider.as_ref(),
468 shell,
469 fs,
470 context: context_strategy,
471 root,
472 budget: blyte_agent::run::Budget {
473 max_turns: config.max_turns as u32,
474 max_gate_attempts: config.max_gates as u32,
475 max_duration: config.max_seconds.map(std::time::Duration::from_secs),
476 },
477 rollback: config.rollback,
478 on_event: Some(&runner_on_event),
479 research: config.research,
480 claim_check: config.claim_check,
481 base_check: config.base_check,
482 };
483
484 let (outcome, report) = runner.run(state);
485 let model_id = provider.model_id();
486
487 let entry = crate::usage_log::Entry {
488 ts: std::time::SystemTime::now()
489 .duration_since(std::time::UNIX_EPOCH)
490 .map(|d| d.as_secs())
491 .unwrap_or(0),
492 repo: crate::usage_log::repo_of(&config.root),
493 session: crate::usage_log::session_from(
494 std::env::var("BLYTE_SESSION").ok(),
495 std::env::var("CLAUDE_CODE_SESSION_ID").ok(),
496 ),
497 dispatch: std::env::var("BLYTE_DISPATCH_ID")
498 .ok()
499 .filter(|s| !s.is_empty()),
500 research: config.research,
501 model: model_id.clone(),
502 outcome: format!("{outcome:?}").to_lowercase(),
503 turns: report.outcome_turns,
504 input: report.usage.input,
505 cached: report.usage.cached,
506 output: report.usage.output,
507 thinking: report.usage.thinking,
508 cost_usd: blyte_provider::pricing(&model_id).map(|p| p.cost(&report.usage)),
509 };
510 if let Some(path) = crate::usage_log::default_path() {
511 if let Err(err) = crate::usage_log::append(&path, &entry) {
512 eprintln!("warning: usage log: {err}");
513 }
514 }
515
516 if let Some(path) = &config.report {
517 let mut record = crate::report::RunRecord::from_run(
518 config,
519 &model_id,
520 &outcome,
521 &report,
522 state,
523 started.elapsed(),
524 );
525 record.effort = provider.effort();
526 crate::report::write(path, &record)?;
527 }
528 Ok((outcome, report))
529}