Skip to main content

blyte_cli/
session.rs

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