neosian 3.0.1

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! Cursor's `stream-json` read for the record (X5b), with the state one
//! turn needs. The rules come from the 2026.09.10-fd3934a print handler and
//! held for live 2026.11.22-e9042b2 turns (X7a; they also print `thinking`
//! events, which carry the chat and are otherwise not read):
//!
//! - `system`/`init` names the chat; every later event carries the same
//!   `session_id`, and one that names another contradicts the turn.
//! - `tool_call` `started` and `completed` pair by `call_id`; each holds
//!   the call in protobuf JSON form, one member naming its kind, and the
//!   completed one has `args` and `result`, which the record keeps as the
//!   call's input and result. A completion with no start, one of another
//!   kind than the call that started under its ID (X7c Y8), a start never
//!   completed, or a call of another shape contradicts the turn.
//! - Cursor prints a failed turn only on stderr and exits 1; the stream's
//!   `result` is printed only on success. The turn completed when that
//!   result says `success` with `is_error` false, under the chat init named,
//!   with nothing contradicted: its `result` text is the answer. A stream
//!   without one is not complete, whatever its last assistant chunk said.

use std::collections::{HashMap, HashSet};

use serde_json::{Map, Value};

use super::Said;
use crate::harness::cursor::{name, text, tool};

/// What the record holds of a Cursor turn while it runs.
#[derive(Default)]
pub struct Reader {
    session: Option<String>,
    /// Each started call's ID and its kind.
    open: HashMap<String, String>,
    ended: HashSet<String>,
    broken: bool,
    done: bool,
    /// The bytes `open` and `ended` hold, charged to the turn's bound (X5d).
    held: u64,
}

impl Reader {
    /// What the reader holds of the turn, in bytes.
    pub fn held(&self) -> u64 {
        self.held
    }

    /// One line of the stream; nothing once the result was read.
    pub fn line(&mut self, event: &Map<String, Value>) -> Vec<Said> {
        if self.done {
            return Vec::new();
        }
        let kind = text(event.get("type")).unwrap_or_default();
        let subtype = text(event.get("subtype"));
        let init = kind == "system" && subtype == Some("init");
        let mut said = Vec::new();
        match (&self.session, text(event.get("session_id"))) {
            (None, Some(session)) if init => {
                self.session = Some(session.to_string());
                said.push(Said::Session(session.to_string()));
            }
            (Some(known), Some(session)) if known != session => self.broken = true,
            (None, _) => self.broken = true,
            _ => {}
        }
        let id = text(event.get("call_id")).map(str::to_string);
        match (kind, subtype) {
            ("tool_call", Some("started")) => match (id, tool(event)) {
                (Some(id), Some((kind, _)))
                    if !self.open.contains_key(&id) && !self.ended.contains(&id) =>
                {
                    self.held += (id.len() + kind.len()) as u64;
                    self.open.insert(id, kind.to_string());
                }
                _ => self.broken = true,
            },
            ("tool_call", Some("completed")) => {
                let call = tool(event).filter(|(_, value)| value.contains_key("args"));
                let result = call.and_then(|(_, value)| value.get("result"));
                match (id, call, result) {
                    (Some(id), Some((kind, value)), Some(Value::Object(_)))
                        if self.open.get(&id).is_some_and(|started| started == kind) =>
                    {
                        self.open.remove(&id);
                        // Out of `open`, into `ended`: the same bytes held.
                        self.ended.insert(id.clone());
                        said.push(Said::Tool {
                            id: Some(id),
                            name: name(kind, value),
                            input: value["args"].clone(),
                            response: value["result"].clone(),
                        });
                    }
                    _ => self.broken = true,
                }
            }
            ("result", subtype) => {
                self.done = true;
                let success = subtype == Some("success")
                    && event.get("is_error") == Some(&Value::Bool(false))
                    && self.open.is_empty()
                    && !self.broken;
                match text(event.get("result")).filter(|_| success) {
                    Some(answer) => {
                        said.push(Said::Answer(answer.to_string()));
                        said.push(Said::Completed);
                    }
                    None => said.push(Said::Failed),
                }
            }
            _ => {}
        }
        said
    }
}

#[cfg(test)]
mod tests;