Skip to main content

read_stream

Function read_stream 

Source
pub fn read_stream(text: &str) -> Result<StreamFacts, String>
Expand description

Read a Claude Code --output-format stream-json --verbose transcript. Lines that are not JSON objects are skipped; a transcript with neither a request nor a result event is an error, because a session that reported nothing must be recorded as having reported nothing, not as having used zero tokens.

use majordomus_cli::economics::usage::read_stream;
assert!(read_stream("").is_err(), "a silent transcript is not zero tokens");
let stream = concat!(
    r#"{"type":"system","subtype":"init","tools":["Read","Bash"],"#,
    r#""mcp_servers":[{"name":"majordomus"}]}"#, "\n",
    "not json\n",
    r#"{"type":"result","subtype":"error_max_turns","is_error":true,"num_turns":9}"#,
);
let facts = read_stream(stream).unwrap();
assert_eq!(facts.tools_offered, ["Read", "Bash"]);
assert_eq!(facts.mcp_servers, ["majordomus"]);
let ending = (facts.ended.as_str(), facts.is_error, facts.turns);
assert_eq!(ending, ("error_max_turns", true, Some(9)));
assert!(facts.requests.is_empty() && facts.reported_cost_microusd.is_none());