ralph_workflow/json_parser/opencode/
io.rs1use std::cell::{Cell, RefCell};
2use std::collections::HashMap;
3use std::rc::Rc;
4
5use crate::json_parser::streaming_state::StreamingSession;
6use crate::json_parser::terminal::TerminalMode;
7
8pub struct OpenCodeParserState {
9 pub streaming_session: Rc<RefCell<StreamingSession>>,
10 pub terminal_mode: RefCell<TerminalMode>,
11 pub last_rendered_content: RefCell<HashMap<String, String>>,
12 pub fallback_step_counter: Cell<u64>,
13}
14
15impl OpenCodeParserState {
16 pub fn new(verbose_warnings: bool) -> Self {
17 let streaming_session = StreamingSession::new().with_verbose_warnings(verbose_warnings);
18 Self {
19 streaming_session: Rc::new(RefCell::new(streaming_session)),
20 terminal_mode: RefCell::new(TerminalMode::detect()),
21 last_rendered_content: RefCell::new(HashMap::new()),
22 fallback_step_counter: Cell::new(0),
23 }
24 }
25
26 pub fn with_session_mut<R>(&self, f: impl FnOnce(&mut StreamingSession) -> R) -> R {
27 f(&mut self.streaming_session.borrow_mut())
28 }
29
30 pub fn with_last_rendered_content_mut<R>(
31 &self,
32 f: impl FnOnce(&mut HashMap<String, String>) -> R,
33 ) -> R {
34 f(&mut self.last_rendered_content.borrow_mut())
35 }
36
37 pub fn next_fallback_step_id(&self, session: &str, timestamp: Option<u64>) -> String {
38 let counter = self.fallback_step_counter.get().saturating_add(1);
39 self.fallback_step_counter.set(counter);
40 timestamp.map_or_else(
41 || format!("{session}:fallback:{counter}"),
42 |ts| format!("{session}:{ts}:{counter}"),
43 )
44 }
45}