1use std::collections::{HashMap, VecDeque};
2use std::panic::{catch_unwind, AssertUnwindSafe};
3use std::sync::atomic::{AtomicU64, Ordering};
4use std::sync::{Arc, Condvar, Mutex, MutexGuard};
5use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
6
7static SESSION_COUNTER: AtomicU64 = AtomicU64::new(0);
8
9#[derive(Clone, Debug, PartialEq, serde::Serialize)]
10pub struct Entry {
11 pub seq: u64,
12 pub ts: u64,
13 #[serde(flatten)]
14 pub body: EntryBody,
15}
16
17#[derive(Clone, Debug, PartialEq, serde::Serialize)]
18#[serde(tag = "kind", rename_all = "snake_case")]
19pub enum EntryBody {
20 UserMessage {
21 text: String,
22 reports: Vec<String>,
23 queued: bool,
24 },
25 Turn {
26 n: u32,
27 text: String,
28 input_tokens: u64,
29 output_tokens: u64,
30 cost_usd: Option<f64>,
31 },
32 ToolStarted {
33 name: String,
34 input: String,
35 },
36 ToolFinished {
37 name: String,
38 summary: String,
39 is_error: bool,
40 },
41 Retry {
42 attempt: u32,
43 max: u32,
44 wait_ms: u64,
45 reason: String,
46 },
47 Error {
48 message: String,
49 },
50 Idle {
51 turns: u32,
52 cost_usd: Option<f64>,
53 },
54 ModelChanged {
55 model: String,
56 },
57 EffortChanged {
58 effort: Option<String>,
59 },
60 Decision {
61 run: String,
62 action: String,
63 note: Option<String>,
64 },
65 ApprovalRequested {
66 id: String,
67 command: String,
68 reason: String,
69 },
70 ApprovalAnswered {
71 id: String,
72 command: String,
73 answer: String,
74 },
75}
76
77#[derive(Clone, Copy, Debug, PartialEq, Eq)]
78pub enum ApprovalAnswer {
79 Yes,
80 No,
81}
82
83impl ApprovalAnswer {
84 pub fn as_str(self) -> &'static str {
85 match self {
86 ApprovalAnswer::Yes => "yes",
87 ApprovalAnswer::No => "no",
88 }
89 }
90
91 fn to_approval(self) -> blyte_agent::approval::Approval {
92 match self {
93 ApprovalAnswer::Yes => blyte_agent::approval::Approval::Approved,
94 ApprovalAnswer::No => blyte_agent::approval::Approval::Denied,
95 }
96 }
97}
98
99#[derive(Clone, Debug, PartialEq, Eq)]
100pub enum AnswerError {
101 NotFound,
102 AlreadyAnswered,
103}
104
105pub struct SurfaceApprover {
106 shared: Arc<Shared>,
107}
108
109impl blyte_agent::approval::Approver for SurfaceApprover {
110 fn ask(&self, command: &str, reason: &str) -> blyte_agent::approval::Approval {
111 let mut state = self.shared.lock_state();
112 if state.closed {
113 return blyte_agent::approval::Approval::Denied;
114 }
115 state.next_approval_id += 1;
116 let order = state.next_approval_id;
117 let id = format!("approval-{order}");
118 state.approvals.insert(
119 id.clone(),
120 ApprovalRecord {
121 order,
122 command: command.to_string(),
123 answer: None,
124 },
125 );
126 state.push_entry(EntryBody::ApprovalRequested {
127 id: id.clone(),
128 command: command.to_string(),
129 reason: reason.to_string(),
130 });
131 self.shared.log_cv.notify_all();
132
133 loop {
134 if let Some(answer) = state.approvals.get(&id).and_then(|r| r.answer) {
135 return answer.to_approval();
136 }
137 if state.closed {
138 return blyte_agent::approval::Approval::Denied;
139 }
140 state = self
141 .shared
142 .approval_cv
143 .wait(state)
144 .unwrap_or_else(|e| e.into_inner());
145 }
146 }
147}
148
149#[derive(Clone, Debug, PartialEq, Eq)]
150pub struct Attachment {
151 pub run: String,
152 pub text: String,
153}
154
155#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
156pub struct SessionInfo {
157 pub model: String,
158 pub effort: Option<String>,
159 pub effort_supported: bool,
160 pub busy: bool,
161 pub queued: usize,
162 pub last_seq: u64,
163}
164
165pub trait PromptRunner: Send + 'static {
166 fn run(
167 &mut self,
168 prompt: &str,
169 model: &str,
170 emit: &(dyn Fn(EntryBody) + Sync),
171 ) -> Result<(), String>;
172}
173
174pub struct AgentRunner {
175 repl: crate::repl::ReplSession,
176 approver: Arc<dyn blyte_agent::approval::Approver>,
177}
178
179impl AgentRunner {
180 pub fn new(
181 config: &crate::repl::ReplConfig,
182 approver: Arc<dyn blyte_agent::approval::Approver>,
183 ) -> Self {
184 let mut cfg = config.clone();
185 cfg.orchestrate = true;
186 let repl = crate::repl::ReplSession::try_new_with_approver(&cfg, Some(approver.clone()))
187 .expect("failed to initialize REPL session");
188 Self { repl, approver }
189 }
190}
191
192impl PromptRunner for AgentRunner {
193 fn run(
194 &mut self,
195 prompt: &str,
196 model: &str,
197 emit: &(dyn Fn(EntryBody) + Sync),
198 ) -> Result<(), String> {
199 self.repl.model = model.to_string();
200 self.repl.state.orchestrator.goal = prompt.to_string();
201 if let Some(ref gate) = self.repl.gate {
202 self.repl.state.orchestrator.verification_cmd = gate.clone();
203 }
204 let task_config = self.repl.task_config_for_prompt(prompt);
205 let pricing = blyte_provider::pricing(model);
206 let on_event = |event: &blyte_agent::run::Event<'_>| match event {
207 blyte_agent::run::Event::Turn { n, text, usage } => {
208 emit(EntryBody::Turn {
209 n: *n,
210 text: (*text).to_string(),
211 input_tokens: usage.input + usage.cached,
212 output_tokens: usage.output + usage.thinking,
213 cost_usd: pricing.map(|p| p.cost(usage)),
214 });
215 }
216 blyte_agent::run::Event::ToolStart { name, input } => {
217 emit(EntryBody::ToolStarted {
218 name: (*name).to_string(),
219 input: input.clone(),
220 });
221 }
222 blyte_agent::run::Event::Tool {
223 name,
224 summary,
225 is_error,
226 ..
227 } => {
228 emit(EntryBody::ToolFinished {
229 name: (*name).to_string(),
230 summary: summary.clone(),
231 is_error: *is_error,
232 });
233 }
234 blyte_agent::run::Event::Retry {
235 attempt,
236 max,
237 wait_ms,
238 reason,
239 } => {
240 emit(EntryBody::Retry {
241 attempt: *attempt,
242 max: *max,
243 wait_ms: *wait_ms,
244 reason: reason.clone(),
245 });
246 }
247 _ => {}
248 };
249 let (outcome, _) = crate::task_runner::run_task_with_approver(
250 &task_config,
251 &mut self.repl.state,
252 Some(self.approver.clone()),
253 &on_event,
254 )?;
255 match outcome {
256 blyte_agent::run::Outcome::Verified | blyte_agent::run::Outcome::Finished => Ok(()),
257 blyte_agent::run::Outcome::BudgetExhausted => Err("budget exhausted".to_string()),
258 blyte_agent::run::Outcome::GateFailed => Err("gate failed".to_string()),
259 blyte_agent::run::Outcome::Blocked(msg) | blyte_agent::run::Outcome::Error(msg) => {
260 Err(msg)
261 }
262 }
263 }
264}
265
266struct ApprovalRecord {
267 order: u64,
268 command: String,
269 answer: Option<ApprovalAnswer>,
270}
271
272struct QueuedMessage {
273 request_id: String,
274 prompt: String,
275}
276
277struct SessionState {
278 entries: Vec<Entry>,
279 queue: VecDeque<QueuedMessage>,
280 session_prefix: String,
281 request_seq: u64,
282 model: String,
283 effort: Option<String>,
284 busy: bool,
285 closed: bool,
286 approvals: HashMap<String, ApprovalRecord>,
287 next_approval_id: u64,
288}
289
290impl SessionState {
291 fn push_entry(&mut self, body: EntryBody) -> u64 {
292 let seq = self.entries.len() as u64 + 1;
293 let ts = now_secs();
294 self.entries.push(Entry { seq, ts, body });
295 seq
296 }
297
298 fn next_request_id(&mut self) -> String {
299 self.request_seq += 1;
300 format!("{}-{}", self.session_prefix, self.request_seq)
301 }
302
303 fn effective_model(&self) -> String {
304 match &self.effort {
305 Some(effort) if model_supports_effort(&self.model) => {
306 format!("{}-{}", self.model, effort)
307 }
308 _ => self.model.clone(),
309 }
310 }
311
312 fn deny_all_pending(&mut self) -> bool {
313 let mut pending: Vec<(u64, String, String)> = self
314 .approvals
315 .iter()
316 .filter(|(_, record)| record.answer.is_none())
317 .map(|(id, record)| (record.order, id.clone(), record.command.clone()))
318 .collect();
319 if pending.is_empty() {
320 return false;
321 }
322 pending.sort_by_key(|(order, _, _)| *order);
323 for (_, id, command) in pending {
324 if let Some(record) = self.approvals.get_mut(&id) {
325 record.answer = Some(ApprovalAnswer::No);
326 }
327 self.push_entry(EntryBody::ApprovalAnswered {
328 id,
329 command,
330 answer: ApprovalAnswer::No.as_str().to_string(),
331 });
332 }
333 true
334 }
335}
336
337struct Shared {
338 state: Mutex<SessionState>,
339 log_cv: Condvar,
340 work_cv: Condvar,
341 approval_cv: Condvar,
342}
343
344impl Shared {
345 fn new(model: String, effort: Option<String>) -> Self {
346 Self {
347 state: Mutex::new(SessionState {
348 entries: Vec::new(),
349 queue: VecDeque::new(),
350 session_prefix: new_session_prefix(),
351 request_seq: 0,
352 model,
353 effort,
354 busy: false,
355 closed: false,
356 approvals: HashMap::new(),
357 next_approval_id: 0,
358 }),
359 log_cv: Condvar::new(),
360 work_cv: Condvar::new(),
361 approval_cv: Condvar::new(),
362 }
363 }
364
365 fn lock_state(&self) -> MutexGuard<'_, SessionState> {
366 self.state.lock().unwrap_or_else(|e| e.into_inner())
367 }
368}
369
370struct SessionGuard {
371 shared: Arc<Shared>,
372}
373
374impl Drop for SessionGuard {
375 fn drop(&mut self) {
376 let mut state = self.shared.lock_state();
377 state.closed = true;
378 state.deny_all_pending();
379 self.shared.work_cv.notify_all();
380 self.shared.log_cv.notify_all();
381 self.shared.approval_cv.notify_all();
382 }
383}
384
385#[derive(Clone)]
386pub struct Session {
387 guard: Arc<SessionGuard>,
388}
389
390struct TurnTotals {
391 turns: u32,
392 cost_usd: Option<f64>,
393}
394
395impl Session {
396 pub fn start(runner: Box<dyn PromptRunner>, model: String) -> Session {
397 Self::start_with(model, |_| runner)
398 }
399
400 pub fn start_with<F>(model: String, build_runner: F) -> Session
401 where
402 F: FnOnce(Arc<SurfaceApprover>) -> Box<dyn PromptRunner>,
403 {
404 let (base_model, effort) = parse_model_and_effort(&model);
405 let shared = Arc::new(Shared::new(base_model, effort));
406 let approver = Arc::new(SurfaceApprover {
407 shared: Arc::clone(&shared),
408 });
409 let runner = build_runner(approver);
410 let worker_shared = Arc::clone(&shared);
411 std::thread::spawn(move || worker_loop(runner, worker_shared));
412 Session {
413 guard: Arc::new(SessionGuard { shared }),
414 }
415 }
416
417 #[doc(hidden)]
418 pub fn start_paused(
419 runner: Box<dyn PromptRunner>,
420 model: String,
421 ) -> (Session, std::sync::mpsc::Sender<()>) {
422 let (base_model, effort) = parse_model_and_effort(&model);
423 let shared = Arc::new(Shared::new(base_model, effort));
424 let (tx, rx) = std::sync::mpsc::channel();
425 let worker_shared = Arc::clone(&shared);
426 std::thread::spawn(move || {
427 if rx.recv().is_ok() {
428 worker_loop(runner, worker_shared);
429 }
430 });
431 (
432 Session {
433 guard: Arc::new(SessionGuard { shared }),
434 },
435 tx,
436 )
437 }
438
439 pub fn approver(&self) -> Arc<SurfaceApprover> {
440 Arc::new(SurfaceApprover {
441 shared: Arc::clone(&self.guard.shared),
442 })
443 }
444
445 pub fn answer_approval(&self, id: &str, answer: ApprovalAnswer) -> Result<u64, AnswerError> {
446 let mut state = self.guard.shared.lock_state();
447 let command = match state.approvals.get_mut(id) {
448 None => return Err(AnswerError::NotFound),
449 Some(record) if record.answer.is_some() => return Err(AnswerError::AlreadyAnswered),
450 Some(record) => {
451 record.answer = Some(answer);
452 record.command.clone()
453 }
454 };
455 let seq = state.push_entry(EntryBody::ApprovalAnswered {
456 id: id.to_string(),
457 command,
458 answer: answer.as_str().to_string(),
459 });
460 self.guard.shared.approval_cv.notify_all();
461 self.guard.shared.log_cv.notify_all();
462 Ok(seq)
463 }
464
465 pub fn stop_run(&self) {
466 let mut state = self.guard.shared.lock_state();
467 if state.deny_all_pending() {
468 self.guard.shared.approval_cv.notify_all();
469 self.guard.shared.log_cv.notify_all();
470 }
471 }
472
473 pub fn submit(&self, text: &str, attachments: Vec<Attachment>) -> Result<u64, String> {
474 if text.trim().is_empty() {
475 return Err("a message needs text".to_string());
476 }
477 let reports = attachments.iter().map(|a| a.run.clone()).collect();
478 let full_prompt = format_prompt(text, &attachments);
479 let mut state = self.guard.shared.lock_state();
480 let queued = state.busy || !state.queue.is_empty();
481 let seq = state.push_entry(EntryBody::UserMessage {
482 text: text.to_string(),
483 reports,
484 queued,
485 });
486 let request_id = state.next_request_id();
487 state.queue.push_back(QueuedMessage {
488 request_id,
489 prompt: full_prompt,
490 });
491 self.guard.shared.work_cv.notify_one();
492 self.guard.shared.log_cv.notify_all();
493 Ok(seq)
494 }
495
496 pub fn entries_after(&self, after: u64, wait: Duration) -> Vec<Entry> {
497 let mut state = self.guard.shared.lock_state();
498 if (state.entries.len() as u64) <= after && !wait.is_zero() {
499 let deadline = Instant::now() + wait;
500 while (state.entries.len() as u64) <= after {
501 let remaining = deadline.saturating_duration_since(Instant::now());
502 if remaining.is_zero() {
503 break;
504 }
505 let (guard, _) = self
506 .guard
507 .shared
508 .log_cv
509 .wait_timeout(state, remaining)
510 .unwrap_or_else(|e| e.into_inner());
511 state = guard;
512 }
513 }
514 let start = usize::try_from(after).unwrap_or(usize::MAX);
515 if start >= state.entries.len() {
516 Vec::new()
517 } else {
518 state.entries[start..].to_vec()
519 }
520 }
521
522 pub fn info(&self) -> SessionInfo {
523 let state = self.guard.shared.lock_state();
524 SessionInfo {
525 effort_supported: model_supports_effort(&state.model),
526 model: state.model.clone(),
527 effort: state.effort.clone(),
528 busy: state.busy,
529 queued: state.queue.len(),
530 last_seq: state.entries.len() as u64,
531 }
532 }
533
534 pub fn set_model(&self, model: &str) -> Result<(), String> {
535 let trimmed = model.trim();
536 if trimmed.is_empty() {
537 return Err("model cannot be empty".to_string());
538 }
539 let mut state = self.guard.shared.lock_state();
540 let supported = model_supports_effort(trimmed);
541 if supported {
542 let (base, parsed_effort) = blyte_provider::gemini::split_effort(trimmed);
543 state.model = base.clone();
544 state.push_entry(EntryBody::ModelChanged { model: base });
545 if let Some(new_effort) = parsed_effort {
546 if state.effort.as_deref() != Some(new_effort.as_str()) {
547 state.effort = Some(new_effort.clone());
548 state.push_entry(EntryBody::EffortChanged {
549 effort: Some(new_effort),
550 });
551 }
552 }
553 } else {
554 state.model = trimmed.to_string();
555 state.push_entry(EntryBody::ModelChanged {
556 model: trimmed.to_string(),
557 });
558 if state.effort.is_some() {
559 state.effort = None;
560 state.push_entry(EntryBody::EffortChanged { effort: None });
561 }
562 }
563 self.guard.shared.log_cv.notify_all();
564 Ok(())
565 }
566
567 pub fn set_effort(&self, effort: Option<&str>) -> Result<(), String> {
568 let normalized = match effort {
569 None => None,
570 Some("low") => Some("low".to_string()),
571 Some("medium") => Some("medium".to_string()),
572 Some("high") => Some("high".to_string()),
573 Some(_) => return Err("effort must be low, medium or high".to_string()),
574 };
575 let mut state = self.guard.shared.lock_state();
576 if !model_supports_effort(&state.model) {
577 return Err(format!("{} does not take an effort setting", state.model));
578 }
579 state.effort = normalized.clone();
580 state.push_entry(EntryBody::EffortChanged { effort: normalized });
581 self.guard.shared.log_cv.notify_all();
582 Ok(())
583 }
584
585 pub fn record_decision(
586 &self,
587 run: &str,
588 action: &str,
589 note: Option<&str>,
590 orchestrator_message: Option<&str>,
591 ) -> Result<u64, String> {
592 if let Some(msg) = orchestrator_message {
593 if msg.trim().is_empty() {
594 return Err("a message needs text".to_string());
595 }
596 }
597 let mut state = self.guard.shared.lock_state();
598 let seq = state.push_entry(EntryBody::Decision {
599 run: run.to_string(),
600 action: action.to_string(),
601 note: note.map(str::to_string),
602 });
603 if let Some(msg) = orchestrator_message {
604 let queued = state.busy || !state.queue.is_empty();
605 state.push_entry(EntryBody::UserMessage {
606 text: msg.to_string(),
607 reports: Vec::new(),
608 queued,
609 });
610 let request_id = state.next_request_id();
611 state.queue.push_back(QueuedMessage {
612 request_id,
613 prompt: msg.to_string(),
614 });
615 self.guard.shared.work_cv.notify_one();
616 }
617 self.guard.shared.log_cv.notify_all();
618 Ok(seq)
619 }
620
621 pub fn queue_for_request(&self, request_id: &str, text: &str) -> Result<u64, String> {
622 if text.trim().is_empty() {
623 return Err("a message needs text".to_string());
624 }
625 let mut state = self.guard.shared.lock_state();
626 let queued = state.busy || !state.queue.is_empty();
627 let seq = state.push_entry(EntryBody::UserMessage {
628 text: text.to_string(),
629 reports: Vec::new(),
630 queued,
631 });
632 state.queue.push_back(QueuedMessage {
633 request_id: request_id.to_string(),
634 prompt: text.to_string(),
635 });
636 self.guard.shared.work_cv.notify_one();
637 self.guard.shared.log_cv.notify_all();
638 Ok(seq)
639 }
640
641 pub fn record_error(&self, message: &str) -> u64 {
642 let mut state = self.guard.shared.lock_state();
643 let seq = state.push_entry(EntryBody::Error {
644 message: message.to_string(),
645 });
646 self.guard.shared.log_cv.notify_all();
647 seq
648 }
649}
650
651struct RequestGuard;
652
653impl RequestGuard {
654 fn enter(request_id: String) -> Self {
655 blyte_agent::tools::set_blyte_request(Some(request_id));
656 Self
657 }
658}
659
660impl Drop for RequestGuard {
661 fn drop(&mut self) {
662 blyte_agent::tools::set_blyte_request(None);
663 }
664}
665
666fn worker_loop(mut runner: Box<dyn PromptRunner>, shared: Arc<Shared>) {
667 loop {
668 let (msg, effective_model) = {
669 let mut state = shared.lock_state();
670 loop {
671 if state.closed {
672 return;
673 }
674 if let Some(msg) = state.queue.pop_front() {
675 state.busy = true;
676 let model = state.effective_model();
677 break (msg, model);
678 }
679 state = shared
680 .work_cv
681 .wait(state)
682 .unwrap_or_else(|e| e.into_inner());
683 }
684 };
685
686 let totals = Mutex::new(TurnTotals {
687 turns: 0,
688 cost_usd: Some(0.0),
689 });
690 let emit_shared = Arc::clone(&shared);
691 let emit = |body: EntryBody| {
692 if let EntryBody::Turn { cost_usd, .. } = &body {
693 let mut t = totals.lock().unwrap_or_else(|e| e.into_inner());
694 t.turns += 1;
695 match (t.cost_usd, cost_usd) {
696 (Some(acc), Some(c)) => t.cost_usd = Some(acc + c),
697 _ => t.cost_usd = None,
698 }
699 }
700 let mut state = emit_shared.lock_state();
701 state.push_entry(body);
702 emit_shared.log_cv.notify_all();
703 };
704
705 let outcome = catch_unwind(AssertUnwindSafe(|| {
706 let _req_guard = RequestGuard::enter(msg.request_id);
707 runner.run(&msg.prompt, &effective_model, &emit)
708 }));
709
710 let (turns, cost_usd) = {
711 let t = totals.lock().unwrap_or_else(|e| e.into_inner());
712 (t.turns, t.cost_usd)
713 };
714
715 let mut state = shared.lock_state();
716 match outcome {
717 Ok(Ok(())) => {}
718 Ok(Err(message)) => {
719 state.push_entry(EntryBody::Error { message });
720 }
721 Err(payload) => {
722 let message = panic_message(payload);
723 state.push_entry(EntryBody::Error { message });
724 }
725 }
726 state.push_entry(EntryBody::Idle { turns, cost_usd });
727 state.busy = false;
728 shared.log_cv.notify_all();
729 }
730}
731
732fn format_prompt(text: &str, attachments: &[Attachment]) -> String {
733 let mut out = text.to_string();
734 for att in attachments {
735 out.push_str("\n\nResearch report ");
736 out.push_str(&att.run);
737 out.push_str(":\n");
738 out.push_str(&att.text);
739 }
740 out
741}
742
743pub(crate) fn model_supports_effort(model: &str) -> bool {
744 blyte_provider::detect_provider_kind(Some(model)) == blyte_provider::ProviderKind::Gemini
745}
746
747fn parse_model_and_effort(model: &str) -> (String, Option<String>) {
748 let trimmed = model.trim();
749 if model_supports_effort(trimmed) {
750 blyte_provider::gemini::split_effort(trimmed)
751 } else {
752 (trimmed.to_string(), None)
753 }
754}
755
756fn panic_message(payload: Box<dyn std::any::Any + Send>) -> String {
757 if let Some(s) = payload.downcast_ref::<&str>() {
758 (*s).to_string()
759 } else if let Some(s) = payload.downcast_ref::<String>() {
760 s.clone()
761 } else {
762 "runner panicked".to_string()
763 }
764}
765
766fn now_secs() -> u64 {
767 SystemTime::now()
768 .duration_since(UNIX_EPOCH)
769 .map(|d| d.as_secs())
770 .unwrap_or(0)
771}
772
773fn now_millis() -> u128 {
774 SystemTime::now()
775 .duration_since(UNIX_EPOCH)
776 .map(|d| d.as_millis())
777 .unwrap_or(0)
778}
779
780fn new_session_prefix() -> String {
781 let seq = SESSION_COUNTER.fetch_add(1, Ordering::Relaxed);
782 format!("r{}-{}-{}", now_millis(), std::process::id(), seq)
783}