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 lock_state(&self) -> MutexGuard<'_, SessionState> {
349        self.state.lock().unwrap_or_else(|e| e.into_inner())
350    }
351}
352
353struct SessionGuard {
354    shared: Arc<Shared>,
355}
356
357impl Drop for SessionGuard {
358    fn drop(&mut self) {
359        let mut state = self.shared.lock_state();
360        state.closed = true;
361        state.deny_all_pending();
362        self.shared.work_cv.notify_all();
363        self.shared.log_cv.notify_all();
364        self.shared.approval_cv.notify_all();
365    }
366}
367
368#[derive(Clone)]
369pub struct Session {
370    guard: Arc<SessionGuard>,
371}
372
373struct TurnTotals {
374    turns: u32,
375    cost_usd: Option<f64>,
376}
377
378impl Session {
379    pub fn start(runner: Box<dyn PromptRunner>, model: String) -> Session {
380        Self::start_with(model, |_| runner)
381    }
382
383    pub fn start_with<F>(model: String, build_runner: F) -> Session
384    where
385        F: FnOnce(Arc<SurfaceApprover>) -> Box<dyn PromptRunner>,
386    {
387        let (base_model, effort) = parse_model_and_effort(&model);
388        let shared = Arc::new(Shared {
389            state: Mutex::new(SessionState {
390                entries: Vec::new(),
391                queue: VecDeque::new(),
392                session_prefix: new_session_prefix(),
393                request_seq: 0,
394                model: base_model,
395                effort,
396                busy: false,
397                closed: false,
398                approvals: HashMap::new(),
399                next_approval_id: 0,
400            }),
401            log_cv: Condvar::new(),
402            work_cv: Condvar::new(),
403            approval_cv: Condvar::new(),
404        });
405        let approver = Arc::new(SurfaceApprover {
406            shared: Arc::clone(&shared),
407        });
408        let runner = build_runner(approver);
409        let worker_shared = Arc::clone(&shared);
410        std::thread::spawn(move || worker_loop(runner, worker_shared));
411        Session {
412            guard: Arc::new(SessionGuard { shared }),
413        }
414    }
415
416    pub fn approver(&self) -> Arc<SurfaceApprover> {
417        Arc::new(SurfaceApprover {
418            shared: Arc::clone(&self.guard.shared),
419        })
420    }
421
422    pub fn answer_approval(&self, id: &str, answer: ApprovalAnswer) -> Result<u64, AnswerError> {
423        let mut state = self.guard.shared.lock_state();
424        let command = match state.approvals.get_mut(id) {
425            None => return Err(AnswerError::NotFound),
426            Some(record) if record.answer.is_some() => return Err(AnswerError::AlreadyAnswered),
427            Some(record) => {
428                record.answer = Some(answer);
429                record.command.clone()
430            }
431        };
432        let seq = state.push_entry(EntryBody::ApprovalAnswered {
433            id: id.to_string(),
434            command,
435            answer: answer.as_str().to_string(),
436        });
437        self.guard.shared.approval_cv.notify_all();
438        self.guard.shared.log_cv.notify_all();
439        Ok(seq)
440    }
441
442    pub fn stop_run(&self) {
443        let mut state = self.guard.shared.lock_state();
444        if state.deny_all_pending() {
445            self.guard.shared.approval_cv.notify_all();
446            self.guard.shared.log_cv.notify_all();
447        }
448    }
449
450    pub fn submit(&self, text: &str, attachments: Vec<Attachment>) -> Result<u64, String> {
451        if text.trim().is_empty() {
452            return Err("a message needs text".to_string());
453        }
454        let reports = attachments.iter().map(|a| a.run.clone()).collect();
455        let full_prompt = format_prompt(text, &attachments);
456        let mut state = self.guard.shared.lock_state();
457        let queued = state.busy || !state.queue.is_empty();
458        let seq = state.push_entry(EntryBody::UserMessage {
459            text: text.to_string(),
460            reports,
461            queued,
462        });
463        let request_id = state.next_request_id();
464        state.queue.push_back(QueuedMessage {
465            request_id,
466            prompt: full_prompt,
467        });
468        self.guard.shared.work_cv.notify_one();
469        self.guard.shared.log_cv.notify_all();
470        Ok(seq)
471    }
472
473    pub fn entries_after(&self, after: u64, wait: Duration) -> Vec<Entry> {
474        let mut state = self.guard.shared.lock_state();
475        if (state.entries.len() as u64) <= after && !wait.is_zero() {
476            let deadline = Instant::now() + wait;
477            while (state.entries.len() as u64) <= after {
478                let remaining = deadline.saturating_duration_since(Instant::now());
479                if remaining.is_zero() {
480                    break;
481                }
482                let (guard, _) = self
483                    .guard
484                    .shared
485                    .log_cv
486                    .wait_timeout(state, remaining)
487                    .unwrap_or_else(|e| e.into_inner());
488                state = guard;
489            }
490        }
491        let start = usize::try_from(after).unwrap_or(usize::MAX);
492        if start >= state.entries.len() {
493            Vec::new()
494        } else {
495            state.entries[start..].to_vec()
496        }
497    }
498
499    pub fn info(&self) -> SessionInfo {
500        let state = self.guard.shared.lock_state();
501        SessionInfo {
502            effort_supported: model_supports_effort(&state.model),
503            model: state.model.clone(),
504            effort: state.effort.clone(),
505            busy: state.busy,
506            queued: state.queue.len(),
507            last_seq: state.entries.len() as u64,
508        }
509    }
510
511    pub fn set_model(&self, model: &str) -> Result<(), String> {
512        let trimmed = model.trim();
513        if trimmed.is_empty() {
514            return Err("model cannot be empty".to_string());
515        }
516        let mut state = self.guard.shared.lock_state();
517        let supported = model_supports_effort(trimmed);
518        if supported {
519            let (base, parsed_effort) = blyte_provider::gemini::split_effort(trimmed);
520            state.model = base.clone();
521            state.push_entry(EntryBody::ModelChanged { model: base });
522            if let Some(new_effort) = parsed_effort {
523                if state.effort.as_deref() != Some(new_effort.as_str()) {
524                    state.effort = Some(new_effort.clone());
525                    state.push_entry(EntryBody::EffortChanged {
526                        effort: Some(new_effort),
527                    });
528                }
529            }
530        } else {
531            state.model = trimmed.to_string();
532            state.push_entry(EntryBody::ModelChanged {
533                model: trimmed.to_string(),
534            });
535            if state.effort.is_some() {
536                state.effort = None;
537                state.push_entry(EntryBody::EffortChanged { effort: None });
538            }
539        }
540        self.guard.shared.log_cv.notify_all();
541        Ok(())
542    }
543
544    pub fn set_effort(&self, effort: Option<&str>) -> Result<(), String> {
545        let normalized = match effort {
546            None => None,
547            Some("low") => Some("low".to_string()),
548            Some("medium") => Some("medium".to_string()),
549            Some("high") => Some("high".to_string()),
550            Some(_) => return Err("effort must be low, medium or high".to_string()),
551        };
552        let mut state = self.guard.shared.lock_state();
553        if !model_supports_effort(&state.model) {
554            return Err(format!("{} does not take an effort setting", state.model));
555        }
556        state.effort = normalized.clone();
557        state.push_entry(EntryBody::EffortChanged { effort: normalized });
558        self.guard.shared.log_cv.notify_all();
559        Ok(())
560    }
561
562    pub fn record_decision(
563        &self,
564        run: &str,
565        action: &str,
566        note: Option<&str>,
567        orchestrator_message: Option<&str>,
568    ) -> Result<u64, String> {
569        if let Some(msg) = orchestrator_message {
570            if msg.trim().is_empty() {
571                return Err("a message needs text".to_string());
572            }
573        }
574        let mut state = self.guard.shared.lock_state();
575        let seq = state.push_entry(EntryBody::Decision {
576            run: run.to_string(),
577            action: action.to_string(),
578            note: note.map(str::to_string),
579        });
580        if let Some(msg) = orchestrator_message {
581            let queued = state.busy || !state.queue.is_empty();
582            state.push_entry(EntryBody::UserMessage {
583                text: msg.to_string(),
584                reports: Vec::new(),
585                queued,
586            });
587            let request_id = state.next_request_id();
588            state.queue.push_back(QueuedMessage {
589                request_id,
590                prompt: msg.to_string(),
591            });
592            self.guard.shared.work_cv.notify_one();
593        }
594        self.guard.shared.log_cv.notify_all();
595        Ok(seq)
596    }
597}
598
599struct RequestGuard;
600
601impl RequestGuard {
602    fn enter(request_id: String) -> Self {
603        blyte_agent::tools::set_blyte_request(Some(request_id));
604        Self
605    }
606}
607
608impl Drop for RequestGuard {
609    fn drop(&mut self) {
610        blyte_agent::tools::set_blyte_request(None);
611    }
612}
613
614fn worker_loop(mut runner: Box<dyn PromptRunner>, shared: Arc<Shared>) {
615    loop {
616        let (msg, effective_model) = {
617            let mut state = shared.lock_state();
618            loop {
619                if state.closed {
620                    return;
621                }
622                if let Some(msg) = state.queue.pop_front() {
623                    state.busy = true;
624                    let model = state.effective_model();
625                    break (msg, model);
626                }
627                state = shared
628                    .work_cv
629                    .wait(state)
630                    .unwrap_or_else(|e| e.into_inner());
631            }
632        };
633
634        let totals = Mutex::new(TurnTotals {
635            turns: 0,
636            cost_usd: Some(0.0),
637        });
638        let emit_shared = Arc::clone(&shared);
639        let emit = |body: EntryBody| {
640            if let EntryBody::Turn { cost_usd, .. } = &body {
641                let mut t = totals.lock().unwrap_or_else(|e| e.into_inner());
642                t.turns += 1;
643                match (t.cost_usd, cost_usd) {
644                    (Some(acc), Some(c)) => t.cost_usd = Some(acc + c),
645                    _ => t.cost_usd = None,
646                }
647            }
648            let mut state = emit_shared.lock_state();
649            state.push_entry(body);
650            emit_shared.log_cv.notify_all();
651        };
652
653        let outcome = catch_unwind(AssertUnwindSafe(|| {
654            let _req_guard = RequestGuard::enter(msg.request_id);
655            runner.run(&msg.prompt, &effective_model, &emit)
656        }));
657
658        let (turns, cost_usd) = {
659            let t = totals.lock().unwrap_or_else(|e| e.into_inner());
660            (t.turns, t.cost_usd)
661        };
662
663        let mut state = shared.lock_state();
664        match outcome {
665            Ok(Ok(())) => {}
666            Ok(Err(message)) => {
667                state.push_entry(EntryBody::Error { message });
668            }
669            Err(payload) => {
670                let message = panic_message(payload);
671                state.push_entry(EntryBody::Error { message });
672            }
673        }
674        state.push_entry(EntryBody::Idle { turns, cost_usd });
675        state.busy = false;
676        shared.log_cv.notify_all();
677    }
678}
679
680fn format_prompt(text: &str, attachments: &[Attachment]) -> String {
681    let mut out = text.to_string();
682    for att in attachments {
683        out.push_str("\n\nResearch report ");
684        out.push_str(&att.run);
685        out.push_str(":\n");
686        out.push_str(&att.text);
687    }
688    out
689}
690
691pub(crate) fn model_supports_effort(model: &str) -> bool {
692    blyte_provider::detect_provider_kind(Some(model)) == blyte_provider::ProviderKind::Gemini
693}
694
695fn parse_model_and_effort(model: &str) -> (String, Option<String>) {
696    let trimmed = model.trim();
697    if model_supports_effort(trimmed) {
698        blyte_provider::gemini::split_effort(trimmed)
699    } else {
700        (trimmed.to_string(), None)
701    }
702}
703
704fn panic_message(payload: Box<dyn std::any::Any + Send>) -> String {
705    if let Some(s) = payload.downcast_ref::<&str>() {
706        (*s).to_string()
707    } else if let Some(s) = payload.downcast_ref::<String>() {
708        s.clone()
709    } else {
710        "runner panicked".to_string()
711    }
712}
713
714fn now_secs() -> u64 {
715    SystemTime::now()
716        .duration_since(UNIX_EPOCH)
717        .map(|d| d.as_secs())
718        .unwrap_or(0)
719}
720
721fn now_millis() -> u128 {
722    SystemTime::now()
723        .duration_since(UNIX_EPOCH)
724        .map(|d| d.as_millis())
725        .unwrap_or(0)
726}
727
728fn new_session_prefix() -> String {
729    let seq = SESSION_COUNTER.fetch_add(1, Ordering::Relaxed);
730    format!("r{}-{}-{}", now_millis(), std::process::id(), seq)
731}