1use agent::AgentEvent;
6use ai::{AssistantMessageEvent, Message};
7use serde_json::{Value, json};
8use session_journal::Session;
9use session_journal::run::Run;
10
11pub struct RunJournal {
13 run: Option<Run>,
14 model: (u64, u64),
16 error: Option<String>,
17 ledger_counts_turns: bool,
20}
21
22impl RunJournal {
23 pub fn admit(
27 session: Option<&mut Session>,
28 config: Value,
29 prompt: Value,
30 model: (u64, u64),
31 settings: Value,
32 captured: &[(String, Value)],
33 inbox: Value,
34 ) -> Result<Self, String> {
35 let run = match session {
36 Some(session) => Some(Run::admit_with(session, config, settings, prompt, captured, inbox)?),
37 None => None,
38 };
39 Ok(RunJournal {
40 run,
41 model,
42 error: None,
43 ledger_counts_turns: false,
44 })
45 }
46
47 pub fn reopen(session: &Session, operation_id: &str, model: (u64, u64)) -> Result<Self, String> {
49 Ok(RunJournal {
50 run: Some(Run::reopen(session, operation_id)?),
51 model,
52 error: None,
53 ledger_counts_turns: false,
54 })
55 }
56
57 pub fn held_until(&self) -> Option<std::time::Instant> {
58 self.run
59 .as_ref()
60 .filter(|_| self.error.is_none())
61 .and_then(Run::held_until)
62 }
63
64 pub fn flush_held(&mut self, session: &mut Session) {
65 self.apply(session, Run::flush_held);
66 }
67
68 pub fn ledger_counts_turns(&mut self) {
70 self.ledger_counts_turns = true;
71 }
72
73 pub fn run(&self) -> Option<&Run> {
75 self.run.as_ref()
76 }
77
78 fn apply(&mut self, session: &mut Session, f: impl FnOnce(&mut Run, &mut Session) -> Result<(), String>) {
79 if self.error.is_some() {
80 return;
81 }
82 if let Some(run) = self.run.as_mut()
83 && let Err(e) = f(run, session)
84 {
85 self.error = Some(e);
86 }
87 }
88
89 pub fn event(&mut self, session: &mut Session, event: &AgentEvent) {
90 let (max_tokens, context_window) = self.model;
91 match event {
92 AgentEvent::TurnStart => self.apply(session, |run, s| run.begin_assistant(s, max_tokens, context_window)),
93 AgentEvent::MessageStart {
94 message: Message::Assistant(partial),
95 } => {
96 let event = json!({"type": "start", "partial": partial});
97 self.apply(session, |run, s| run.stream_event(s, &event));
98 }
99 AgentEvent::MessageUpdate {
100 assistant_message_event,
101 ..
102 } => {
103 if let Some(event) = frame_source(assistant_message_event) {
104 self.apply(session, |run, s| run.stream_event(s, &event));
105 }
106 }
107 AgentEvent::MessageEnd {
108 message: Message::Assistant(message),
109 } => {
110 if let Ok(value) = serde_json::to_value(message) {
111 let count = !self.ledger_counts_turns;
112 self.apply(session, |run, s| {
113 if count {
114 run.record_turn(s, &value)?;
115 }
116 run.commit_assistant(s, value.clone()).map(|_| ())
117 });
118 }
119 }
120 AgentEvent::ToolExecutionStart { tool_call_id, args, .. } => {
121 self.apply(session, |run, s| run.tool_started(s, tool_call_id, args.clone()));
122 }
123 AgentEvent::MessageEnd {
124 message: Message::ToolResult(result),
125 } => {
126 if let Ok(value) = serde_json::to_value(result) {
127 self.apply(session, |run, s| {
128 run.tool_finished(s, &result.tool_call_id, value.clone())
129 });
130 }
131 }
132 _ => {}
133 }
134 }
135
136 pub fn begin_with(&mut self, session: &mut Session, before: Vec<session_journal::Write>, trigger: Option<String>) {
138 let (max_tokens, context_window) = self.model;
139 self.apply(session, |run, s| {
140 run.begin_assistant_with(s, max_tokens, context_window, before, trigger)
141 });
142 }
143
144 pub fn set_stream_options(&mut self, options: Value) {
145 if let Some(run) = self.run.as_mut() {
146 run.set_stream_options(options);
147 }
148 }
149
150 pub fn set_retry_policy(&mut self, policy: Value) {
151 if let Some(run) = self.run.as_mut() {
152 run.set_retry_policy(policy);
153 }
154 }
155
156 pub fn schedule_retry(&mut self, not_before: i64, error: String) {
157 if let Some(run) = self.run.as_mut() {
158 run.schedule_retry(not_before, error);
159 }
160 }
161
162 pub fn set_inbox(&mut self, inbox: Value) {
164 if let Some(run) = self.run.as_mut() {
165 run.set_inbox(inbox);
166 }
167 }
168
169 pub fn request_cancel(&mut self, session: &mut Session, at: i64) {
171 self.apply(session, |run, s| run.request_cancel(s, at));
172 }
173
174 pub fn finish_aborted(&self, session: &mut Session) -> Result<(), String> {
178 match &self.run {
179 Some(run) => run.finish_aborted(session),
180 None => Ok(()),
181 }
182 }
183
184 pub fn finish(&self, session: Option<&mut Session>, failure: Option<(&str, &str)>) -> Result<(), String> {
187 let failure = match &self.error {
188 Some(error) => Some(("journal_write_failed", error.as_str())),
189 None => failure,
190 };
191 match (&self.run, session) {
192 (Some(run), Some(session)) => run.finish(session, failure),
193 _ => Ok(()),
194 }
195 }
196
197 pub fn fail_configuration(
198 self,
199 session: &mut Session,
200 code: &str,
201 message: &str,
202 details: Value,
203 ) -> Result<(), String> {
204 if let Some(error) = self.error {
205 return Err(error);
206 }
207 match self.run {
208 Some(run) => run.fail_configuration(session, code, message, details),
209 None => Ok(()),
210 }
211 }
212
213 pub fn compact_with_answer(&mut self, session: &Session, prepared: Value) {
214 if let Some(run) = self.run.as_mut() {
215 run.compact_with_answer(session, prepared);
216 }
217 }
218
219 pub fn begin_compaction(
220 &mut self,
221 session: &mut Session,
222 reason: &str,
223 prepared: Value,
224 resume_after: Option<Value>,
225 ) {
226 self.apply(session, |run, s| {
227 run.begin_compaction(s, reason, prepared, resume_after)
228 });
229 }
230
231 pub fn compaction_request(&mut self, session: &mut Session, retry: &ai::retry::RetryPolicy) -> Option<String> {
233 let mut id = None;
234 self.apply(session, |run, s| {
235 id = Some(run.compaction_request(s, retry.journal_value())?);
236 Ok(())
237 });
238 id
239 }
240
241 pub fn compaction_task_id(&self) -> Option<String> {
243 self.run.as_ref()?.compaction_task_id()
244 }
245
246 pub fn compaction_retry_wait(
247 &mut self,
248 session: &mut Session,
249 usage: Option<&Value>,
250 error: &str,
251 not_before: i64,
252 ) {
253 self.apply(session, |run, s| run.compaction_retry_wait(s, usage, error, not_before));
254 }
255
256 pub fn compaction_retry(&mut self, session: &mut Session) {
257 self.apply(session, |run, s| run.compaction_retry(s));
258 }
259
260 pub fn compaction_usage(&mut self, session: &mut Session, usage: &Value) {
261 self.apply(session, |run, s| run.compaction_usage(s, usage));
262 }
263
264 pub fn complete_compaction(&mut self, session: &mut Session, id: &str, entry: serde_json::Map<String, Value>) {
265 self.apply(session, |run, s| run.complete_compaction(s, id, entry));
266 }
267
268 pub fn complete_compaction_from_hook(
270 &mut self,
271 session: &mut Session,
272 entry: serde_json::Map<String, Value>,
273 usage: Option<Value>,
274 ) -> Option<String> {
275 let mut id = None;
276 self.apply(session, |run, s| {
277 id = Some(run.complete_compaction_from_hook(s, entry, usage)?);
278 Ok(())
279 });
280 id
281 }
282
283 pub fn decline_compaction(&mut self, session: &mut Session, placement: Vec<session_journal::Write>) -> bool {
285 let mut resumed = false;
286 self.apply(session, |run, s| {
287 resumed = run.decline_compaction(s, placement)?;
288 Ok(())
289 });
290 resumed
291 }
292
293 pub fn abandon_compaction(&mut self) {
294 if let Some(run) = self.run.as_mut() {
295 run.abandon_compaction();
296 }
297 }
298
299 pub fn error(&self) -> Option<&str> {
301 self.error.as_deref()
302 }
303}
304
305pub fn update_fields(message: &agent::AgentMessage, event: &AssistantMessageEvent) -> (Value, Value) {
309 let mut frame = frame_source(event).unwrap_or(Value::Null);
310 if frame["type"] == "toolcall_start"
311 && let Some(index) = frame["contentIndex"].as_u64()
312 {
313 let call = frame["partial"]["content"][index as usize].clone();
314 frame["id"] = call["id"].clone();
315 frame["toolName"] = call["name"].clone();
316 }
317 if let Some(map) = frame.as_object_mut() {
318 map.shift_remove("partial");
319 }
320 let usage = match message {
321 ai::Message::Assistant(assistant) => serde_json::to_value(&assistant.usage).unwrap_or(Value::Null),
322 _ => Value::Null,
323 };
324 (frame, usage)
325}
326
327pub fn frame_source(event: &AssistantMessageEvent) -> Option<Value> {
330 use AssistantMessageEvent::{TextDelta, ThinkingDelta, ToolCallDelta};
331 let (kind, index, delta) = match event {
332 TextDelta {
333 content_index, delta, ..
334 } => ("text_delta", content_index, delta),
335 ThinkingDelta {
336 content_index, delta, ..
337 } => ("thinking_delta", content_index, delta),
338 ToolCallDelta {
339 content_index, delta, ..
340 } => ("toolcall_delta", content_index, delta),
341 other => return serde_json::to_value(other).ok(),
342 };
343 Some(json!({"type": kind, "contentIndex": index, "delta": delta}))
344}