Skip to main content

artifactize_core/agent/session/
events.rs

1//! Known JSONL event shapes parsed once when a conversation is opened.
2
3use crate::{
4    config::Backend,
5    llm::Attempt,
6    types::{RequestId, RunId, SessionId},
7};
8use rig_core::{
9    completion::ToolDefinition,
10    message::{AssistantContent, Message, ToolCall},
11};
12use serde::{Deserialize, Serialize};
13use serde_json::Value;
14use std::{collections::BTreeMap, path::PathBuf};
15
16#[derive(Debug, Clone, Serialize, Deserialize)]
17pub struct Event {
18    #[serde(default, skip_serializing_if = "Option::is_none")]
19    pub at: Option<crate::types::Timestamp>,
20    #[serde(default, skip_serializing_if = "Option::is_none")]
21    pub send: Option<usize>,
22    #[serde(flatten)]
23    pub kind: Kind,
24}
25impl Event {
26    /// The shared typed JSONL boundary. Unknown kinds and malformed known records are errors;
27    /// unknown header metadata remains compatible through Header::extra.
28    pub fn parse(bytes: &[u8]) -> Result<Self, serde_json::Error> {
29        serde_json::from_slice(bytes)
30    }
31}
32#[derive(Debug, Clone, Serialize, Deserialize)]
33#[serde(tag = "kind", rename_all = "lowercase")]
34pub enum Kind {
35    Review(Box<Header>),
36    Message(MessageEvent),
37    Attempt(Attempt),
38    End(End),
39    Send(Send),
40    Answer(Answer),
41    /// Typed navigation, not model text or part of replay history.
42    RunReference {
43        run: RunId,
44    },
45    /// Display-only single outcome while other tool calls from the same turn still run.
46    ToolOutcome(MessageEvent),
47    /// Display-only provider delivery; never part of replay history or usage calculations.
48    Delivery(Delivery),
49}
50#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
51#[serde(rename_all = "camelCase")]
52pub enum DeliveryKind {
53    Text,
54    Summary,
55}
56#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
57#[serde(rename_all = "camelCase")]
58pub enum DeliveryState {
59    Delta,
60    Complete,
61    Interrupted,
62}
63#[derive(Debug, Clone, Serialize, Deserialize)]
64#[serde(rename_all = "camelCase")]
65pub struct Delivery {
66    pub turn: usize,
67    pub attempt: usize,
68    pub block: crate::types::DeliveryBlock,
69    #[serde(rename = "contentKind")]
70    pub kind: DeliveryKind,
71    pub text: String,
72    pub state: DeliveryState,
73}
74
75#[derive(Debug, Clone, Default, Serialize, Deserialize)]
76#[serde(rename_all = "camelCase")]
77pub struct Header {
78    #[serde(default, skip_serializing_if = "Option::is_none")]
79    pub version: Option<u32>,
80    #[serde(default, skip_serializing_if = "Option::is_none")]
81    pub session_id: Option<SessionId>,
82    #[serde(default, skip_serializing_if = "Option::is_none")]
83    pub run_id: Option<RunId>,
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    pub request_id: Option<RequestId>,
86    #[serde(default, skip_serializing_if = "Option::is_none")]
87    pub backend: Option<Backend>,
88    #[serde(default, skip_serializing_if = "Option::is_none")]
89    pub model: Option<crate::config::ModelId>,
90    #[serde(default)]
91    pub reasoning: Option<crate::config::Reasoning>,
92    #[serde(default, skip_serializing_if = "Option::is_none")]
93    pub budgets: Option<Budgets>,
94    #[serde(default, skip_serializing_if = "Option::is_none")]
95    pub tools: Option<Vec<ToolDefinition>>,
96    #[serde(default, skip_serializing_if = "Option::is_none")]
97    pub producer: Option<crate::types::ProducerId>,
98    #[serde(default, skip_serializing_if = "Option::is_none")]
99    pub state: Option<crate::types::StateId>,
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub eval_id: Option<crate::types::EvalId>,
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub target: Option<crate::types::ArtifactName>,
104    /// Provider-specific parameters remain dynamic.
105    #[serde(default)]
106    pub parameters: Value,
107    // Unknown saved display metadata is retained for compatibility.
108    #[serde(flatten)]
109    pub extra: BTreeMap<String, Value>,
110}
111#[derive(Debug, Clone, Default, Serialize, Deserialize)]
112#[serde(rename_all = "camelCase")]
113pub struct Budgets {
114    #[serde(default, with = "crate::config::validation::milliseconds")]
115    pub timeout_ms: Option<std::time::Duration>,
116    #[serde(default)]
117    pub max_tool_calls: Option<u64>,
118    #[serde(default)]
119    pub max_tokens: Option<u64>,
120}
121#[derive(Debug, Clone, Serialize, Deserialize)]
122#[serde(rename_all = "camelCase", from = "MessageWire")]
123pub struct MessageEvent {
124    pub turn: usize,
125    message: Message,
126    #[serde(skip_serializing_if = "std::ops::Not::not")]
127    pub repair: bool,
128    #[serde(skip_serializing_if = "Vec::is_empty")]
129    pub is_error: Vec<bool>,
130    #[serde(skip_serializing_if = "Option::is_none")]
131    pub question: Option<String>,
132    // The complete message stays on the wire for replay; only the safe, known targets
133    // are exposed to the transcript. The key is the position in the assistant message.
134    #[serde(skip)]
135    targets: BTreeMap<usize, BuiltinTarget>,
136}
137
138#[derive(Deserialize)]
139#[serde(rename_all = "camelCase")]
140struct MessageWire {
141    #[serde(default)]
142    turn: usize,
143    message: Message,
144    #[serde(default)]
145    repair: bool,
146    #[serde(default)]
147    is_error: Vec<bool>,
148    question: Option<String>,
149}
150
151impl From<MessageWire> for MessageEvent {
152    fn from(wire: MessageWire) -> Self {
153        Self::new(
154            wire.turn,
155            wire.message,
156            wire.repair,
157            wire.is_error,
158            wire.question,
159        )
160    }
161}
162
163impl MessageEvent {
164    pub fn new(
165        turn: usize,
166        message: Message,
167        repair: bool,
168        is_error: Vec<bool>,
169        question: Option<String>,
170    ) -> Self {
171        let targets = match &message {
172            Message::Assistant { content, .. } => content
173                .iter()
174                .enumerate()
175                .filter_map(|(index, part)| match part {
176                    AssistantContent::ToolCall(call) => {
177                        BuiltinTarget::decode(call).map(|target| (index, target))
178                    }
179                    _ => None,
180                })
181                .collect(),
182            _ => BTreeMap::new(),
183        };
184        Self {
185            turn,
186            message,
187            repair,
188            is_error,
189            question,
190            targets,
191        }
192    }
193
194    pub fn message(&self) -> &Message {
195        &self.message
196    }
197
198    pub(crate) fn builtin_target_parts(
199        &self,
200        index: usize,
201    ) -> (Option<&std::path::Path>, Option<&str>) {
202        self.builtin_target(index).map_or((None, None), |target| {
203            (target.path.as_deref(), target.pattern.as_deref())
204        })
205    }
206
207    pub(super) fn builtin_target(&self, index: usize) -> Option<&BuiltinTarget> {
208        self.targets.get(&index)
209    }
210}
211
212#[derive(Debug, Clone)]
213pub(super) struct BuiltinTarget {
214    pub path: Option<PathBuf>,
215    pub pattern: Option<String>,
216}
217
218impl BuiltinTarget {
219    fn decode(call: &ToolCall) -> Option<Self> {
220        let name = call.function.name.as_str();
221        let builtin = ["read", "list", "glob", "grep", "view_image"]
222            .iter()
223            .any(|base| {
224                name == *base
225                    || name
226                        .strip_prefix(base)
227                        .is_some_and(|rest| rest.starts_with('_'))
228            });
229        builtin.then(|| {
230            let text = |field| call.function.arguments.get(field).and_then(Value::as_str);
231            Self {
232                path: text("path")
233                    .and_then(|path| artifactize_tools::files::path_from_text(path).ok()),
234                pattern: text("pattern").map(str::to_owned),
235            }
236        })
237    }
238}
239#[derive(Debug, Clone, Default, Serialize, Deserialize)]
240#[serde(rename_all = "camelCase")]
241pub struct Send {
242    #[serde(default, skip_serializing_if = "Option::is_none")]
243    pub text: Option<String>,
244    #[serde(default, skip_serializing_if = "Option::is_none")]
245    pub framing: Option<String>,
246    #[serde(default, skip_serializing_if = "Option::is_none")]
247    pub files_changed: Option<bool>,
248    #[serde(default, skip_serializing_if = "Option::is_none")]
249    pub tools: Option<Vec<crate::types::ToolName>>,
250}
251pub use super::outcome::{Answer, End};