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 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
541struct Shared {
542 state: Mutex<SessionState>,
543 log_cv: Condvar,
544 work_cv: Condvar,
545 approval_cv: Condvar,
546}
547
548impl Shared {
549 fn new(model: String, effort: Option<String>) -> Self {
550 Self {
551 state: Mutex::new(SessionState {
552 entries: Vec::new(),
553 last_seq: 0,
554 log: None,
555 write_failure_noticed: false,
556 queue: VecDeque::new(),
557 session_prefix: new_session_prefix(),
558 request_seq: 0,
559 model,
560 effort,
561 busy: false,
562 closed: false,
563 approvals: HashMap::new(),
564 next_approval_id: 0,
565 }),
566 log_cv: Condvar::new(),
567 work_cv: Condvar::new(),
568 approval_cv: Condvar::new(),
569 }
570 }
571
572 fn new_with_log(
573 model: String,
574 effort: Option<String>,
575 log_path: Option<PathBuf>,
576 err: &mut dyn Write,
577 ) -> Result<Self, String> {
578 let (log, entries) = match log_path {
579 Some(path) => {
580 let (log, entries) = EntryLog::open(path, err)?;
581 (Some(log), entries)
582 }
583 None => (None, Vec::new()),
584 };
585 let last_seq = entries.iter().map(|e| e.seq).max().unwrap_or(0);
586 let next_approval_id = max_approval_id(&entries);
587 let had_entries = !entries.is_empty();
588 let mut state = SessionState {
589 entries,
590 last_seq,
591 log,
592 write_failure_noticed: false,
593 queue: VecDeque::new(),
594 session_prefix: new_session_prefix(),
595 request_seq: 0,
596 model,
597 effort,
598 busy: false,
599 closed: false,
600 approvals: HashMap::new(),
601 next_approval_id,
602 };
603 if had_entries {
604 state.push_entry(EntryBody::Error {
605 message: RESTART_NOTICE_TEXT.to_string(),
606 });
607 }
608 Ok(Self {
609 state: Mutex::new(state),
610 log_cv: Condvar::new(),
611 work_cv: Condvar::new(),
612 approval_cv: Condvar::new(),
613 })
614 }
615
616 fn lock_state(&self) -> MutexGuard<'_, SessionState> {
617 self.state.lock().unwrap_or_else(|e| e.into_inner())
618 }
619}
620
621struct SessionGuard {
622 shared: Arc<Shared>,
623}
624
625impl Drop for SessionGuard {
626 fn drop(&mut self) {
627 let mut state = self.shared.lock_state();
628 state.closed = true;
629 state.deny_all_pending();
630 self.shared.work_cv.notify_all();
631 self.shared.log_cv.notify_all();
632 self.shared.approval_cv.notify_all();
633 }
634}
635
636#[derive(Clone)]
637pub struct Session {
638 guard: Arc<SessionGuard>,
639}
640
641struct TurnTotals {
642 turns: u32,
643 cost_usd: Option<f64>,
644}
645
646impl Session {
647 pub fn start(runner: Box<dyn PromptRunner>, model: String) -> Session {
648 Self::start_with(model, |_| runner)
649 }
650
651 pub fn start_with<F>(model: String, build_runner: F) -> Session
652 where
653 F: FnOnce(Arc<SurfaceApprover>) -> Box<dyn PromptRunner>,
654 {
655 let (base_model, effort) = parse_model_and_effort(&model);
656 let shared = Arc::new(Shared::new(base_model, effort));
657 let approver = Arc::new(SurfaceApprover {
658 shared: Arc::clone(&shared),
659 });
660 let runner = build_runner(approver);
661 let worker_shared = Arc::clone(&shared);
662 std::thread::spawn(move || worker_loop(runner, worker_shared));
663 Session {
664 guard: Arc::new(SessionGuard { shared }),
665 }
666 }
667
668 pub fn start_with_log<F>(
669 model: String,
670 log_path: Option<PathBuf>,
671 build_runner: F,
672 ) -> Result<Session, String>
673 where
674 F: FnOnce(Arc<SurfaceApprover>) -> Box<dyn PromptRunner>,
675 {
676 let mut stderr = std::io::stderr();
677 Self::start_with_log_io(model, log_path, &mut stderr, build_runner)
678 }
679
680 pub fn start_with_log_io<F>(
681 model: String,
682 log_path: Option<PathBuf>,
683 err: &mut dyn Write,
684 build_runner: F,
685 ) -> Result<Session, String>
686 where
687 F: FnOnce(Arc<SurfaceApprover>) -> Box<dyn PromptRunner>,
688 {
689 let (base_model, effort) = parse_model_and_effort(&model);
690 let shared = Arc::new(Shared::new_with_log(base_model, effort, log_path, err)?);
691 let approver = Arc::new(SurfaceApprover {
692 shared: Arc::clone(&shared),
693 });
694 let runner = build_runner(approver);
695 let worker_shared = Arc::clone(&shared);
696 std::thread::spawn(move || worker_loop(runner, worker_shared));
697 Ok(Session {
698 guard: Arc::new(SessionGuard { shared }),
699 })
700 }
701
702 #[doc(hidden)]
703 pub fn start_paused(
704 runner: Box<dyn PromptRunner>,
705 model: String,
706 ) -> (Session, std::sync::mpsc::Sender<()>) {
707 let (base_model, effort) = parse_model_and_effort(&model);
708 let shared = Arc::new(Shared::new(base_model, effort));
709 let (tx, rx) = std::sync::mpsc::channel();
710 let worker_shared = Arc::clone(&shared);
711 std::thread::spawn(move || {
712 if rx.recv().is_ok() {
713 worker_loop(runner, worker_shared);
714 }
715 });
716 (
717 Session {
718 guard: Arc::new(SessionGuard { shared }),
719 },
720 tx,
721 )
722 }
723
724 #[doc(hidden)]
725 pub fn fail_log_writes(&self, reason: &str) {
726 let mut state = self.guard.shared.lock_state();
727 if let Some(log) = &mut state.log {
728 log.fail_writes_with = Some(reason.to_string());
729 }
730 }
731
732 pub fn approver(&self) -> Arc<SurfaceApprover> {
733 Arc::new(SurfaceApprover {
734 shared: Arc::clone(&self.guard.shared),
735 })
736 }
737
738 pub fn answer_approval(&self, id: &str, answer: ApprovalAnswer) -> Result<u64, AnswerError> {
739 let mut state = self.guard.shared.lock_state();
740 let command = match state.approvals.get_mut(id) {
741 None => return Err(AnswerError::NotFound),
742 Some(record) if record.answer.is_some() => return Err(AnswerError::AlreadyAnswered),
743 Some(record) => {
744 record.answer = Some(answer);
745 record.command.clone()
746 }
747 };
748 let seq = state.push_entry(EntryBody::ApprovalAnswered {
749 id: id.to_string(),
750 command,
751 answer: answer.as_str().to_string(),
752 });
753 self.guard.shared.approval_cv.notify_all();
754 self.guard.shared.log_cv.notify_all();
755 Ok(seq)
756 }
757
758 pub fn stop_run(&self) {
759 let mut state = self.guard.shared.lock_state();
760 if state.deny_all_pending() {
761 self.guard.shared.approval_cv.notify_all();
762 self.guard.shared.log_cv.notify_all();
763 }
764 }
765
766 pub fn submit(&self, text: &str, attachments: Vec<Attachment>) -> Result<u64, String> {
767 if text.trim().is_empty() {
768 return Err("a message needs text".to_string());
769 }
770 let reports = attachments.iter().map(|a| a.run.clone()).collect();
771 let full_prompt = format_prompt(text, &attachments);
772 let mut state = self.guard.shared.lock_state();
773 let queued = state.busy || !state.queue.is_empty();
774 let seq = state.push_entry(EntryBody::UserMessage {
775 text: text.to_string(),
776 reports,
777 queued,
778 });
779 let request_id = state.next_request_id();
780 state.queue.push_back(QueuedMessage {
781 request_id,
782 prompt: full_prompt,
783 });
784 self.guard.shared.work_cv.notify_one();
785 self.guard.shared.log_cv.notify_all();
786 Ok(seq)
787 }
788
789 pub fn entries_after(&self, after: u64, wait: Duration) -> Vec<Entry> {
790 let mut state = self.guard.shared.lock_state();
791 if state.last_seq <= after && !wait.is_zero() {
792 let deadline = Instant::now() + wait;
793 while state.last_seq <= after {
794 let remaining = deadline.saturating_duration_since(Instant::now());
795 if remaining.is_zero() {
796 break;
797 }
798 let (guard, _) = self
799 .guard
800 .shared
801 .log_cv
802 .wait_timeout(state, remaining)
803 .unwrap_or_else(|e| e.into_inner());
804 state = guard;
805 }
806 }
807 state
808 .entries
809 .iter()
810 .filter(|e| e.seq > after)
811 .cloned()
812 .collect()
813 }
814
815 pub fn info(&self) -> SessionInfo {
816 let state = self.guard.shared.lock_state();
817 SessionInfo {
818 effort_supported: model_supports_effort(&state.model),
819 model: state.model.clone(),
820 effort: state.effort.clone(),
821 busy: state.busy,
822 queued: state.queue.len(),
823 last_seq: state.last_seq,
824 }
825 }
826
827 pub fn set_model(&self, model: &str) -> Result<(), String> {
828 let trimmed = model.trim();
829 if trimmed.is_empty() {
830 return Err("model cannot be empty".to_string());
831 }
832 let mut state = self.guard.shared.lock_state();
833 let supported = model_supports_effort(trimmed);
834 if supported {
835 let (base, parsed_effort) = blyte_provider::gemini::split_effort(trimmed);
836 state.model = base.clone();
837 state.push_entry(EntryBody::ModelChanged { model: base });
838 if let Some(new_effort) = parsed_effort {
839 if state.effort.as_deref() != Some(new_effort.as_str()) {
840 state.effort = Some(new_effort.clone());
841 state.push_entry(EntryBody::EffortChanged {
842 effort: Some(new_effort),
843 });
844 }
845 }
846 } else {
847 state.model = trimmed.to_string();
848 state.push_entry(EntryBody::ModelChanged {
849 model: trimmed.to_string(),
850 });
851 if state.effort.is_some() {
852 state.effort = None;
853 state.push_entry(EntryBody::EffortChanged { effort: None });
854 }
855 }
856 self.guard.shared.log_cv.notify_all();
857 Ok(())
858 }
859
860 pub fn set_effort(&self, effort: Option<&str>) -> Result<(), String> {
861 let normalized = match effort {
862 None => None,
863 Some("low") => Some("low".to_string()),
864 Some("medium") => Some("medium".to_string()),
865 Some("high") => Some("high".to_string()),
866 Some(_) => return Err("effort must be low, medium or high".to_string()),
867 };
868 let mut state = self.guard.shared.lock_state();
869 if !model_supports_effort(&state.model) {
870 return Err(format!("{} does not take an effort setting", state.model));
871 }
872 state.effort = normalized.clone();
873 state.push_entry(EntryBody::EffortChanged { effort: normalized });
874 self.guard.shared.log_cv.notify_all();
875 Ok(())
876 }
877
878 pub fn record_decision(
879 &self,
880 run: &str,
881 action: &str,
882 note: Option<&str>,
883 conversation_message: Option<&str>,
884 ) -> Result<u64, String> {
885 if let Some(msg) = conversation_message {
886 if msg.trim().is_empty() {
887 return Err("a message needs text".to_string());
888 }
889 }
890 let mut state = self.guard.shared.lock_state();
891 let seq = state.push_entry(EntryBody::Decision {
892 run: run.to_string(),
893 action: action.to_string(),
894 note: note.map(str::to_string),
895 });
896 if let Some(msg) = conversation_message {
897 let queued = state.busy || !state.queue.is_empty();
898 state.push_entry(EntryBody::UserMessage {
899 text: msg.to_string(),
900 reports: Vec::new(),
901 queued,
902 });
903 let request_id = state.next_request_id();
904 state.queue.push_back(QueuedMessage {
905 request_id,
906 prompt: msg.to_string(),
907 });
908 self.guard.shared.work_cv.notify_one();
909 }
910 self.guard.shared.log_cv.notify_all();
911 Ok(seq)
912 }
913
914 pub fn queue_for_request(&self, request_id: &str, text: &str) -> Result<u64, String> {
915 if text.trim().is_empty() {
916 return Err("a message needs text".to_string());
917 }
918 let mut state = self.guard.shared.lock_state();
919 let queued = state.busy || !state.queue.is_empty();
920 let seq = state.push_entry(EntryBody::UserMessage {
921 text: text.to_string(),
922 reports: Vec::new(),
923 queued,
924 });
925 state.queue.push_back(QueuedMessage {
926 request_id: request_id.to_string(),
927 prompt: text.to_string(),
928 });
929 self.guard.shared.work_cv.notify_one();
930 self.guard.shared.log_cv.notify_all();
931 Ok(seq)
932 }
933
934 pub fn record_error(&self, message: &str) -> u64 {
935 let mut state = self.guard.shared.lock_state();
936 let seq = state.push_entry(EntryBody::Error {
937 message: message.to_string(),
938 });
939 self.guard.shared.log_cv.notify_all();
940 seq
941 }
942}
943
944struct RequestGuard;
945
946impl RequestGuard {
947 fn enter(request_id: String) -> Self {
948 blyte_agent::tools::set_blyte_request(Some(request_id));
949 Self
950 }
951}
952
953impl Drop for RequestGuard {
954 fn drop(&mut self) {
955 blyte_agent::tools::set_blyte_request(None);
956 }
957}
958
959fn worker_loop(mut runner: Box<dyn PromptRunner>, shared: Arc<Shared>) {
960 loop {
961 let (msg, effective_model) = {
962 let mut state = shared.lock_state();
963 loop {
964 if state.closed {
965 return;
966 }
967 if let Some(msg) = state.queue.pop_front() {
968 state.busy = true;
969 let model = state.effective_model();
970 break (msg, model);
971 }
972 state = shared
973 .work_cv
974 .wait(state)
975 .unwrap_or_else(|e| e.into_inner());
976 }
977 };
978
979 let totals = Mutex::new(TurnTotals {
980 turns: 0,
981 cost_usd: Some(0.0),
982 });
983 let emit_shared = Arc::clone(&shared);
984 let emit = |body: EntryBody| {
985 if let EntryBody::Turn { cost_usd, .. } = &body {
986 let mut t = totals.lock().unwrap_or_else(|e| e.into_inner());
987 t.turns += 1;
988 match (t.cost_usd, cost_usd) {
989 (Some(acc), Some(c)) => t.cost_usd = Some(acc + c),
990 _ => t.cost_usd = None,
991 }
992 }
993 let mut state = emit_shared.lock_state();
994 state.push_entry(body);
995 emit_shared.log_cv.notify_all();
996 };
997
998 let outcome = catch_unwind(AssertUnwindSafe(|| {
999 let _req_guard = RequestGuard::enter(msg.request_id);
1000 runner.run(&msg.prompt, &effective_model, &emit)
1001 }));
1002
1003 let (turns, cost_usd) = {
1004 let t = totals.lock().unwrap_or_else(|e| e.into_inner());
1005 (t.turns, t.cost_usd)
1006 };
1007
1008 let mut state = shared.lock_state();
1009 match outcome {
1010 Ok(Ok(())) => {}
1011 Ok(Err(message)) => {
1012 state.push_entry(EntryBody::Error { message });
1013 }
1014 Err(payload) => {
1015 let message = panic_message(payload);
1016 state.push_entry(EntryBody::Error { message });
1017 }
1018 }
1019 state.push_entry(EntryBody::Idle { turns, cost_usd });
1020 state.busy = false;
1021 shared.log_cv.notify_all();
1022 }
1023}
1024
1025fn format_prompt(text: &str, attachments: &[Attachment]) -> String {
1026 let mut out = text.to_string();
1027 for att in attachments {
1028 out.push_str("\n\nResearch report ");
1029 out.push_str(&att.run);
1030 out.push_str(":\n");
1031 out.push_str(&att.text);
1032 }
1033 out
1034}
1035
1036pub(crate) fn model_supports_effort(model: &str) -> bool {
1037 blyte_provider::detect_provider_kind(Some(model)) == blyte_provider::ProviderKind::Gemini
1038}
1039
1040fn parse_model_and_effort(model: &str) -> (String, Option<String>) {
1041 let trimmed = model.trim();
1042 if model_supports_effort(trimmed) {
1043 blyte_provider::gemini::split_effort(trimmed)
1044 } else {
1045 (trimmed.to_string(), None)
1046 }
1047}
1048
1049fn panic_message(payload: Box<dyn std::any::Any + Send>) -> String {
1050 if let Some(s) = payload.downcast_ref::<&str>() {
1051 (*s).to_string()
1052 } else if let Some(s) = payload.downcast_ref::<String>() {
1053 s.clone()
1054 } else {
1055 "runner panicked".to_string()
1056 }
1057}
1058
1059fn now_secs() -> u64 {
1060 SystemTime::now()
1061 .duration_since(UNIX_EPOCH)
1062 .map(|d| d.as_secs())
1063 .unwrap_or(0)
1064}
1065
1066fn now_millis() -> u128 {
1067 SystemTime::now()
1068 .duration_since(UNIX_EPOCH)
1069 .map(|d| d.as_millis())
1070 .unwrap_or(0)
1071}
1072
1073fn new_session_prefix() -> String {
1074 let seq = SESSION_COUNTER.fetch_add(1, Ordering::Relaxed);
1075 format!("r{}-{}-{}", now_millis(), std::process::id(), seq)
1076}