1use std::collections::VecDeque;
2use std::panic::{catch_unwind, AssertUnwindSafe};
3use std::sync::{Arc, Condvar, Mutex, MutexGuard};
4use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
5
6#[derive(Clone, Debug, PartialEq, serde::Serialize)]
7pub struct Entry {
8 pub seq: u64,
9 pub ts: u64,
10 #[serde(flatten)]
11 pub body: EntryBody,
12}
13
14#[derive(Clone, Debug, PartialEq, serde::Serialize)]
15#[serde(tag = "kind", rename_all = "snake_case")]
16pub enum EntryBody {
17 UserMessage {
18 text: String,
19 reports: Vec<String>,
20 queued: bool,
21 },
22 Turn {
23 n: u32,
24 text: String,
25 input_tokens: u64,
26 output_tokens: u64,
27 cost_usd: Option<f64>,
28 },
29 ToolStarted {
30 name: String,
31 input: String,
32 },
33 ToolFinished {
34 name: String,
35 summary: String,
36 is_error: bool,
37 },
38 Retry {
39 attempt: u32,
40 max: u32,
41 wait_ms: u64,
42 reason: String,
43 },
44 Error {
45 message: String,
46 },
47 Idle {
48 turns: u32,
49 cost_usd: Option<f64>,
50 },
51 ModelChanged {
52 model: String,
53 },
54 EffortChanged {
55 effort: Option<String>,
56 },
57 Decision {
58 run: String,
59 action: String,
60 note: Option<String>,
61 },
62}
63
64#[derive(Clone, Debug, PartialEq, Eq)]
65pub struct Attachment {
66 pub run: String,
67 pub text: String,
68}
69
70#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
71pub struct SessionInfo {
72 pub model: String,
73 pub effort: Option<String>,
74 pub effort_supported: bool,
75 pub busy: bool,
76 pub queued: usize,
77 pub last_seq: u64,
78}
79
80pub trait PromptRunner: Send + 'static {
81 fn run(
82 &mut self,
83 prompt: &str,
84 model: &str,
85 emit: &(dyn Fn(EntryBody) + Sync),
86 ) -> Result<(), String>;
87}
88
89pub struct AgentRunner {
90 repl: crate::repl::ReplSession,
91}
92
93impl AgentRunner {
94 pub fn new(config: &crate::repl::ReplConfig) -> Self {
95 let mut cfg = config.clone();
96 cfg.orchestrate = true;
97 let repl = crate::repl::ReplSession::new(&cfg);
98 if let Some(approval) = blyte_agent::tools::approval() {
99 blyte_agent::tools::set_approval(Some(blyte_agent::approval::ApprovalConfig {
100 approver: std::sync::Arc::new(blyte_agent::approval::NoApprover),
101 rules: approval.rules,
102 }));
103 }
104 Self { repl }
105 }
106}
107
108impl PromptRunner for AgentRunner {
109 fn run(
110 &mut self,
111 prompt: &str,
112 model: &str,
113 emit: &(dyn Fn(EntryBody) + Sync),
114 ) -> Result<(), String> {
115 self.repl.model = model.to_string();
116 self.repl.state.orchestrator.goal = prompt.to_string();
117 if let Some(ref gate) = self.repl.gate {
118 self.repl.state.orchestrator.verification_cmd = gate.clone();
119 }
120 let task_config = self.repl.task_config_for_prompt(prompt);
121 let pricing = blyte_provider::pricing(model);
122 let on_event = |event: &blyte_agent::run::Event<'_>| match event {
123 blyte_agent::run::Event::Turn { n, text, usage } => {
124 emit(EntryBody::Turn {
125 n: *n,
126 text: (*text).to_string(),
127 input_tokens: usage.input + usage.cached,
128 output_tokens: usage.output + usage.thinking,
129 cost_usd: pricing.map(|p| p.cost(usage)),
130 });
131 }
132 blyte_agent::run::Event::ToolStart { name, input } => {
133 emit(EntryBody::ToolStarted {
134 name: (*name).to_string(),
135 input: input.clone(),
136 });
137 }
138 blyte_agent::run::Event::Tool {
139 name,
140 summary,
141 is_error,
142 ..
143 } => {
144 emit(EntryBody::ToolFinished {
145 name: (*name).to_string(),
146 summary: summary.clone(),
147 is_error: *is_error,
148 });
149 }
150 blyte_agent::run::Event::Retry {
151 attempt,
152 max,
153 wait_ms,
154 reason,
155 } => {
156 emit(EntryBody::Retry {
157 attempt: *attempt,
158 max: *max,
159 wait_ms: *wait_ms,
160 reason: reason.clone(),
161 });
162 }
163 _ => {}
164 };
165 let (outcome, _) = crate::task_runner::run_task_with_state_and_events(
166 &task_config,
167 &mut self.repl.state,
168 &on_event,
169 )?;
170 match outcome {
171 blyte_agent::run::Outcome::Verified | blyte_agent::run::Outcome::Finished => Ok(()),
172 blyte_agent::run::Outcome::BudgetExhausted => Err("budget exhausted".to_string()),
173 blyte_agent::run::Outcome::GateFailed => Err("gate failed".to_string()),
174 blyte_agent::run::Outcome::Blocked(msg) | blyte_agent::run::Outcome::Error(msg) => {
175 Err(msg)
176 }
177 }
178 }
179}
180
181struct SessionState {
182 entries: Vec<Entry>,
183 queue: VecDeque<String>,
184 model: String,
185 effort: Option<String>,
186 busy: bool,
187 closed: bool,
188}
189
190impl SessionState {
191 fn push_entry(&mut self, body: EntryBody) -> u64 {
192 let seq = self.entries.len() as u64 + 1;
193 let ts = now_secs();
194 self.entries.push(Entry { seq, ts, body });
195 seq
196 }
197
198 fn effective_model(&self) -> String {
199 match &self.effort {
200 Some(effort) if model_supports_effort(&self.model) => {
201 format!("{}-{}", self.model, effort)
202 }
203 _ => self.model.clone(),
204 }
205 }
206}
207
208struct Shared {
209 state: Mutex<SessionState>,
210 log_cv: Condvar,
211 work_cv: Condvar,
212}
213
214impl Shared {
215 fn lock_state(&self) -> MutexGuard<'_, SessionState> {
216 self.state.lock().unwrap_or_else(|e| e.into_inner())
217 }
218}
219
220struct SessionGuard {
221 shared: Arc<Shared>,
222}
223
224impl Drop for SessionGuard {
225 fn drop(&mut self) {
226 let mut state = self.shared.lock_state();
227 state.closed = true;
228 self.shared.work_cv.notify_all();
229 self.shared.log_cv.notify_all();
230 }
231}
232
233#[derive(Clone)]
234pub struct Session {
235 guard: Arc<SessionGuard>,
236}
237
238struct TurnTotals {
239 turns: u32,
240 cost_usd: Option<f64>,
241}
242
243impl Session {
244 pub fn start(runner: Box<dyn PromptRunner>, model: String) -> Session {
245 let (base_model, effort) = parse_model_and_effort(&model);
246 let shared = Arc::new(Shared {
247 state: Mutex::new(SessionState {
248 entries: Vec::new(),
249 queue: VecDeque::new(),
250 model: base_model,
251 effort,
252 busy: false,
253 closed: false,
254 }),
255 log_cv: Condvar::new(),
256 work_cv: Condvar::new(),
257 });
258 let worker_shared = Arc::clone(&shared);
259 std::thread::spawn(move || worker_loop(runner, worker_shared));
260 Session {
261 guard: Arc::new(SessionGuard { shared }),
262 }
263 }
264
265 pub fn submit(&self, text: &str, attachments: Vec<Attachment>) -> Result<u64, String> {
266 if text.trim().is_empty() {
267 return Err("a message needs text".to_string());
268 }
269 let reports = attachments.iter().map(|a| a.run.clone()).collect();
270 let full_prompt = format_prompt(text, &attachments);
271 let mut state = self.guard.shared.lock_state();
272 let queued = state.busy || !state.queue.is_empty();
273 let seq = state.push_entry(EntryBody::UserMessage {
274 text: text.to_string(),
275 reports,
276 queued,
277 });
278 state.queue.push_back(full_prompt);
279 self.guard.shared.work_cv.notify_one();
280 self.guard.shared.log_cv.notify_all();
281 Ok(seq)
282 }
283
284 pub fn entries_after(&self, after: u64, wait: Duration) -> Vec<Entry> {
285 let mut state = self.guard.shared.lock_state();
286 if (state.entries.len() as u64) <= after && !wait.is_zero() {
287 let deadline = Instant::now() + wait;
288 while (state.entries.len() as u64) <= after {
289 let remaining = deadline.saturating_duration_since(Instant::now());
290 if remaining.is_zero() {
291 break;
292 }
293 let (guard, _) = self
294 .guard
295 .shared
296 .log_cv
297 .wait_timeout(state, remaining)
298 .unwrap_or_else(|e| e.into_inner());
299 state = guard;
300 }
301 }
302 let start = usize::try_from(after).unwrap_or(usize::MAX);
303 if start >= state.entries.len() {
304 Vec::new()
305 } else {
306 state.entries[start..].to_vec()
307 }
308 }
309
310 pub fn info(&self) -> SessionInfo {
311 let state = self.guard.shared.lock_state();
312 SessionInfo {
313 effort_supported: model_supports_effort(&state.model),
314 model: state.model.clone(),
315 effort: state.effort.clone(),
316 busy: state.busy,
317 queued: state.queue.len(),
318 last_seq: state.entries.len() as u64,
319 }
320 }
321
322 pub fn set_model(&self, model: &str) -> Result<(), String> {
323 let trimmed = model.trim();
324 if trimmed.is_empty() {
325 return Err("model cannot be empty".to_string());
326 }
327 let mut state = self.guard.shared.lock_state();
328 let supported = model_supports_effort(trimmed);
329 if supported {
330 let (base, parsed_effort) = blyte_provider::gemini::split_effort(trimmed);
331 state.model = base.clone();
332 state.push_entry(EntryBody::ModelChanged { model: base });
333 if let Some(new_effort) = parsed_effort {
334 if state.effort.as_deref() != Some(new_effort.as_str()) {
335 state.effort = Some(new_effort.clone());
336 state.push_entry(EntryBody::EffortChanged {
337 effort: Some(new_effort),
338 });
339 }
340 }
341 } else {
342 state.model = trimmed.to_string();
343 state.push_entry(EntryBody::ModelChanged {
344 model: trimmed.to_string(),
345 });
346 if state.effort.is_some() {
347 state.effort = None;
348 state.push_entry(EntryBody::EffortChanged { effort: None });
349 }
350 }
351 self.guard.shared.log_cv.notify_all();
352 Ok(())
353 }
354
355 pub fn set_effort(&self, effort: Option<&str>) -> Result<(), String> {
356 let normalized = match effort {
357 None => None,
358 Some("low") => Some("low".to_string()),
359 Some("medium") => Some("medium".to_string()),
360 Some("high") => Some("high".to_string()),
361 Some(_) => return Err("effort must be low, medium or high".to_string()),
362 };
363 let mut state = self.guard.shared.lock_state();
364 if !model_supports_effort(&state.model) {
365 return Err(format!("{} does not take an effort setting", state.model));
366 }
367 state.effort = normalized.clone();
368 state.push_entry(EntryBody::EffortChanged { effort: normalized });
369 self.guard.shared.log_cv.notify_all();
370 Ok(())
371 }
372
373 pub fn record_decision(
374 &self,
375 run: &str,
376 action: &str,
377 note: Option<&str>,
378 orchestrator_message: Option<&str>,
379 ) -> Result<u64, String> {
380 if let Some(msg) = orchestrator_message {
381 if msg.trim().is_empty() {
382 return Err("a message needs text".to_string());
383 }
384 }
385 let mut state = self.guard.shared.lock_state();
386 let seq = state.push_entry(EntryBody::Decision {
387 run: run.to_string(),
388 action: action.to_string(),
389 note: note.map(str::to_string),
390 });
391 if let Some(msg) = orchestrator_message {
392 let queued = state.busy || !state.queue.is_empty();
393 state.push_entry(EntryBody::UserMessage {
394 text: msg.to_string(),
395 reports: Vec::new(),
396 queued,
397 });
398 state.queue.push_back(msg.to_string());
399 self.guard.shared.work_cv.notify_one();
400 }
401 self.guard.shared.log_cv.notify_all();
402 Ok(seq)
403 }
404}
405
406fn worker_loop(mut runner: Box<dyn PromptRunner>, shared: Arc<Shared>) {
407 loop {
408 let (prompt, effective_model) = {
409 let mut state = shared.lock_state();
410 loop {
411 if state.closed {
412 return;
413 }
414 if let Some(prompt) = state.queue.pop_front() {
415 state.busy = true;
416 let model = state.effective_model();
417 break (prompt, model);
418 }
419 state = shared
420 .work_cv
421 .wait(state)
422 .unwrap_or_else(|e| e.into_inner());
423 }
424 };
425
426 let totals = Mutex::new(TurnTotals {
427 turns: 0,
428 cost_usd: Some(0.0),
429 });
430 let emit_shared = Arc::clone(&shared);
431 let emit = |body: EntryBody| {
432 if let EntryBody::Turn { cost_usd, .. } = &body {
433 let mut t = totals.lock().unwrap_or_else(|e| e.into_inner());
434 t.turns += 1;
435 match (t.cost_usd, cost_usd) {
436 (Some(acc), Some(c)) => t.cost_usd = Some(acc + c),
437 _ => t.cost_usd = None,
438 }
439 }
440 let mut state = emit_shared.lock_state();
441 state.push_entry(body);
442 emit_shared.log_cv.notify_all();
443 };
444
445 let outcome = catch_unwind(AssertUnwindSafe(|| {
446 runner.run(&prompt, &effective_model, &emit)
447 }));
448
449 let (turns, cost_usd) = {
450 let t = totals.lock().unwrap_or_else(|e| e.into_inner());
451 (t.turns, t.cost_usd)
452 };
453
454 let mut state = shared.lock_state();
455 match outcome {
456 Ok(Ok(())) => {}
457 Ok(Err(message)) => {
458 state.push_entry(EntryBody::Error { message });
459 }
460 Err(payload) => {
461 let message = panic_message(payload);
462 state.push_entry(EntryBody::Error { message });
463 }
464 }
465 state.push_entry(EntryBody::Idle { turns, cost_usd });
466 state.busy = false;
467 shared.log_cv.notify_all();
468 }
469}
470
471fn format_prompt(text: &str, attachments: &[Attachment]) -> String {
472 let mut out = text.to_string();
473 for att in attachments {
474 out.push_str("\n\nResearch report ");
475 out.push_str(&att.run);
476 out.push_str(":\n");
477 out.push_str(&att.text);
478 }
479 out
480}
481
482pub(crate) fn model_supports_effort(model: &str) -> bool {
483 blyte_provider::detect_provider_kind(Some(model)) == blyte_provider::ProviderKind::Gemini
484}
485
486fn parse_model_and_effort(model: &str) -> (String, Option<String>) {
487 let trimmed = model.trim();
488 if model_supports_effort(trimmed) {
489 blyte_provider::gemini::split_effort(trimmed)
490 } else {
491 (trimmed.to_string(), None)
492 }
493}
494
495fn panic_message(payload: Box<dyn std::any::Any + Send>) -> String {
496 if let Some(s) = payload.downcast_ref::<&str>() {
497 (*s).to_string()
498 } else if let Some(s) = payload.downcast_ref::<String>() {
499 s.clone()
500 } else {
501 "runner panicked".to_string()
502 }
503}
504
505fn now_secs() -> u64 {
506 SystemTime::now()
507 .duration_since(UNIX_EPOCH)
508 .map(|d| d.as_secs())
509 .unwrap_or(0)
510}