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.orchestrate = 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.orchestrator.goal = prompt.to_string();
207 if let Some(ref gate) = self.repl.gate {
208 self.repl.state.orchestrator.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}
287
288impl EntryLog {
289 fn open(path: PathBuf, err: &mut dyn Write) -> Result<(Self, Vec<Entry>), String> {
290 let (entries, truncate_to, needs_newline) = load_entries_file(&path, err)?;
291 if let Some(parent) = path.parent() {
292 if !parent.as_os_str().is_empty() {
293 std::fs::create_dir_all(parent)
294 .map_err(|e| format!("failed to create directory {}: {e}", parent.display()))?;
295 }
296 }
297 if let Some(len) = truncate_to {
298 let f = OpenOptions::new()
299 .write(true)
300 .open(&path)
301 .map_err(|e| format!("failed to truncate {}: {e}", path.display()))?;
302 f.set_len(len)
303 .map_err(|e| format!("failed to truncate {}: {e}", path.display()))?;
304 }
305 let mut file = OpenOptions::new()
306 .create(true)
307 .append(true)
308 .open(&path)
309 .map_err(|e| format!("failed to open {}: {e}", path.display()))?;
310 if needs_newline {
311 file.write_all(b"\n")
312 .and_then(|_| file.flush())
313 .map_err(|e| format!("failed to write to {}: {e}", path.display()))?;
314 }
315 Ok((Self { path, file }, entries))
316 }
317
318 fn append(&mut self, entry: &Entry) {
319 let mut line = match serde_json::to_string(entry) {
320 Ok(s) => s,
321 Err(e) => {
322 eprintln!(
323 "blyte: failed to serialize entry for {}: {e}",
324 self.path.display()
325 );
326 return;
327 }
328 };
329 line.push('\n');
330 if let Err(e) = self
331 .file
332 .write_all(line.as_bytes())
333 .and_then(|_| self.file.flush())
334 {
335 eprintln!("blyte: failed to write to {}: {e}", self.path.display());
336 }
337 }
338}
339
340fn load_entries_file(
341 path: &Path,
342 err: &mut dyn Write,
343) -> Result<(Vec<Entry>, Option<u64>, bool), String> {
344 let bytes = match std::fs::read(path) {
345 Ok(b) => b,
346 Err(e) if e.kind() == ErrorKind::NotFound => return Ok((Vec::new(), None, false)),
347 Err(e) => return Err(format!("failed to read {}: {e}", path.display())),
348 };
349 if bytes.is_empty() {
350 return Ok((Vec::new(), None, false));
351 }
352
353 let mut entries = Vec::new();
354 let mut pos = 0usize;
355 let mut line_no = 0usize;
356 let mut truncate_to = None;
357 let mut valid_end = 0usize;
358
359 while pos < bytes.len() {
360 line_no += 1;
361 let start = pos;
362 let end = match bytes[pos..].iter().position(|&b| b == b'\n') {
363 Some(rel) => pos + rel + 1,
364 None => bytes.len(),
365 };
366 let is_last = end == bytes.len() && !bytes[start..end].ends_with(b"\n");
368 let line_slice = &bytes[start..end];
369 let parsed = std::str::from_utf8(line_slice)
370 .map_err(|e| e.to_string())
371 .and_then(|s| serde_json::from_str::<Entry>(s).map_err(|e| e.to_string()));
372 match parsed {
373 Ok(entry) => {
374 entries.push(entry);
375 valid_end = end;
376 }
377 Err(reason) => {
378 if is_last {
379 let _ = writeln!(
380 err,
381 "blyte: dropping truncated last line in {} at line {}: {}",
382 path.display(),
383 line_no,
384 reason
385 );
386 let _ = err.flush();
387 truncate_to = Some(start as u64);
388 } else {
389 return Err(format!(
390 "invalid entry in {} at line {}: {}",
391 path.display(),
392 line_no,
393 reason
394 ));
395 }
396 }
397 }
398 pos = end;
399 }
400
401 let needs_newline = valid_end > 0 && bytes[valid_end - 1] != b'\n';
402 Ok((entries, truncate_to, needs_newline))
403}
404
405fn max_approval_id(entries: &[Entry]) -> u64 {
406 entries
407 .iter()
408 .filter_map(|e| match &e.body {
409 EntryBody::ApprovalRequested { id, .. } | EntryBody::ApprovalAnswered { id, .. } => {
410 id.strip_prefix("approval-")?.parse::<u64>().ok()
411 }
412 _ => None,
413 })
414 .max()
415 .unwrap_or(0)
416}
417
418struct SessionState {
419 entries: Vec<Entry>,
420 last_seq: u64,
421 log: Option<EntryLog>,
422 queue: VecDeque<QueuedMessage>,
423 session_prefix: String,
424 request_seq: u64,
425 model: String,
426 effort: Option<String>,
427 busy: bool,
428 closed: bool,
429 approvals: HashMap<String, ApprovalRecord>,
430 next_approval_id: u64,
431}
432
433impl SessionState {
434 fn push_entry(&mut self, body: EntryBody) -> u64 {
435 self.last_seq += 1;
436 let seq = self.last_seq;
437 let ts = now_secs();
438 let entry = Entry { seq, ts, body };
439 if let Some(log) = &mut self.log {
440 log.append(&entry);
441 }
442 self.entries.push(entry);
443 seq
444 }
445
446 fn next_request_id(&mut self) -> String {
447 self.request_seq += 1;
448 format!("{}-{}", self.session_prefix, self.request_seq)
449 }
450
451 fn effective_model(&self) -> String {
452 match &self.effort {
453 Some(effort) if model_supports_effort(&self.model) => {
454 format!("{}-{}", self.model, effort)
455 }
456 _ => self.model.clone(),
457 }
458 }
459
460 fn deny_all_pending(&mut self) -> bool {
461 let mut pending: Vec<(u64, String, String)> = self
462 .approvals
463 .iter()
464 .filter(|(_, record)| record.answer.is_none())
465 .map(|(id, record)| (record.order, id.clone(), record.command.clone()))
466 .collect();
467 if pending.is_empty() {
468 return false;
469 }
470 pending.sort_by_key(|(order, _, _)| *order);
471 for (_, id, command) in pending {
472 if let Some(record) = self.approvals.get_mut(&id) {
473 record.answer = Some(ApprovalAnswer::No);
474 }
475 self.push_entry(EntryBody::ApprovalAnswered {
476 id,
477 command,
478 answer: ApprovalAnswer::No.as_str().to_string(),
479 });
480 }
481 true
482 }
483}
484
485struct Shared {
486 state: Mutex<SessionState>,
487 log_cv: Condvar,
488 work_cv: Condvar,
489 approval_cv: Condvar,
490}
491
492impl Shared {
493 fn new(model: String, effort: Option<String>) -> Self {
494 Self {
495 state: Mutex::new(SessionState {
496 entries: Vec::new(),
497 last_seq: 0,
498 log: None,
499 queue: VecDeque::new(),
500 session_prefix: new_session_prefix(),
501 request_seq: 0,
502 model,
503 effort,
504 busy: false,
505 closed: false,
506 approvals: HashMap::new(),
507 next_approval_id: 0,
508 }),
509 log_cv: Condvar::new(),
510 work_cv: Condvar::new(),
511 approval_cv: Condvar::new(),
512 }
513 }
514
515 fn new_with_log(
516 model: String,
517 effort: Option<String>,
518 log_path: Option<PathBuf>,
519 err: &mut dyn Write,
520 ) -> Result<Self, String> {
521 let (log, entries) = match log_path {
522 Some(path) => {
523 let (log, entries) = EntryLog::open(path, err)?;
524 (Some(log), entries)
525 }
526 None => (None, Vec::new()),
527 };
528 let last_seq = entries.iter().map(|e| e.seq).max().unwrap_or(0);
529 let next_approval_id = max_approval_id(&entries);
530 let had_entries = !entries.is_empty();
531 let mut state = SessionState {
532 entries,
533 last_seq,
534 log,
535 queue: VecDeque::new(),
536 session_prefix: new_session_prefix(),
537 request_seq: 0,
538 model,
539 effort,
540 busy: false,
541 closed: false,
542 approvals: HashMap::new(),
543 next_approval_id,
544 };
545 if had_entries {
546 state.push_entry(EntryBody::Error {
547 message: RESTART_NOTICE_TEXT.to_string(),
548 });
549 }
550 Ok(Self {
551 state: Mutex::new(state),
552 log_cv: Condvar::new(),
553 work_cv: Condvar::new(),
554 approval_cv: Condvar::new(),
555 })
556 }
557
558 fn lock_state(&self) -> MutexGuard<'_, SessionState> {
559 self.state.lock().unwrap_or_else(|e| e.into_inner())
560 }
561}
562
563struct SessionGuard {
564 shared: Arc<Shared>,
565}
566
567impl Drop for SessionGuard {
568 fn drop(&mut self) {
569 let mut state = self.shared.lock_state();
570 state.closed = true;
571 state.deny_all_pending();
572 self.shared.work_cv.notify_all();
573 self.shared.log_cv.notify_all();
574 self.shared.approval_cv.notify_all();
575 }
576}
577
578#[derive(Clone)]
579pub struct Session {
580 guard: Arc<SessionGuard>,
581}
582
583struct TurnTotals {
584 turns: u32,
585 cost_usd: Option<f64>,
586}
587
588impl Session {
589 pub fn start(runner: Box<dyn PromptRunner>, model: String) -> Session {
590 Self::start_with(model, |_| runner)
591 }
592
593 pub fn start_with<F>(model: String, build_runner: F) -> Session
594 where
595 F: FnOnce(Arc<SurfaceApprover>) -> Box<dyn PromptRunner>,
596 {
597 let (base_model, effort) = parse_model_and_effort(&model);
598 let shared = Arc::new(Shared::new(base_model, effort));
599 let approver = Arc::new(SurfaceApprover {
600 shared: Arc::clone(&shared),
601 });
602 let runner = build_runner(approver);
603 let worker_shared = Arc::clone(&shared);
604 std::thread::spawn(move || worker_loop(runner, worker_shared));
605 Session {
606 guard: Arc::new(SessionGuard { shared }),
607 }
608 }
609
610 pub fn start_with_log<F>(
611 model: String,
612 log_path: Option<PathBuf>,
613 build_runner: F,
614 ) -> Result<Session, String>
615 where
616 F: FnOnce(Arc<SurfaceApprover>) -> Box<dyn PromptRunner>,
617 {
618 let mut stderr = std::io::stderr();
619 Self::start_with_log_io(model, log_path, &mut stderr, build_runner)
620 }
621
622 pub fn start_with_log_io<F>(
623 model: String,
624 log_path: Option<PathBuf>,
625 err: &mut dyn Write,
626 build_runner: F,
627 ) -> Result<Session, String>
628 where
629 F: FnOnce(Arc<SurfaceApprover>) -> Box<dyn PromptRunner>,
630 {
631 let (base_model, effort) = parse_model_and_effort(&model);
632 let shared = Arc::new(Shared::new_with_log(base_model, effort, log_path, err)?);
633 let approver = Arc::new(SurfaceApprover {
634 shared: Arc::clone(&shared),
635 });
636 let runner = build_runner(approver);
637 let worker_shared = Arc::clone(&shared);
638 std::thread::spawn(move || worker_loop(runner, worker_shared));
639 Ok(Session {
640 guard: Arc::new(SessionGuard { shared }),
641 })
642 }
643
644 #[doc(hidden)]
645 pub fn start_paused(
646 runner: Box<dyn PromptRunner>,
647 model: String,
648 ) -> (Session, std::sync::mpsc::Sender<()>) {
649 let (base_model, effort) = parse_model_and_effort(&model);
650 let shared = Arc::new(Shared::new(base_model, effort));
651 let (tx, rx) = std::sync::mpsc::channel();
652 let worker_shared = Arc::clone(&shared);
653 std::thread::spawn(move || {
654 if rx.recv().is_ok() {
655 worker_loop(runner, worker_shared);
656 }
657 });
658 (
659 Session {
660 guard: Arc::new(SessionGuard { shared }),
661 },
662 tx,
663 )
664 }
665
666 pub fn approver(&self) -> Arc<SurfaceApprover> {
667 Arc::new(SurfaceApprover {
668 shared: Arc::clone(&self.guard.shared),
669 })
670 }
671
672 pub fn answer_approval(&self, id: &str, answer: ApprovalAnswer) -> Result<u64, AnswerError> {
673 let mut state = self.guard.shared.lock_state();
674 let command = match state.approvals.get_mut(id) {
675 None => return Err(AnswerError::NotFound),
676 Some(record) if record.answer.is_some() => return Err(AnswerError::AlreadyAnswered),
677 Some(record) => {
678 record.answer = Some(answer);
679 record.command.clone()
680 }
681 };
682 let seq = state.push_entry(EntryBody::ApprovalAnswered {
683 id: id.to_string(),
684 command,
685 answer: answer.as_str().to_string(),
686 });
687 self.guard.shared.approval_cv.notify_all();
688 self.guard.shared.log_cv.notify_all();
689 Ok(seq)
690 }
691
692 pub fn stop_run(&self) {
693 let mut state = self.guard.shared.lock_state();
694 if state.deny_all_pending() {
695 self.guard.shared.approval_cv.notify_all();
696 self.guard.shared.log_cv.notify_all();
697 }
698 }
699
700 pub fn submit(&self, text: &str, attachments: Vec<Attachment>) -> Result<u64, String> {
701 if text.trim().is_empty() {
702 return Err("a message needs text".to_string());
703 }
704 let reports = attachments.iter().map(|a| a.run.clone()).collect();
705 let full_prompt = format_prompt(text, &attachments);
706 let mut state = self.guard.shared.lock_state();
707 let queued = state.busy || !state.queue.is_empty();
708 let seq = state.push_entry(EntryBody::UserMessage {
709 text: text.to_string(),
710 reports,
711 queued,
712 });
713 let request_id = state.next_request_id();
714 state.queue.push_back(QueuedMessage {
715 request_id,
716 prompt: full_prompt,
717 });
718 self.guard.shared.work_cv.notify_one();
719 self.guard.shared.log_cv.notify_all();
720 Ok(seq)
721 }
722
723 pub fn entries_after(&self, after: u64, wait: Duration) -> Vec<Entry> {
724 let mut state = self.guard.shared.lock_state();
725 if state.last_seq <= after && !wait.is_zero() {
726 let deadline = Instant::now() + wait;
727 while state.last_seq <= after {
728 let remaining = deadline.saturating_duration_since(Instant::now());
729 if remaining.is_zero() {
730 break;
731 }
732 let (guard, _) = self
733 .guard
734 .shared
735 .log_cv
736 .wait_timeout(state, remaining)
737 .unwrap_or_else(|e| e.into_inner());
738 state = guard;
739 }
740 }
741 state
742 .entries
743 .iter()
744 .filter(|e| e.seq > after)
745 .cloned()
746 .collect()
747 }
748
749 pub fn info(&self) -> SessionInfo {
750 let state = self.guard.shared.lock_state();
751 SessionInfo {
752 effort_supported: model_supports_effort(&state.model),
753 model: state.model.clone(),
754 effort: state.effort.clone(),
755 busy: state.busy,
756 queued: state.queue.len(),
757 last_seq: state.last_seq,
758 }
759 }
760
761 pub fn set_model(&self, model: &str) -> Result<(), String> {
762 let trimmed = model.trim();
763 if trimmed.is_empty() {
764 return Err("model cannot be empty".to_string());
765 }
766 let mut state = self.guard.shared.lock_state();
767 let supported = model_supports_effort(trimmed);
768 if supported {
769 let (base, parsed_effort) = blyte_provider::gemini::split_effort(trimmed);
770 state.model = base.clone();
771 state.push_entry(EntryBody::ModelChanged { model: base });
772 if let Some(new_effort) = parsed_effort {
773 if state.effort.as_deref() != Some(new_effort.as_str()) {
774 state.effort = Some(new_effort.clone());
775 state.push_entry(EntryBody::EffortChanged {
776 effort: Some(new_effort),
777 });
778 }
779 }
780 } else {
781 state.model = trimmed.to_string();
782 state.push_entry(EntryBody::ModelChanged {
783 model: trimmed.to_string(),
784 });
785 if state.effort.is_some() {
786 state.effort = None;
787 state.push_entry(EntryBody::EffortChanged { effort: None });
788 }
789 }
790 self.guard.shared.log_cv.notify_all();
791 Ok(())
792 }
793
794 pub fn set_effort(&self, effort: Option<&str>) -> Result<(), String> {
795 let normalized = match effort {
796 None => None,
797 Some("low") => Some("low".to_string()),
798 Some("medium") => Some("medium".to_string()),
799 Some("high") => Some("high".to_string()),
800 Some(_) => return Err("effort must be low, medium or high".to_string()),
801 };
802 let mut state = self.guard.shared.lock_state();
803 if !model_supports_effort(&state.model) {
804 return Err(format!("{} does not take an effort setting", state.model));
805 }
806 state.effort = normalized.clone();
807 state.push_entry(EntryBody::EffortChanged { effort: normalized });
808 self.guard.shared.log_cv.notify_all();
809 Ok(())
810 }
811
812 pub fn record_decision(
813 &self,
814 run: &str,
815 action: &str,
816 note: Option<&str>,
817 orchestrator_message: Option<&str>,
818 ) -> Result<u64, String> {
819 if let Some(msg) = orchestrator_message {
820 if msg.trim().is_empty() {
821 return Err("a message needs text".to_string());
822 }
823 }
824 let mut state = self.guard.shared.lock_state();
825 let seq = state.push_entry(EntryBody::Decision {
826 run: run.to_string(),
827 action: action.to_string(),
828 note: note.map(str::to_string),
829 });
830 if let Some(msg) = orchestrator_message {
831 let queued = state.busy || !state.queue.is_empty();
832 state.push_entry(EntryBody::UserMessage {
833 text: msg.to_string(),
834 reports: Vec::new(),
835 queued,
836 });
837 let request_id = state.next_request_id();
838 state.queue.push_back(QueuedMessage {
839 request_id,
840 prompt: msg.to_string(),
841 });
842 self.guard.shared.work_cv.notify_one();
843 }
844 self.guard.shared.log_cv.notify_all();
845 Ok(seq)
846 }
847
848 pub fn queue_for_request(&self, request_id: &str, text: &str) -> Result<u64, String> {
849 if text.trim().is_empty() {
850 return Err("a message needs text".to_string());
851 }
852 let mut state = self.guard.shared.lock_state();
853 let queued = state.busy || !state.queue.is_empty();
854 let seq = state.push_entry(EntryBody::UserMessage {
855 text: text.to_string(),
856 reports: Vec::new(),
857 queued,
858 });
859 state.queue.push_back(QueuedMessage {
860 request_id: request_id.to_string(),
861 prompt: text.to_string(),
862 });
863 self.guard.shared.work_cv.notify_one();
864 self.guard.shared.log_cv.notify_all();
865 Ok(seq)
866 }
867
868 pub fn record_error(&self, message: &str) -> u64 {
869 let mut state = self.guard.shared.lock_state();
870 let seq = state.push_entry(EntryBody::Error {
871 message: message.to_string(),
872 });
873 self.guard.shared.log_cv.notify_all();
874 seq
875 }
876}
877
878struct RequestGuard;
879
880impl RequestGuard {
881 fn enter(request_id: String) -> Self {
882 blyte_agent::tools::set_blyte_request(Some(request_id));
883 Self
884 }
885}
886
887impl Drop for RequestGuard {
888 fn drop(&mut self) {
889 blyte_agent::tools::set_blyte_request(None);
890 }
891}
892
893fn worker_loop(mut runner: Box<dyn PromptRunner>, shared: Arc<Shared>) {
894 loop {
895 let (msg, effective_model) = {
896 let mut state = shared.lock_state();
897 loop {
898 if state.closed {
899 return;
900 }
901 if let Some(msg) = state.queue.pop_front() {
902 state.busy = true;
903 let model = state.effective_model();
904 break (msg, model);
905 }
906 state = shared
907 .work_cv
908 .wait(state)
909 .unwrap_or_else(|e| e.into_inner());
910 }
911 };
912
913 let totals = Mutex::new(TurnTotals {
914 turns: 0,
915 cost_usd: Some(0.0),
916 });
917 let emit_shared = Arc::clone(&shared);
918 let emit = |body: EntryBody| {
919 if let EntryBody::Turn { cost_usd, .. } = &body {
920 let mut t = totals.lock().unwrap_or_else(|e| e.into_inner());
921 t.turns += 1;
922 match (t.cost_usd, cost_usd) {
923 (Some(acc), Some(c)) => t.cost_usd = Some(acc + c),
924 _ => t.cost_usd = None,
925 }
926 }
927 let mut state = emit_shared.lock_state();
928 state.push_entry(body);
929 emit_shared.log_cv.notify_all();
930 };
931
932 let outcome = catch_unwind(AssertUnwindSafe(|| {
933 let _req_guard = RequestGuard::enter(msg.request_id);
934 runner.run(&msg.prompt, &effective_model, &emit)
935 }));
936
937 let (turns, cost_usd) = {
938 let t = totals.lock().unwrap_or_else(|e| e.into_inner());
939 (t.turns, t.cost_usd)
940 };
941
942 let mut state = shared.lock_state();
943 match outcome {
944 Ok(Ok(())) => {}
945 Ok(Err(message)) => {
946 state.push_entry(EntryBody::Error { message });
947 }
948 Err(payload) => {
949 let message = panic_message(payload);
950 state.push_entry(EntryBody::Error { message });
951 }
952 }
953 state.push_entry(EntryBody::Idle { turns, cost_usd });
954 state.busy = false;
955 shared.log_cv.notify_all();
956 }
957}
958
959fn format_prompt(text: &str, attachments: &[Attachment]) -> String {
960 let mut out = text.to_string();
961 for att in attachments {
962 out.push_str("\n\nResearch report ");
963 out.push_str(&att.run);
964 out.push_str(":\n");
965 out.push_str(&att.text);
966 }
967 out
968}
969
970pub(crate) fn model_supports_effort(model: &str) -> bool {
971 blyte_provider::detect_provider_kind(Some(model)) == blyte_provider::ProviderKind::Gemini
972}
973
974fn parse_model_and_effort(model: &str) -> (String, Option<String>) {
975 let trimmed = model.trim();
976 if model_supports_effort(trimmed) {
977 blyte_provider::gemini::split_effort(trimmed)
978 } else {
979 (trimmed.to_string(), None)
980 }
981}
982
983fn panic_message(payload: Box<dyn std::any::Any + Send>) -> String {
984 if let Some(s) = payload.downcast_ref::<&str>() {
985 (*s).to_string()
986 } else if let Some(s) = payload.downcast_ref::<String>() {
987 s.clone()
988 } else {
989 "runner panicked".to_string()
990 }
991}
992
993fn now_secs() -> u64 {
994 SystemTime::now()
995 .duration_since(UNIX_EPOCH)
996 .map(|d| d.as_secs())
997 .unwrap_or(0)
998}
999
1000fn now_millis() -> u128 {
1001 SystemTime::now()
1002 .duration_since(UNIX_EPOCH)
1003 .map(|d| d.as_millis())
1004 .unwrap_or(0)
1005}
1006
1007fn new_session_prefix() -> String {
1008 let seq = SESSION_COUNTER.fetch_add(1, Ordering::Relaxed);
1009 format!("r{}-{}-{}", now_millis(), std::process::id(), seq)
1010}