use agent::AgentEvent;
use ai::{AssistantMessageEvent, Message};
use serde_json::{Value, json};
use session_journal::Session;
use session_journal::run::Run;
pub struct RunJournal {
run: Option<Run>,
model: (u64, u64),
error: Option<String>,
ledger_counts_turns: bool,
}
impl RunJournal {
pub fn admit(
session: Option<&mut Session>,
config: Value,
prompt: Value,
model: (u64, u64),
settings: Value,
captured: &[(String, Value)],
inbox: Value,
) -> Result<Self, String> {
let run = match session {
Some(session) => Some(Run::admit_with(session, config, settings, prompt, captured, inbox)?),
None => None,
};
Ok(RunJournal {
run,
model,
error: None,
ledger_counts_turns: false,
})
}
pub fn reopen(session: &Session, operation_id: &str, model: (u64, u64)) -> Result<Self, String> {
Ok(RunJournal {
run: Some(Run::reopen(session, operation_id)?),
model,
error: None,
ledger_counts_turns: false,
})
}
pub fn held_until(&self) -> Option<std::time::Instant> {
self.run
.as_ref()
.filter(|_| self.error.is_none())
.and_then(Run::held_until)
}
pub fn flush_held(&mut self, session: &mut Session) {
self.apply(session, Run::flush_held);
}
pub fn ledger_counts_turns(&mut self) {
self.ledger_counts_turns = true;
}
pub fn run(&self) -> Option<&Run> {
self.run.as_ref()
}
fn apply(&mut self, session: &mut Session, f: impl FnOnce(&mut Run, &mut Session) -> Result<(), String>) {
if self.error.is_some() {
return;
}
if let Some(run) = self.run.as_mut()
&& let Err(e) = f(run, session)
{
self.error = Some(e);
}
}
pub fn event(&mut self, session: &mut Session, event: &AgentEvent) {
let (max_tokens, context_window) = self.model;
match event {
AgentEvent::TurnStart => self.apply(session, |run, s| run.begin_assistant(s, max_tokens, context_window)),
AgentEvent::MessageStart {
message: Message::Assistant(partial),
} => {
let event = json!({"type": "start", "partial": partial});
self.apply(session, |run, s| run.stream_event(s, &event));
}
AgentEvent::MessageUpdate {
assistant_message_event,
..
} => {
if let Some(event) = frame_source(assistant_message_event) {
self.apply(session, |run, s| run.stream_event(s, &event));
}
}
AgentEvent::MessageEnd {
message: Message::Assistant(message),
} => {
if let Ok(value) = serde_json::to_value(message) {
let count = !self.ledger_counts_turns;
self.apply(session, |run, s| {
if count {
run.record_turn(s, &value)?;
}
run.commit_assistant(s, value.clone()).map(|_| ())
});
}
}
AgentEvent::ToolExecutionStart { tool_call_id, args, .. } => {
self.apply(session, |run, s| run.tool_started(s, tool_call_id, args.clone()));
}
AgentEvent::MessageEnd {
message: Message::ToolResult(result),
} => {
if let Ok(value) = serde_json::to_value(result) {
self.apply(session, |run, s| {
run.tool_finished(s, &result.tool_call_id, value.clone())
});
}
}
_ => {}
}
}
pub fn begin_with(&mut self, session: &mut Session, before: Vec<session_journal::Write>, trigger: Option<String>) {
let (max_tokens, context_window) = self.model;
self.apply(session, |run, s| {
run.begin_assistant_with(s, max_tokens, context_window, before, trigger)
});
}
pub fn set_stream_options(&mut self, options: Value) {
if let Some(run) = self.run.as_mut() {
run.set_stream_options(options);
}
}
pub fn set_retry_policy(&mut self, policy: Value) {
if let Some(run) = self.run.as_mut() {
run.set_retry_policy(policy);
}
}
pub fn schedule_retry(&mut self, not_before: i64, error: String) {
if let Some(run) = self.run.as_mut() {
run.schedule_retry(not_before, error);
}
}
pub fn set_inbox(&mut self, inbox: Value) {
if let Some(run) = self.run.as_mut() {
run.set_inbox(inbox);
}
}
pub fn request_cancel(&mut self, session: &mut Session, at: i64) {
self.apply(session, |run, s| run.request_cancel(s, at));
}
pub fn finish_aborted(&self, session: &mut Session) -> Result<(), String> {
match &self.run {
Some(run) => run.finish_aborted(session),
None => Ok(()),
}
}
pub fn finish(&self, session: Option<&mut Session>, failure: Option<(&str, &str)>) -> Result<(), String> {
let failure = match &self.error {
Some(error) => Some(("journal_write_failed", error.as_str())),
None => failure,
};
match (&self.run, session) {
(Some(run), Some(session)) => run.finish(session, failure),
_ => Ok(()),
}
}
pub fn fail_configuration(
self,
session: &mut Session,
code: &str,
message: &str,
details: Value,
) -> Result<(), String> {
if let Some(error) = self.error {
return Err(error);
}
match self.run {
Some(run) => run.fail_configuration(session, code, message, details),
None => Ok(()),
}
}
pub fn compact_with_answer(&mut self, session: &Session, prepared: Value) {
if let Some(run) = self.run.as_mut() {
run.compact_with_answer(session, prepared);
}
}
pub fn begin_compaction(
&mut self,
session: &mut Session,
reason: &str,
prepared: Value,
resume_after: Option<Value>,
) {
self.apply(session, |run, s| {
run.begin_compaction(s, reason, prepared, resume_after)
});
}
pub fn compaction_request(&mut self, session: &mut Session, retry: &ai::retry::RetryPolicy) -> Option<String> {
let mut id = None;
self.apply(session, |run, s| {
id = Some(run.compaction_request(s, retry.journal_value())?);
Ok(())
});
id
}
pub fn compaction_task_id(&self) -> Option<String> {
self.run.as_ref()?.compaction_task_id()
}
pub fn compaction_retry_wait(
&mut self,
session: &mut Session,
usage: Option<&Value>,
error: &str,
not_before: i64,
) {
self.apply(session, |run, s| run.compaction_retry_wait(s, usage, error, not_before));
}
pub fn compaction_retry(&mut self, session: &mut Session) {
self.apply(session, |run, s| run.compaction_retry(s));
}
pub fn compaction_usage(&mut self, session: &mut Session, usage: &Value) {
self.apply(session, |run, s| run.compaction_usage(s, usage));
}
pub fn complete_compaction(&mut self, session: &mut Session, id: &str, entry: serde_json::Map<String, Value>) {
self.apply(session, |run, s| run.complete_compaction(s, id, entry));
}
pub fn complete_compaction_from_hook(
&mut self,
session: &mut Session,
entry: serde_json::Map<String, Value>,
usage: Option<Value>,
) -> Option<String> {
let mut id = None;
self.apply(session, |run, s| {
id = Some(run.complete_compaction_from_hook(s, entry, usage)?);
Ok(())
});
id
}
pub fn decline_compaction(&mut self, session: &mut Session, placement: Vec<session_journal::Write>) -> bool {
let mut resumed = false;
self.apply(session, |run, s| {
resumed = run.decline_compaction(s, placement)?;
Ok(())
});
resumed
}
pub fn abandon_compaction(&mut self) {
if let Some(run) = self.run.as_mut() {
run.abandon_compaction();
}
}
pub fn error(&self) -> Option<&str> {
self.error.as_deref()
}
}
pub fn update_fields(message: &agent::AgentMessage, event: &AssistantMessageEvent) -> (Value, Value) {
let mut frame = frame_source(event).unwrap_or(Value::Null);
if frame["type"] == "toolcall_start"
&& let Some(index) = frame["contentIndex"].as_u64()
{
let call = frame["partial"]["content"][index as usize].clone();
frame["id"] = call["id"].clone();
frame["toolName"] = call["name"].clone();
}
if let Some(map) = frame.as_object_mut() {
map.shift_remove("partial");
}
let usage = match message {
ai::Message::Assistant(assistant) => serde_json::to_value(&assistant.usage).unwrap_or(Value::Null),
_ => Value::Null,
};
(frame, usage)
}
pub fn frame_source(event: &AssistantMessageEvent) -> Option<Value> {
use AssistantMessageEvent::{TextDelta, ThinkingDelta, ToolCallDelta};
let (kind, index, delta) = match event {
TextDelta {
content_index, delta, ..
} => ("text_delta", content_index, delta),
ThinkingDelta {
content_index, delta, ..
} => ("thinking_delta", content_index, delta),
ToolCallDelta {
content_index, delta, ..
} => ("toolcall_delta", content_index, delta),
other => return serde_json::to_value(other).ok(),
};
Some(json!({"type": kind, "contentIndex": index, "delta": delta}))
}