neosian 3.0.3

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! Pi's JSON stream read for the record (X5a), with the state one turn
//! needs. Pi 1.7.0's documentation (`json.md`) and its agent loop
//! (`pi-agent-core/dist/agent-loop.js`) give the rules, which held for
//! live turns with a local model (X7a):
//!
//! - The session header names the session; another header naming another
//!   session contradicts the turn.
//! - Each assistant `message_end` is authoritative and replaces the answer
//!   candidate with its text blocks; the last one is the answer.
//! - Every tool call, refused or not, is `tool_execution_start`, then
//!   `tool_execution_end` with the result and `isError`, then a
//!   `toolResult` message: the first two are paired by `toolCallId` and
//!   recorded with an error result kept, as Pi's own recording extension
//!   keeps it; the message only corroborates, so a round is never recorded
//!   twice, and one that names no ended call contradicts the turn.
//! - `agent_end` can be followed by a retry or recovery; only
//!   `agent_settled` ends the run. A retry is open from an
//!   `auto_retry_start` (one for each attempt) to the one `auto_retry_end`
//!   that closes it. The turn completed when settlement is not aborted, no
//!   retry is open and none failed, every tool call
//!   started has ended, nothing contradicted it and the last assistant
//!   message stopped with `stop`. `length`, `error` and `aborted` do not
//!   complete it; nor does a stream that never settles.

use std::collections::HashMap;

use serde_json::{Map, Value, json};

use super::Said;
use crate::harness::pi::{role, text, words};

/// What the record holds of a Pi turn while it runs.
#[derive(Default)]
pub struct Reader {
    session: Option<String>,
    /// The last assistant message's stop reason.
    stop: Option<String>,
    /// Tool calls started and not ended, by ID, with their names.
    open: HashMap<String, String>,
    /// Tool calls ended, by ID, with whether their result is an error.
    ended: HashMap<String, bool>,
    /// A retry has begun and not ended.
    retrying: bool,
    /// A retry failed, or an event contradicts the turn.
    broken: bool,
    settled: bool,
    /// The bytes `open` and `ended` hold, charged to the turn's bound (X5d).
    held: u64,
}

impl Reader {
    /// One line of the stream; nothing once the run has settled.
    pub fn line(&mut self, event: &Map<String, Value>) -> Vec<Said> {
        if self.settled {
            return Vec::new();
        }
        let mut said = Vec::new();
        let id = text(event.get("toolCallId")).map(str::to_string);
        let name = text(event.get("toolName")).unwrap_or("tool").to_string();
        match text(event.get("type")).unwrap_or_default() {
            "session" => match (text(event.get("id")), &self.session) {
                (Some(session), None) => {
                    self.session = Some(session.to_string());
                    said.push(Said::Session(session.to_string()));
                }
                (Some(session), Some(known)) if session == known => {}
                _ => self.broken = true,
            },
            "message_end" => self.message(event.get("message"), &mut said),
            "tool_execution_start" => match id {
                Some(id) if !self.open.contains_key(&id) && !self.ended.contains_key(&id) => {
                    self.held += (id.len() + name.len()) as u64;
                    self.open.insert(id.clone(), name.clone());
                    let input = event.get("args").cloned().unwrap_or(json!({}));
                    said.push(Said::Call { id, name, input });
                }
                _ => self.broken = true,
            },
            "tool_execution_end" => match self.close(id) {
                Some((id, started)) if started == name => {
                    let error = event.get("isError") == Some(&Value::Bool(true));
                    self.held += id.len() as u64 + 1;
                    self.ended.insert(id.clone(), error);
                    let content = event.get("result").and_then(|r| r.get("content"));
                    let response = json!({"content": content, "isError": error});
                    said.push(Said::Result {
                        id,
                        response,
                        ok: true,
                    });
                }
                _ => self.broken = true,
            },
            "auto_retry_start" => self.retrying = true,
            "auto_retry_end" => {
                let failed = event.get("success") != Some(&Value::Bool(true));
                self.broken |= failed || !self.retrying;
                self.retrying = false;
            }
            "agent_settled" => {
                self.settled = true;
                said.push(if self.completed(event) {
                    Said::Completed
                } else {
                    Said::Failed
                });
            }
            _ => {}
        }
        said
    }

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

    /// The started call `id`, taken out of the open calls.
    fn close(&mut self, id: Option<String>) -> Option<(String, String)> {
        let (id, name) = self.open.remove_entry(&id?)?;
        self.held -= (id.len() + name.len()) as u64;
        Some((id, name))
    }

    fn message(&mut self, message: Option<&Value>, said: &mut Vec<Said>) {
        match role(message) {
            Some("assistant") => {
                let stop = message.and_then(|m| text(m.get("stopReason")));
                self.stop = stop.map(str::to_string);
                said.push(Said::Answer(words(message)));
            }
            Some("toolResult") => {
                let id = text(message.and_then(|m| m.get("toolCallId")));
                let error = message.and_then(|m| m.get("isError")) == Some(&Value::Bool(true));
                let ended = id.and_then(|id| self.ended.get(id));
                self.broken |= ended != Some(&error);
            }
            _ => {}
        }
    }

    fn completed(&self, settled: &Map<String, Value>) -> bool {
        settled.get("aborted") == Some(&Value::Bool(false))
            && self.session.is_some()
            && !self.broken
            && !self.retrying
            && self.open.is_empty()
            && self.stop.as_deref() == Some("stop")
    }
}

#[cfg(test)]
mod tests;