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