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