xonecas.ioDon't click! Sean Caetano Martin Sign in
cast / src / agent / stream.rs 140 lines4.4 kB Raw
1use serde_json::Value;
2
3#[derive(Default)]
4pub struct Parser {
5    text: String,
6    result: Option<Result<String, String>>,
7}
8
9const KEYS: [&str; 7] = [
10    "command",
11    "file_path",
12    "filePath",
13    "path",
14    "pattern",
15    "url",
16    "description",
17];
18
19impl Parser {
20    pub fn feed(&mut self, line: &str) -> Vec<String> {
21        let Ok(v) = serde_json::from_str::<Value>(line) else {
22            return if line.trim().is_empty() {
23                vec![]
24            } else {
25                vec![line.to_string()]
26            };
27        };
28        match v["type"].as_str().unwrap_or("") {
29            "assistant" => v["message"]["content"]
30                .as_array()
31                .into_iter()
32                .flatten()
33                .flat_map(|c| match c["type"].as_str() {
34                    Some("text") => self.text(c["text"].as_str()),
35                    Some("tool_use") => vec![tool(c["name"].as_str(), &c["input"])],
36                    _ => vec![],
37                })
38                .collect(),
39            "text" => self.text(v["part"]["text"].as_str()),
40            "tool_use" => vec![tool(
41                v["part"]["tool"].as_str(),
42                &v["part"]["state"]["input"],
43            )],
44            "result" => {
45                let body = v["result"].as_str().unwrap_or_default().to_string();
46                let failed = v["is_error"].as_bool().unwrap_or(false);
47                self.result = Some(if failed { Err(body) } else { Ok(body) });
48                vec![]
49            }
50            "error" => {
51                let msg = v["error"]["data"]["message"]
52                    .as_str()
53                    .or(v["error"]["message"].as_str());
54                let msg = msg
55                    .map(str::to_string)
56                    .unwrap_or_else(|| v["error"].to_string());
57                self.result = Some(Err(msg.clone()));
58                vec![format!("error: {msg}")]
59            }
60            _ => vec![],
61        }
62    }
63
64    fn text(&mut self, t: Option<&str>) -> Vec<String> {
65        let t = t.unwrap_or_default().trim();
66        if !t.is_empty() {
67            self.text = t.to_string();
68        }
69        t.lines()
70            .filter(|l| !l.trim().is_empty())
71            .map(str::to_string)
72            .collect()
73    }
74
75    pub fn finish(self, exited_ok: bool, stderr: &str) -> Result<String, String> {
76        match self.result {
77            Some(r) => r,
78            None if exited_ok && !self.text.is_empty() => Ok(self.text),
79            None => {
80                let tail: Vec<&str> = stderr.lines().rev().take(3).collect();
81                let tail: Vec<&str> = tail.into_iter().rev().collect();
82                Err(if tail.is_empty() {
83                    "agent exited without an answer".into()
84                } else {
85                    tail.join("\n")
86                })
87            }
88        }
89    }
90}
91
92fn tool(name: Option<&str>, input: &Value) -> String {
93    let arg = KEYS
94        .iter()
95        .find_map(|k| input[*k].as_str())
96        .unwrap_or_default();
97    let arg: String = arg
98        .lines()
99        .next()
100        .unwrap_or_default()
101        .chars()
102        .take(100)
103        .collect();
104    format!("$ {} {arg}", name.unwrap_or("tool").to_lowercase())
105}
106
107#[cfg(test)]
108mod tests {
109    use super::*;
110
111    #[test]
112    fn claude_stream_yields_tools_and_result() {
113        let mut p = Parser::default();
114        let lines = p.feed(r#"{"type":"assistant","message":{"content":[{"type":"text","text":"Building\nnow"},{"type":"tool_use","name":"Bash","input":{"command":"cargo build"}}]}}"#);
115        assert_eq!(
116            lines,
117            vec![
118                "Building".to_string(),
119                "now".to_string(),
120                "$ bash cargo build".to_string()
121            ]
122        );
123        p.feed(r#"{"type":"result","is_error":false,"result":"all good"}"#);
124        assert_eq!(p.finish(true, ""), Ok("all good".into()));
125    }
126
127    #[test]
128    fn opencode_stream_uses_last_text() {
129        let mut p = Parser::default();
130        p.feed(r#"{"type":"tool_use","part":{"tool":"read","state":{"input":{"filePath":"src/a.rs"}}}}"#);
131        p.feed(r#"{"type":"text","part":{"text":"{\"tasks\":[]}"}}"#);
132        assert_eq!(p.finish(true, ""), Ok("{\"tasks\":[]}".into()));
133    }
134
135    #[test]
136    fn failure_reports_stderr_tail() {
137        let p = Parser::default();
138        assert_eq!(p.finish(false, "a\nb\nc\nd"), Err("b\nc\nd".into()));
139    }
140}