use crate::context::ContextReader;
use crate::context::ir::{IrMessage, IrPart, build_tool_call, extract_text};
use crate::message::{
AssistantResponse, BashOutput, Context, ContextListing, ConversationMessage, Entry,
MessageKind, TextContent, ToolResultData,
};
use anyhow::Context as _;
use serde_json::Value;
use std::fs;
use std::io::{BufRead, BufReader};
use std::path::PathBuf;
pub struct JsonlReader {
file_path: Option<PathBuf>,
}
impl JsonlReader {
pub fn new(file_path: PathBuf) -> Self {
Self {
file_path: Some(file_path),
}
}
pub fn empty() -> Self {
Self { file_path: None }
}
}
impl ContextReader for JsonlReader {
fn list_contexts(&self) -> anyhow::Result<Vec<ContextListing>> {
let Some(file_path) = &self.file_path else {
return Ok(Vec::new());
};
let file =
fs::File::open(file_path).with_context(|| format!("open {}", file_path.display()))?;
let mut reader = BufReader::new(file);
let mut first_line = String::new();
reader
.read_line(&mut first_line)
.with_context(|| format!("read {}", file_path.display()))?;
let first_line = first_line.trim_end().to_string();
if first_line.is_empty() {
anyhow::bail!("empty file");
}
let session: Value = serde_json::from_str(&first_line)?;
if session["type"].as_str() != Some("session") {
anyhow::bail!("first line is not a session header");
}
let id = session["id"].as_str().unwrap_or("unknown").to_string();
let cwd = session["cwd"].as_str().unwrap_or("").to_string();
let detail = if cwd.is_empty() {
String::new()
} else {
format!("cwd: {cwd}")
};
Ok(vec![ContextListing {
id,
detail,
path: self.file_path.clone(),
}])
}
fn read_context(&self, _context_id: &str) -> anyhow::Result<Context> {
let Some(file_path) = &self.file_path else {
anyhow::bail!("no sessions found");
};
let file =
fs::File::open(file_path).with_context(|| format!("open {}", file_path.display()))?;
let reader = BufReader::new(file);
let mut entries = Vec::new();
let mut messages = Vec::new();
for (line_num, line_result) in reader.lines().enumerate() {
let line = line_result
.with_context(|| format!("{}:{}: read error", file_path.display(), line_num + 1))?;
if line.trim().is_empty() {
continue;
}
let entry_json: Value = serde_json::from_str(&line).with_context(|| {
format!("{}:{}: JSON parse error", file_path.display(), line_num + 1)
})?;
let entry_type = entry_json["type"].as_str().unwrap_or("").to_string();
if entry_type == "session" {
continue;
}
let id = entry_json["id"].as_str().unwrap_or("").to_string();
let parent_id = entry_json["parentId"].as_str().unwrap_or("").to_string();
if let Some(raw_msg) = entry_json.get("message") {
let kind = jsonl_build_message_kind(&entry_type, raw_msg);
let metadata = collect_metadata(&entry_json);
let mut message = ConversationMessage::new(id.clone(), kind);
message.metadata = metadata;
messages.push(message);
}
entries.push(Entry { id, parent_id });
}
Ok(Context { entries, messages })
}
}
fn jsonl_build_message_kind(msg_type: &str, msg: &Value) -> MessageKind {
let role = msg["role"].as_str().unwrap_or(msg_type).to_string();
let content = msg.get("content");
match role.as_str() {
"assistant" => {
let mut ir = IrMessage::new();
if let Some(Value::Array(parts)) = content {
for part in parts {
match part["type"].as_str() {
Some("text") => {
ir.push(IrPart::text(part["text"].as_str().unwrap_or("")));
}
Some("thinking" | "redacted_thinking") => {
if let Some(text) = part["text"].as_str() {
ir.push(IrPart::thinking(text));
}
}
Some("toolCall" | "tool_use") => {
let name = part["name"].as_str().unwrap_or("");
let arguments = part.get("arguments").or_else(|| part.get("input"));
ir.push(IrPart::tool_call(build_tool_call(name, arguments)));
}
_ => {}
}
}
}
MessageKind::AssistantResponse(AssistantResponse {
thinking: ir.thinking(),
tool_calls: ir.tool_calls(),
text: ir.text(),
})
}
"toolResult" | "bashExecution" => {
let content_str = extract_text(content);
if role == "bashExecution" {
let command = msg["command"].as_str().unwrap_or("").to_string();
MessageKind::BashOutput(BashOutput {
command,
output: content_str,
})
} else {
let tool_name = msg["toolName"].as_str().unwrap_or("").to_string();
let is_error = msg["isError"].as_bool().unwrap_or(false);
MessageKind::ToolResultData(ToolResultData {
tool_name,
content: content_str,
is_error,
})
}
}
_ => MessageKind::TextContent(TextContent {
role,
text: extract_text(content),
}),
}
}
fn collect_metadata(entry: &Value) -> std::collections::BTreeMap<String, Value> {
let mut metadata = std::collections::BTreeMap::new();
if let Some(message) = entry.get("message") {
if let Some(role) = message["role"].as_str() {
metadata.insert("role".to_string(), Value::String(role.to_string()));
}
}
if let Some(command) = entry["message"]["command"].as_str() {
metadata.insert("command".to_string(), Value::String(command.to_string()));
}
metadata
}