use std::path::PathBuf;
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use crate::perf::TokenUsage;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct HistoryMessage {
pub role: String,
pub content: String,
}
impl HistoryMessage {
pub fn user(content: impl Into<String>) -> Self {
Self {
role: "user".to_string(),
content: content.into(),
}
}
pub fn assistant(content: impl Into<String>) -> Self {
Self {
role: "assistant".to_string(),
content: content.into(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum IpcMessage {
Task {
id: String,
task: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
history: Option<Vec<HistoryMessage>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
session_reset: Option<bool>,
},
Result {
id: String,
content: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
summary: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
usage: Option<TokenUsage>,
status: String,
},
Error {
id: String,
error: String,
status: String,
},
}
impl IpcMessage {
pub fn new_task(task: impl Into<String>) -> Self {
IpcMessage::Task {
id: uuid::Uuid::new_v4().to_string(),
task: task.into(),
history: None,
session_reset: None,
}
}
#[allow(dead_code)]
pub fn new_task_with_history(task: impl Into<String>, history: Vec<HistoryMessage>) -> Self {
IpcMessage::Task {
id: uuid::Uuid::new_v4().to_string(),
task: task.into(),
history: if history.is_empty() {
None
} else {
Some(history)
},
session_reset: None,
}
}
#[allow(dead_code)]
pub fn new_result(id: impl Into<String>, content: impl Into<String>) -> Self {
IpcMessage::Result {
id: id.into(),
content: content.into(),
summary: None,
usage: None,
status: "success".into(),
}
}
#[allow(dead_code)]
pub fn new_result_with_summary(
id: impl Into<String>,
content: impl Into<String>,
summary: Option<String>,
) -> Self {
IpcMessage::Result {
id: id.into(),
content: content.into(),
summary,
usage: None,
status: "success".into(),
}
}
pub fn new_result_full(
id: impl Into<String>,
content: impl Into<String>,
summary: Option<String>,
usage: Option<TokenUsage>,
) -> Self {
IpcMessage::Result {
id: id.into(),
content: content.into(),
summary,
usage,
status: "success".into(),
}
}
pub fn new_error(id: impl Into<String>, error: impl Into<String>) -> Self {
IpcMessage::Error {
id: id.into(),
error: error.into(),
status: "error".into(),
}
}
}
pub fn serialize_message(msg: &IpcMessage) -> Result<String> {
let mut s = serde_json::to_string(msg).context("failed to serialize IpcMessage")?;
s.push('\n');
Ok(s)
}
pub fn parse_message(line: &str) -> Result<IpcMessage> {
let trimmed = line.trim_end_matches(['\n', '\r']);
serde_json::from_str::<IpcMessage>(trimmed)
.with_context(|| format!("failed to parse IpcMessage from line: {trimmed}"))
}
pub fn extract_summary(content: &str) -> String {
let lower = content.to_ascii_lowercase();
let mut best: Option<usize> = None;
let needle = "## summary";
let mut start = 0usize;
while let Some(pos) = lower[start..].find(needle) {
let abs = start + pos;
let at_line_start = abs == 0 || lower.as_bytes()[abs - 1] == b'\n';
if at_line_start {
best = Some(abs);
}
start = abs + needle.len();
}
if let Some(h) = best {
let after_header = &content[h..];
if let Some(nl) = after_header.find('\n') {
return after_header[nl + 1..].trim().to_string();
}
return String::new();
}
let trimmed = content.trim();
if trimmed.chars().count() <= 500 {
return trimmed.to_string();
}
let prefix: String = trimmed.chars().take(500).collect();
prefix
}
pub fn extract_files_from_content(content: &str) -> Vec<(PathBuf, String)> {
let lines: Vec<&str> = content.lines().collect();
let mut out: Vec<(PathBuf, String)> = Vec::new();
let mut i = 0;
while i < lines.len() {
let line = lines[i];
let trimmed = line.trim_start();
let rel_path: Option<String> = if let Some(rest) = trimmed.strip_prefix("## File:") {
Some(rest.trim().trim_matches('`').to_string())
} else if let Some(rest) = trimmed.strip_prefix("### File:") {
Some(rest.trim().trim_matches('`').to_string())
} else if let Some(rest) = trimmed.strip_prefix("### ") {
let s = rest.trim();
if s.starts_with('`') && s.ends_with('`') && s.len() >= 2 {
Some(s.trim_matches('`').to_string())
} else {
None
}
} else if let Some(rest) = trimmed.strip_prefix("## ") {
let s = rest.trim();
if s.starts_with('`') && s.ends_with('`') && s.len() >= 2 {
Some(s.trim_matches('`').to_string())
} else {
None
}
} else {
None
};
let Some(rel) = rel_path else {
i += 1;
continue;
};
if rel.is_empty() {
i += 1;
continue;
}
let mut j = i + 1;
while j < lines.len() && !lines[j].trim_start().starts_with("```") {
j += 1;
}
if j >= lines.len() {
break;
}
let body_start = j + 1;
let mut k = body_start;
while k < lines.len() && !lines[k].trim_start().starts_with("```") {
k += 1;
}
let body = if k > body_start {
lines[body_start..k].join("\n")
} else {
String::new()
};
let mut final_body = body;
if !final_body.ends_with('\n') {
final_body.push('\n');
}
out.push((PathBuf::from(rel), final_body));
i = k + 1;
}
out
}
#[cfg(test)]
mod tests;