use std::path::PathBuf;
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Query {
pub limit: Option<u32>,
pub cursor: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Page {
pub turns: Vec<Turn>,
pub next_cursor: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Turn {
pub id: String,
pub status: Status,
pub items: Vec<Item>,
pub started_at: Option<i64>,
pub completed_at: Option<i64>,
pub duration_ms: Option<i64>,
pub error: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum Status {
InProgress,
Completed,
Interrupted,
Failed,
#[serde(other)]
Unknown,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(
tag = "type",
rename_all = "camelCase",
rename_all_fields = "camelCase"
)]
#[non_exhaustive]
pub enum Item {
UserMessage {
id: String,
content: Vec<UserContent>,
},
AgentMessage {
id: String,
text: String,
},
Thinking {
id: String,
text: String,
summarized: bool,
},
Plan {
id: String,
text: String,
},
ToolCall(ToolCall),
Other {
id: Option<String>,
kind: String,
raw: Value,
},
#[serde(untagged)]
Unknown(Value),
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(
tag = "type",
rename_all = "camelCase",
rename_all_fields = "camelCase"
)]
#[non_exhaustive]
pub enum UserContent {
Text {
text: String,
},
Image {
source: String,
},
Other {
kind: String,
},
#[serde(untagged)]
Unknown(Value),
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolCall {
pub id: String,
pub status: ToolStatus,
pub duration_ms: Option<i64>,
pub detail: ToolDetail,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum ToolStatus {
InProgress,
Completed,
Failed,
Declined,
#[serde(other)]
Unknown,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(
tag = "kind",
rename_all = "camelCase",
rename_all_fields = "camelCase"
)]
#[non_exhaustive]
pub enum ToolDetail {
Command {
command: String,
cwd: Option<PathBuf>,
output: Option<String>,
exit_code: Option<i32>,
},
FileChange {
changes: Vec<FileChange>,
},
Mcp {
server: String,
tool: String,
arguments: Value,
error: Option<String>,
},
Other {
name: String,
input: Value,
output: Option<String>,
},
#[serde(untagged)]
Unknown(Value),
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FileChange {
pub path: PathBuf,
pub kind: FileChangeKind,
pub diff: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(
tag = "type",
rename_all = "camelCase",
rename_all_fields = "camelCase"
)]
#[non_exhaustive]
pub enum FileChangeKind {
Add,
Delete,
Update {
move_path: Option<PathBuf>,
},
#[serde(untagged)]
Unknown(Value),
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
#[non_exhaustive]
pub enum Delta {
Text { text: String },
Thinking { text: String },
Output { text: String },
#[serde(untagged)]
Unknown(Value),
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Input {
pub text: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub images: Vec<Image>,
}
impl Input {
pub fn text(text: impl Into<String>) -> Self {
Self {
text: text.into(),
images: Vec::new(),
}
}
#[must_use]
pub fn with_images(mut self, images: Vec<Image>) -> Self {
self.images = images;
self
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Image {
pub path: std::path::PathBuf,
pub mime_type: String,
}
impl Image {
pub fn new(path: impl Into<std::path::PathBuf>, mime_type: impl Into<String>) -> Self {
Self {
path: path.into(),
mime_type: mime_type.into(),
}
}
pub(crate) async fn base64(&self) -> crate::Result<String> {
use base64::Engine as _;
let bytes =
tokio::fs::read(&self.path)
.await
.map_err(|source| crate::Error::ImageUnreadable {
path: self.path.clone(),
source,
})?;
Ok(base64::engine::general_purpose::STANDARD.encode(bytes))
}
}
pub(crate) fn user_content(input: &Input) -> Vec<UserContent> {
input
.images
.iter()
.map(|image| UserContent::Image {
source: image.path.display().to_string(),
})
.chain([UserContent::Text {
text: input.text.clone(),
}])
.collect()
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Receipt {
pub turn_id: String,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenCount {
pub input: i64,
pub cached_input: i64,
pub output: i64,
pub reasoning_output: i64,
pub total: i64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Usage {
pub last: TokenCount,
pub total: TokenCount,
pub context_window: Option<i64>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn images_are_recorded_before_the_text() {
let input =
Input::text("what is this?").with_images(vec![Image::new("/tmp/a.png", "image/png")]);
assert_eq!(
user_content(&input),
vec![
UserContent::Image {
source: "/tmp/a.png".into()
},
UserContent::Text {
text: "what is this?".into()
},
]
);
}
#[tokio::test]
async fn images_are_read_as_base64() {
let path = std::env::temp_dir().join(format!("stubb-image-{}.bin", std::process::id()));
std::fs::write(&path, b"hi").unwrap();
assert_eq!(
Image::new(&path, "image/png").base64().await.unwrap(),
"aGk="
);
std::fs::remove_file(&path).unwrap();
let missing = Image::new("/nonexistent/stubb.png", "image/png")
.base64()
.await;
assert_eq!(missing.unwrap_err().code(), "image_unreadable");
}
}