Skip to main content

blyte_cli/
session.rs

1use std::collections::{HashMap, VecDeque};
2use std::fs::{File, OpenOptions};
3use std::io::{ErrorKind, Write};
4use std::panic::{catch_unwind, AssertUnwindSafe};
5use std::path::{Path, PathBuf};
6use std::sync::atomic::{AtomicU64, Ordering};
7use std::sync::{Arc, Condvar, Mutex, MutexGuard};
8use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
9
10pub const RESTART_NOTICE_TEXT: &str =
11    "blyte restarted: the entries above are from before; the model does not remember them";
12
13static SESSION_COUNTER: AtomicU64 = AtomicU64::new(0);
14
15#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
16pub struct Entry {
17    pub seq: u64,
18    pub ts: u64,
19    #[serde(flatten)]
20    pub body: EntryBody,
21}
22
23#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
24#[serde(tag = "kind", rename_all = "snake_case")]
25pub enum EntryBody {
26    UserMessage {
27        text: String,
28        reports: Vec<String>,
29        queued: bool,
30    },
31    Turn {
32        n: u32,
33        text: String,
34        input_tokens: u64,
35        output_tokens: u64,
36        cost_usd: Option<f64>,
37    },
38    ToolStarted {
39        name: String,
40        input: String,
41    },
42    ToolFinished {
43        name: String,
44        summary: String,
45        is_error: bool,
46    },
47    Retry {
48        attempt: u32,
49        max: u32,
50        wait_ms: u64,
51        reason: String,
52    },
53    Error {
54        message: String,
55    },
56    Idle {
57        turns: u32,
58        cost_usd: Option<f64>,
59    },
60    ModelChanged {
61        model: String,
62    },
63    EffortChanged {
64        effort: Option<String>,
65    },
66    Decision {
67        run: String,
68        action: String,
69        note: Option<String>,
70    },
71    ApprovalRequested {
72        id: String,
73        command: String,
74        reason: String,
75    },
76    ApprovalAnswered {
77        id: String,
78        command: String,
79        answer: String,
80    },
81}
82
83#[derive(Clone, Copy, Debug, PartialEq, Eq)]
84pub enum ApprovalAnswer {
85    Yes,
86    No,
87}
88
89impl ApprovalAnswer {
90    pub fn as_str(self) -> &'static str {
91        match self {
92            ApprovalAnswer::Yes => "yes",
93            ApprovalAnswer::No => "no",
94        }
95    }
96
97    fn to_approval(self) -> blyte_agent::approval::Approval {
98        match self {
99            ApprovalAnswer::Yes => blyte_agent::approval::Approval::Approved,
100            ApprovalAnswer::No => blyte_agent::approval::Approval::Denied,
101        }
102    }
103}
104
105#[derive(Clone, Debug, PartialEq, Eq)]
106pub enum AnswerError {
107    NotFound,
108    AlreadyAnswered,
109}
110
111pub struct SurfaceApprover {
112    shared: Arc<Shared>,
113}
114
115impl blyte_agent::approval::Approver for SurfaceApprover {
116    fn ask(&self, command: &str, reason: &str) -> blyte_agent::approval::Approval {
117        let mut state = self.shared.lock_state();
118        if state.closed {
119            return blyte_agent::approval::Approval::Denied;
120        }
121        state.next_approval_id += 1;
122        let order = state.next_approval_id;
123        let id = format!("approval-{order}");
124        state.approvals.insert(
125            id.clone(),
126            ApprovalRecord {
127                order,
128                command: command.to_string(),
129                answer: None,
130            },
131        );
132        state.push_entry(EntryBody::ApprovalRequested {
133            id: id.clone(),
134            command: command.to_string(),
135            reason: reason.to_string(),
136        });
137        self.shared.log_cv.notify_all();
138
139        loop {
140            if let Some(answer) = state.approvals.get(&id).and_then(|r| r.answer) {
141                return answer.to_approval();
142            }
143            if state.closed {
144                return blyte_agent::approval::Approval::Denied;
145            }
146            state = self
147                .shared
148                .approval_cv
149                .wait(state)
150                .unwrap_or_else(|e| e.into_inner());
151        }
152    }
153}
154
155#[derive(Clone, Debug, PartialEq, Eq)]
156pub struct Attachment {
157    pub run: String,
158    pub text: String,
159}
160
161#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
162pub struct SessionInfo {
163    pub model: String,
164    pub effort: Option<String>,
165    pub effort_supported: bool,
166    pub busy: bool,
167    pub queued: usize,
168    pub last_seq: u64,
169}
170
171pub trait PromptRunner: Send + 'static {
172    fn run(
173        &mut self,
174        prompt: &str,
175        model: &str,
176        emit: &(dyn Fn(EntryBody) + Sync),
177    ) -> Result<(), String>;
178}
179
180pub struct AgentRunner {
181    repl: crate::repl::ReplSession,
182    approver: Arc<dyn blyte_agent::approval::Approver>,
183}
184
185impl AgentRunner {
186    pub fn new(
187        config: &crate::repl::ReplConfig,
188        approver: Arc<dyn blyte_agent::approval::Approver>,
189    ) -> Self {
190        let mut cfg = config.clone();
191        cfg.converse = true;
192        let repl = crate::repl::ReplSession::try_new_with_approver(&cfg, Some(approver.clone()))
193            .expect("failed to initialize REPL session");
194        Self { repl, approver }
195    }
196}
197
198impl PromptRunner for AgentRunner {
199    fn run(
200        &mut self,
201        prompt: &str,
202        model: &str,
203        emit: &(dyn Fn(EntryBody) + Sync),
204    ) -> Result<(), String> {
205        self.repl.model = model.to_string();
206        self.repl.state.brief.goal = prompt.to_string();
207        if let Some(ref gate) = self.repl.gate {
208            self.repl.state.brief.verification_cmd = gate.clone();
209        }
210        let task_config = self.repl.task_config_for_prompt(prompt);
211        let pricing = blyte_provider::pricing(model);
212        let on_event = |event: &blyte_agent::run::Event<'_>| match event {
213            blyte_agent::run::Event::Turn { n, text, usage } => {
214                emit(EntryBody::Turn {
215                    n: *n,
216                    text: (*text).to_string(),
217                    input_tokens: usage.input + usage.cached,
218                    output_tokens: usage.output + usage.thinking,
219                    cost_usd: pricing.map(|p| p.cost(usage)),
220                });
221            }
222            blyte_agent::run::Event::ToolStart { name, input } => {
223                emit(EntryBody::ToolStarted {
224                    name: (*name).to_string(),
225                    input: input.clone(),
226                });
227            }
228            blyte_agent::run::Event::Tool {
229                name,
230                summary,
231                is_error,
232                ..
233            } => {
234                emit(EntryBody::ToolFinished {
235                    name: (*name).to_string(),
236                    summary: summary.clone(),
237                    is_error: *is_error,
238                });
239            }
240            blyte_agent::run::Event::Retry {
241                attempt,
242                max,
243                wait_ms,
244                reason,
245            } => {
246                emit(EntryBody::Retry {
247                    attempt: *attempt,
248                    max: *max,
249                    wait_ms: *wait_ms,
250                    reason: reason.clone(),
251                });
252            }
253            _ => {}
254        };
255        let (outcome, _) = crate::task_runner::run_task_with_approver(
256            &task_config,
257            &mut self.repl.state,
258            Some(self.approver.clone()),
259            &on_event,
260        )?;
261        match outcome {
262            blyte_agent::run::Outcome::Verified | blyte_agent::run::Outcome::Finished => Ok(()),
263            blyte_agent::run::Outcome::BudgetExhausted => Err("budget exhausted".to_string()),
264            blyte_agent::run::Outcome::GateFailed => Err("gate failed".to_string()),
265            blyte_agent::run::Outcome::Blocked(msg) | blyte_agent::run::Outcome::Error(msg) => {
266                Err(msg)
267            }
268        }
269    }
270}
271
272struct ApprovalRecord {
273    order: u64,
274    command: String,
275    answer: Option<ApprovalAnswer>,
276}
277
278struct QueuedMessage {
279    request_id: String,
280    prompt: String,
281}
282
283struct EntryLog {
284    path: PathBuf,
285    file: File,
286    fail_writes_with: Option<String>,
287}
288
289impl EntryLog {
290    fn open(path: PathBuf, err: &mut dyn Write) -> Result<(Self, Vec<Entry>), String> {
291        let (entries, truncate_to, needs_newline) = load_entries_file(&path, err)?;
292        if let Some(parent) = path.parent() {
293            if !parent.as_os_str().is_empty() {
294                std::fs::create_dir_all(parent)
295                    .map_err(|e| format!("failed to create directory {}: {e}", parent.display()))?;
296            }
297        }
298        if let Some(len) = truncate_to {
299            let f = OpenOptions::new()
300                .write(true)
301                .open(&path)
302                .map_err(|e| format!("failed to truncate {}: {e}", path.display()))?;
303            f.set_len(len)
304                .map_err(|e| format!("failed to truncate {}: {e}", path.display()))?;
305        }
306        let mut file = OpenOptions::new()
307            .create(true)
308            .append(true)
309            .open(&path)
310            .map_err(|e| format!("failed to open {}: {e}", path.display()))?;
311        if needs_newline {
312            file.write_all(b"\n")
313                .and_then(|_| file.flush())
314                .map_err(|e| format!("failed to write to {}: {e}", path.display()))?;
315        }
316        Ok((
317            Self {
318                path,
319                file,
320                fail_writes_with: None,
321            },
322            entries,
323        ))
324    }
325
326    fn append(&mut self, entry: &Entry) -> Result<(), String> {
327        let mut line = match serde_json::to_string(entry) {
328            Ok(s) => s,
329            Err(e) => {
330                eprintln!(
331                    "blyte: failed to serialize entry for {}: {e}",
332                    self.path.display()
333                );
334                return Err(e.to_string());
335            }
336        };
337        line.push('\n');
338        let write_result = match &self.fail_writes_with {
339            Some(reason) => Err(std::io::Error::other(reason.clone())),
340            None => self
341                .file
342                .write_all(line.as_bytes())
343                .and_then(|_| self.file.flush()),
344        };
345        if let Err(e) = write_result {
346            eprintln!("blyte: failed to write to {}: {e}", self.path.display());
347            return Err(e.to_string());
348        }
349        Ok(())
350    }
351}
352
353fn gap_notice_message(missing: u64) -> String {
354    if missing == 1 {
355        "blyte: 1 entry was not saved here".to_string()
356    } else {
357        format!("blyte: {missing} entries were not saved here")
358    }
359}
360
361fn load_entries_file(
362    path: &Path,
363    err: &mut dyn Write,
364) -> Result<(Vec<Entry>, Option<u64>, bool), String> {
365    let bytes = match std::fs::read(path) {
366        Ok(b) => b,
367        Err(e) if e.kind() == ErrorKind::NotFound => return Ok((Vec::new(), None, false)),
368        Err(e) => return Err(format!("failed to read {}: {e}", path.display())),
369    };
370    if bytes.is_empty() {
371        return Ok((Vec::new(), None, false));
372    }
373
374    let mut entries = Vec::new();
375    let mut prev_seq = 0u64;
376    let mut pos = 0usize;
377    let mut line_no = 0usize;
378    let mut truncate_to = None;
379    let mut valid_end = 0usize;
380
381    while pos < bytes.len() {
382        line_no += 1;
383        let start = pos;
384        let end = match bytes[pos..].iter().position(|&b| b == b'\n') {
385            Some(rel) => pos + rel + 1,
386            None => bytes.len(),
387        };
388        // A cut-off write never ends in a newline; a complete bad line is corruption.
389        let is_last = end == bytes.len() && !bytes[start..end].ends_with(b"\n");
390        let line_slice = &bytes[start..end];
391        let parsed = std::str::from_utf8(line_slice)
392            .map_err(|e| e.to_string())
393            .and_then(|s| serde_json::from_str::<Entry>(s).map_err(|e| e.to_string()));
394        match parsed {
395            Ok(entry) => {
396                if entry.seq <= prev_seq {
397                    return Err(format!(
398                        "invalid entry in {} at line {}: seq {} does not follow seq {}",
399                        path.display(),
400                        line_no,
401                        entry.seq,
402                        prev_seq
403                    ));
404                }
405                if entry.seq > prev_seq + 1 {
406                    let missing = entry.seq - prev_seq - 1;
407                    entries.push(Entry {
408                        seq: prev_seq + 1,
409                        ts: entry.ts,
410                        body: EntryBody::Error {
411                            message: gap_notice_message(missing),
412                        },
413                    });
414                }
415                prev_seq = entry.seq;
416                entries.push(entry);
417                valid_end = end;
418            }
419            Err(reason) => {
420                if is_last {
421                    let _ = writeln!(
422                        err,
423                        "blyte: dropping truncated last line in {} at line {}: {}",
424                        path.display(),
425                        line_no,
426                        reason
427                    );
428                    let _ = err.flush();
429                    truncate_to = Some(start as u64);
430                } else {
431                    return Err(format!(
432                        "invalid entry in {} at line {}: {}",
433                        path.display(),
434                        line_no,
435                        reason
436                    ));
437                }
438            }
439        }
440        pos = end;
441    }
442
443    let needs_newline = valid_end > 0 && bytes[valid_end - 1] != b'\n';
444    Ok((entries, truncate_to, needs_newline))
445}
446
447fn max_approval_id(entries: &[Entry]) -> u64 {
448    entries
449        .iter()
450        .filter_map(|e| match &e.body {
451            EntryBody::ApprovalRequested { id, .. } | EntryBody::ApprovalAnswered { id, .. } => {
452                id.strip_prefix("approval-")?.parse::<u64>().ok()
453            }
454            _ => None,
455        })
456        .max()
457        .unwrap_or(0)
458}
459
460struct SessionState {
461    entries: Vec<Entry>,
462    last_seq: u64,
463    log: Option<EntryLog>,
464    write_failure_noticed: bool,
465    queue: VecDeque<QueuedMessage>,
466    session_prefix: String,
467    request_seq: u64,
468    model: String,
469    effort: Option<String>,
470    busy: bool,
471    closed: bool,
472    approvals: HashMap<String, ApprovalRecord>,
473    next_approval_id: u64,
474}
475
476impl SessionState {
477    fn push_entry(&mut self, body: EntryBody) -> u64 {
478        self.last_seq += 1;
479        let seq = self.last_seq;
480        let ts = now_secs();
481        let entry = Entry { seq, ts, body };
482        let append_failure = self
483            .log
484            .as_mut()
485            .and_then(|log| log.append(&entry).err().map(|err| (log.path.clone(), err)));
486        self.entries.push(entry);
487        if let Some((path, err)) = append_failure {
488            if !self.write_failure_noticed {
489                self.write_failure_noticed = true;
490                self.push_entry(EntryBody::Error {
491                    message: format!(
492                        "blyte: could not save this session's entries to {}: {}; entries from here on may be missing after a restart",
493                        path.display(),
494                        err
495                    ),
496                });
497            }
498        }
499        seq
500    }
501
502    fn next_request_id(&mut self) -> String {
503        self.request_seq += 1;
504        format!("{}-{}", self.session_prefix, self.request_seq)
505    }
506
507    fn effective_model(&self) -> String {
508        match &self.effort {
509            Some(effort) if model_supports_effort(&self.model) => {
510                format!("{}-{}", self.model, effort)
511            }
512            _ => self.model.clone(),
513        }
514    }
515
516    fn deny_all_pending(&mut self) -> bool {
517        let mut pending: Vec<(u64, String, String)> = self
518            .approvals
519            .iter()
520            .filter(|(_, record)| record.answer.is_none())
521            .map(|(id, record)| (record.order, id.clone(), record.command.clone()))
522            .collect();
523        if pending.is_empty() {
524            return false;
525        }
526        pending.sort_by_key(|(order, _, _)| *order);
527        for (_, id, command) in pending {
528            if let Some(record) = self.approvals.get_mut(&id) {
529                record.answer = Some(ApprovalAnswer::No);
530            }
531            self.push_entry(EntryBody::ApprovalAnswered {
532                id,
533                command,
534                answer: ApprovalAnswer::No.as_str().to_string(),
535            });
536        }
537        true
538    }
539}
540
541type ActivityHook = Arc<dyn Fn(Option<&str>) + Send + Sync>;
542
543struct Shared {
544    state: Mutex<SessionState>,
545    activity_hook: Mutex<Option<ActivityHook>>,
546    log_cv: Condvar,
547    work_cv: Condvar,
548    approval_cv: Condvar,
549}
550
551impl Shared {
552    fn new(model: String, effort: Option<String>) -> Self {
553        Self {
554            state: Mutex::new(SessionState {
555                entries: Vec::new(),
556                last_seq: 0,
557                log: None,
558                write_failure_noticed: false,
559                queue: VecDeque::new(),
560                session_prefix: new_session_prefix(),
561                request_seq: 0,
562                model,
563                effort,
564                busy: false,
565                closed: false,
566                approvals: HashMap::new(),
567                next_approval_id: 0,
568            }),
569            activity_hook: Mutex::new(None),
570            log_cv: Condvar::new(),
571            work_cv: Condvar::new(),
572            approval_cv: Condvar::new(),
573        }
574    }
575
576    fn new_with_log(
577        model: String,
578        effort: Option<String>,
579        log_path: Option<PathBuf>,
580        err: &mut dyn Write,
581    ) -> Result<Self, String> {
582        let (log, entries) = match log_path {
583            Some(path) => {
584                let (log, entries) = EntryLog::open(path, err)?;
585                (Some(log), entries)
586            }
587            None => (None, Vec::new()),
588        };
589        let last_seq = entries.iter().map(|e| e.seq).max().unwrap_or(0);
590        let next_approval_id = max_approval_id(&entries);
591        let had_entries = !entries.is_empty();
592        let mut state = SessionState {
593            entries,
594            last_seq,
595            log,
596            write_failure_noticed: false,
597            queue: VecDeque::new(),
598            session_prefix: new_session_prefix(),
599            request_seq: 0,
600            model,
601            effort,
602            busy: false,
603            closed: false,
604            approvals: HashMap::new(),
605            next_approval_id,
606        };
607        if had_entries {
608            state.push_entry(EntryBody::Error {
609                message: RESTART_NOTICE_TEXT.to_string(),
610            });
611        }
612        Ok(Self {
613            state: Mutex::new(state),
614            activity_hook: Mutex::new(None),
615            log_cv: Condvar::new(),
616            work_cv: Condvar::new(),
617            approval_cv: Condvar::new(),
618        })
619    }
620
621    fn lock_state(&self) -> MutexGuard<'_, SessionState> {
622        self.state.lock().unwrap_or_else(|e| e.into_inner())
623    }
624}
625
626struct SessionGuard {
627    shared: Arc<Shared>,
628}
629
630impl Drop for SessionGuard {
631    fn drop(&mut self) {
632        let mut state = self.shared.lock_state();
633        state.closed = true;
634        state.deny_all_pending();
635        self.shared.work_cv.notify_all();
636        self.shared.log_cv.notify_all();
637        self.shared.approval_cv.notify_all();
638    }
639}
640
641#[derive(Clone)]
642pub struct Session {
643    guard: Arc<SessionGuard>,
644}
645
646struct TurnTotals {
647    turns: u32,
648    cost_usd: Option<f64>,
649}
650
651impl Session {
652    #[allow(clippy::type_complexity)]
653    pub fn set_activity_hook(&self, hook: Box<dyn Fn(Option<&str>) + Send + Sync>) {
654        let mut slot = self
655            .guard
656            .shared
657            .activity_hook
658            .lock()
659            .unwrap_or_else(|e| e.into_inner());
660        *slot = Some(Arc::from(hook));
661    }
662
663    pub fn start(runner: Box<dyn PromptRunner>, model: String) -> Session {
664        Self::start_with(model, |_| runner)
665    }
666
667    pub fn start_with<F>(model: String, build_runner: F) -> Session
668    where
669        F: FnOnce(Arc<SurfaceApprover>) -> Box<dyn PromptRunner>,
670    {
671        let (base_model, effort) = parse_model_and_effort(&model);
672        let shared = Arc::new(Shared::new(base_model, effort));
673        let approver = Arc::new(SurfaceApprover {
674            shared: Arc::clone(&shared),
675        });
676        let runner = build_runner(approver);
677        let worker_shared = Arc::clone(&shared);
678        std::thread::spawn(move || worker_loop(runner, worker_shared));
679        Session {
680            guard: Arc::new(SessionGuard { shared }),
681        }
682    }
683
684    pub fn start_with_log<F>(
685        model: String,
686        log_path: Option<PathBuf>,
687        build_runner: F,
688    ) -> Result<Session, String>
689    where
690        F: FnOnce(Arc<SurfaceApprover>) -> Box<dyn PromptRunner>,
691    {
692        let mut stderr = std::io::stderr();
693        Self::start_with_log_io(model, log_path, &mut stderr, build_runner)
694    }
695
696    pub fn start_with_log_io<F>(
697        model: String,
698        log_path: Option<PathBuf>,
699        err: &mut dyn Write,
700        build_runner: F,
701    ) -> Result<Session, String>
702    where
703        F: FnOnce(Arc<SurfaceApprover>) -> Box<dyn PromptRunner>,
704    {
705        let (base_model, effort) = parse_model_and_effort(&model);
706        let shared = Arc::new(Shared::new_with_log(base_model, effort, log_path, err)?);
707        let approver = Arc::new(SurfaceApprover {
708            shared: Arc::clone(&shared),
709        });
710        let runner = build_runner(approver);
711        let worker_shared = Arc::clone(&shared);
712        std::thread::spawn(move || worker_loop(runner, worker_shared));
713        Ok(Session {
714            guard: Arc::new(SessionGuard { shared }),
715        })
716    }
717
718    #[doc(hidden)]
719    pub fn start_paused(
720        runner: Box<dyn PromptRunner>,
721        model: String,
722    ) -> (Session, std::sync::mpsc::Sender<()>) {
723        let (base_model, effort) = parse_model_and_effort(&model);
724        let shared = Arc::new(Shared::new(base_model, effort));
725        let (tx, rx) = std::sync::mpsc::channel();
726        let worker_shared = Arc::clone(&shared);
727        std::thread::spawn(move || {
728            if rx.recv().is_ok() {
729                worker_loop(runner, worker_shared);
730            }
731        });
732        (
733            Session {
734                guard: Arc::new(SessionGuard { shared }),
735            },
736            tx,
737        )
738    }
739
740    #[doc(hidden)]
741    pub fn fail_log_writes(&self, reason: &str) {
742        let mut state = self.guard.shared.lock_state();
743        if let Some(log) = &mut state.log {
744            log.fail_writes_with = Some(reason.to_string());
745        }
746    }
747
748    pub fn approver(&self) -> Arc<SurfaceApprover> {
749        Arc::new(SurfaceApprover {
750            shared: Arc::clone(&self.guard.shared),
751        })
752    }
753
754    pub fn answer_approval(&self, id: &str, answer: ApprovalAnswer) -> Result<u64, AnswerError> {
755        let mut state = self.guard.shared.lock_state();
756        let command = match state.approvals.get_mut(id) {
757            None => return Err(AnswerError::NotFound),
758            Some(record) if record.answer.is_some() => return Err(AnswerError::AlreadyAnswered),
759            Some(record) => {
760                record.answer = Some(answer);
761                record.command.clone()
762            }
763        };
764        let seq = state.push_entry(EntryBody::ApprovalAnswered {
765            id: id.to_string(),
766            command,
767            answer: answer.as_str().to_string(),
768        });
769        self.guard.shared.approval_cv.notify_all();
770        self.guard.shared.log_cv.notify_all();
771        Ok(seq)
772    }
773
774    pub fn stop_run(&self) {
775        let mut state = self.guard.shared.lock_state();
776        if state.deny_all_pending() {
777            self.guard.shared.approval_cv.notify_all();
778            self.guard.shared.log_cv.notify_all();
779        }
780    }
781
782    pub fn submit(&self, text: &str, attachments: Vec<Attachment>) -> Result<u64, String> {
783        if text.trim().is_empty() {
784            return Err("a message needs text".to_string());
785        }
786        let reports = attachments.iter().map(|a| a.run.clone()).collect();
787        let full_prompt = format_prompt(text, &attachments);
788        let mut state = self.guard.shared.lock_state();
789        let queued = state.busy || !state.queue.is_empty();
790        let seq = state.push_entry(EntryBody::UserMessage {
791            text: text.to_string(),
792            reports,
793            queued,
794        });
795        let request_id = state.next_request_id();
796        state.queue.push_back(QueuedMessage {
797            request_id,
798            prompt: full_prompt,
799        });
800        self.guard.shared.work_cv.notify_one();
801        self.guard.shared.log_cv.notify_all();
802        Ok(seq)
803    }
804
805    pub fn entries_after(&self, after: u64, wait: Duration) -> Vec<Entry> {
806        let mut state = self.guard.shared.lock_state();
807        if state.last_seq <= after && !wait.is_zero() {
808            let deadline = Instant::now() + wait;
809            while state.last_seq <= after {
810                let remaining = deadline.saturating_duration_since(Instant::now());
811                if remaining.is_zero() {
812                    break;
813                }
814                let (guard, _) = self
815                    .guard
816                    .shared
817                    .log_cv
818                    .wait_timeout(state, remaining)
819                    .unwrap_or_else(|e| e.into_inner());
820                state = guard;
821            }
822        }
823        state
824            .entries
825            .iter()
826            .filter(|e| e.seq > after)
827            .cloned()
828            .collect()
829    }
830
831    pub fn info(&self) -> SessionInfo {
832        let state = self.guard.shared.lock_state();
833        SessionInfo {
834            effort_supported: model_supports_effort(&state.model),
835            model: state.model.clone(),
836            effort: state.effort.clone(),
837            busy: state.busy,
838            queued: state.queue.len(),
839            last_seq: state.last_seq,
840        }
841    }
842
843    pub fn set_model(&self, model: &str) -> Result<(), String> {
844        let trimmed = model.trim();
845        if trimmed.is_empty() {
846            return Err("model cannot be empty".to_string());
847        }
848        let mut state = self.guard.shared.lock_state();
849        let supported = model_supports_effort(trimmed);
850        if supported {
851            let (base, parsed_effort) = blyte_provider::gemini::split_effort(trimmed);
852            state.model = base.clone();
853            state.push_entry(EntryBody::ModelChanged { model: base });
854            if let Some(new_effort) = parsed_effort {
855                if state.effort.as_deref() != Some(new_effort.as_str()) {
856                    state.effort = Some(new_effort.clone());
857                    state.push_entry(EntryBody::EffortChanged {
858                        effort: Some(new_effort),
859                    });
860                }
861            }
862        } else {
863            state.model = trimmed.to_string();
864            state.push_entry(EntryBody::ModelChanged {
865                model: trimmed.to_string(),
866            });
867            if state.effort.is_some() {
868                state.effort = None;
869                state.push_entry(EntryBody::EffortChanged { effort: None });
870            }
871        }
872        self.guard.shared.log_cv.notify_all();
873        Ok(())
874    }
875
876    pub fn set_effort(&self, effort: Option<&str>) -> Result<(), String> {
877        let normalized = match effort {
878            None => None,
879            Some("low") => Some("low".to_string()),
880            Some("medium") => Some("medium".to_string()),
881            Some("high") => Some("high".to_string()),
882            Some(_) => return Err("effort must be low, medium or high".to_string()),
883        };
884        let mut state = self.guard.shared.lock_state();
885        if !model_supports_effort(&state.model) {
886            return Err(format!("{} does not take an effort setting", state.model));
887        }
888        state.effort = normalized.clone();
889        state.push_entry(EntryBody::EffortChanged { effort: normalized });
890        self.guard.shared.log_cv.notify_all();
891        Ok(())
892    }
893
894    pub fn record_decision(
895        &self,
896        run: &str,
897        action: &str,
898        note: Option<&str>,
899        conversation_message: Option<&str>,
900    ) -> Result<u64, String> {
901        if let Some(msg) = conversation_message {
902            if msg.trim().is_empty() {
903                return Err("a message needs text".to_string());
904            }
905        }
906        let mut state = self.guard.shared.lock_state();
907        let seq = state.push_entry(EntryBody::Decision {
908            run: run.to_string(),
909            action: action.to_string(),
910            note: note.map(str::to_string),
911        });
912        if let Some(msg) = conversation_message {
913            let queued = state.busy || !state.queue.is_empty();
914            state.push_entry(EntryBody::UserMessage {
915                text: msg.to_string(),
916                reports: Vec::new(),
917                queued,
918            });
919            let request_id = state.next_request_id();
920            state.queue.push_back(QueuedMessage {
921                request_id,
922                prompt: msg.to_string(),
923            });
924            self.guard.shared.work_cv.notify_one();
925        }
926        self.guard.shared.log_cv.notify_all();
927        Ok(seq)
928    }
929
930    pub fn queue_for_request(&self, request_id: &str, text: &str) -> Result<u64, String> {
931        if text.trim().is_empty() {
932            return Err("a message needs text".to_string());
933        }
934        let mut state = self.guard.shared.lock_state();
935        let queued = state.busy || !state.queue.is_empty();
936        let seq = state.push_entry(EntryBody::UserMessage {
937            text: text.to_string(),
938            reports: Vec::new(),
939            queued,
940        });
941        state.queue.push_back(QueuedMessage {
942            request_id: request_id.to_string(),
943            prompt: text.to_string(),
944        });
945        self.guard.shared.work_cv.notify_one();
946        self.guard.shared.log_cv.notify_all();
947        Ok(seq)
948    }
949
950    pub fn record_error(&self, message: &str) -> u64 {
951        let mut state = self.guard.shared.lock_state();
952        let seq = state.push_entry(EntryBody::Error {
953            message: message.to_string(),
954        });
955        self.guard.shared.log_cv.notify_all();
956        seq
957    }
958}
959
960struct RequestGuard;
961
962impl RequestGuard {
963    fn enter(request_id: String) -> Self {
964        blyte_agent::tools::set_blyte_request(Some(request_id));
965        Self
966    }
967}
968
969impl Drop for RequestGuard {
970    fn drop(&mut self) {
971        blyte_agent::tools::set_blyte_request(None);
972    }
973}
974
975fn call_activity_hook(shared: &Shared, prompt: Option<&str>) {
976    let hook = {
977        let slot = shared
978            .activity_hook
979            .lock()
980            .unwrap_or_else(|e| e.into_inner());
981        slot.clone()
982    };
983    if let Some(hook) = hook {
984        if let Err(payload) = catch_unwind(AssertUnwindSafe(|| hook(prompt))) {
985            let msg = panic_message(payload).replace(['\r', '\n'], " ");
986            eprintln!("blyte: activity hook panicked: {msg}");
987        }
988    }
989}
990
991fn worker_loop(mut runner: Box<dyn PromptRunner>, shared: Arc<Shared>) {
992    loop {
993        let (msg, effective_model) = {
994            let mut state = shared.lock_state();
995            loop {
996                if state.closed {
997                    return;
998                }
999                if let Some(msg) = state.queue.pop_front() {
1000                    state.busy = true;
1001                    let model = state.effective_model();
1002                    break (msg, model);
1003                }
1004                state = shared
1005                    .work_cv
1006                    .wait(state)
1007                    .unwrap_or_else(|e| e.into_inner());
1008            }
1009        };
1010
1011        call_activity_hook(&shared, Some(&msg.prompt));
1012
1013        let totals = Mutex::new(TurnTotals {
1014            turns: 0,
1015            cost_usd: Some(0.0),
1016        });
1017        let emit_shared = Arc::clone(&shared);
1018        let emit = |body: EntryBody| {
1019            if let EntryBody::Turn { cost_usd, .. } = &body {
1020                let mut t = totals.lock().unwrap_or_else(|e| e.into_inner());
1021                t.turns += 1;
1022                match (t.cost_usd, cost_usd) {
1023                    (Some(acc), Some(c)) => t.cost_usd = Some(acc + c),
1024                    _ => t.cost_usd = None,
1025                }
1026            }
1027            let mut state = emit_shared.lock_state();
1028            state.push_entry(body);
1029            emit_shared.log_cv.notify_all();
1030        };
1031
1032        let outcome = catch_unwind(AssertUnwindSafe(|| {
1033            let _req_guard = RequestGuard::enter(msg.request_id);
1034            runner.run(&msg.prompt, &effective_model, &emit)
1035        }));
1036
1037        call_activity_hook(&shared, None);
1038
1039        let (turns, cost_usd) = {
1040            let t = totals.lock().unwrap_or_else(|e| e.into_inner());
1041            (t.turns, t.cost_usd)
1042        };
1043
1044        let mut state = shared.lock_state();
1045        match outcome {
1046            Ok(Ok(())) => {}
1047            Ok(Err(message)) => {
1048                state.push_entry(EntryBody::Error { message });
1049            }
1050            Err(payload) => {
1051                let message = panic_message(payload);
1052                state.push_entry(EntryBody::Error { message });
1053            }
1054        }
1055        state.push_entry(EntryBody::Idle { turns, cost_usd });
1056        state.busy = false;
1057        shared.log_cv.notify_all();
1058    }
1059}
1060
1061fn format_prompt(text: &str, attachments: &[Attachment]) -> String {
1062    let mut out = text.to_string();
1063    for att in attachments {
1064        out.push_str("\n\nResearch report ");
1065        out.push_str(&att.run);
1066        out.push_str(":\n");
1067        out.push_str(&att.text);
1068    }
1069    out
1070}
1071
1072pub(crate) fn model_supports_effort(model: &str) -> bool {
1073    blyte_provider::detect_provider_kind(Some(model)) == blyte_provider::ProviderKind::Gemini
1074}
1075
1076fn parse_model_and_effort(model: &str) -> (String, Option<String>) {
1077    let trimmed = model.trim();
1078    if model_supports_effort(trimmed) {
1079        blyte_provider::gemini::split_effort(trimmed)
1080    } else {
1081        (trimmed.to_string(), None)
1082    }
1083}
1084
1085fn panic_message(payload: Box<dyn std::any::Any + Send>) -> String {
1086    if let Some(s) = payload.downcast_ref::<&str>() {
1087        (*s).to_string()
1088    } else if let Some(s) = payload.downcast_ref::<String>() {
1089        s.clone()
1090    } else {
1091        "runner panicked".to_string()
1092    }
1093}
1094
1095fn now_secs() -> u64 {
1096    SystemTime::now()
1097        .duration_since(UNIX_EPOCH)
1098        .map(|d| d.as_secs())
1099        .unwrap_or(0)
1100}
1101
1102fn now_millis() -> u128 {
1103    SystemTime::now()
1104        .duration_since(UNIX_EPOCH)
1105        .map(|d| d.as_millis())
1106        .unwrap_or(0)
1107}
1108
1109fn new_session_prefix() -> String {
1110    let seq = SESSION_COUNTER.fetch_add(1, Ordering::Relaxed);
1111    format!("r{}-{}-{}", now_millis(), std::process::id(), seq)
1112}