neosian 3.0.3

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! What a turn's threads learned, read by the registry: the child's words
//! and the observed entries, the answer, the failure and how the turn
//! ended.

use std::sync::{Mutex, MutexGuard, PoisonError};
use std::time::Instant;

use serde_json::Value;

use super::super::adapter;
use super::super::events::{Event, Log, Tail, Text};
use super::DRAIN;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum End {
    Exited(i32),
    Stopped,
    TimedOut,
    /// The watcher died by a signal it did not send itself.
    Lost,
}

/// Whether an announced session already existed in this store.
pub type Announce = Box<dyn Fn(&str) -> bool + Send>;

/// What the threads learned, read by the registry.
#[derive(Default)]
pub struct Shared {
    pub text: Text,
    pub log: Log,
    pub last_text: Option<String>,
    pub answer: Option<String>,
    pub failure: Option<String>,
    /// The failure is the client's sign-in, which a later error never
    /// replaces (X4c).
    signin: bool,
    pub stderr: Tail,
    pub session: Option<String>,
    /// The announced session already existed when it was announced.
    pub existed: bool,
    /// What the watcher's filing of the turn said (X4a).
    pub filed: Option<Value>,
    /// The watcher said filing began: a stop no longer cuts the turn (X4e).
    pub filing: bool,
    pub end: Option<End>,
    pub(super) ended_at: Option<Instant>,
    pub(super) eof: bool,
}

impl Shared {
    pub(super) fn apply(&mut self, event: Event, announce: &mut Option<Announce>) {
        match event {
            Event::Session(session) => {
                if self.session.is_none() && adapter::session_ok(&session) {
                    if let Some(check) = announce.take() {
                        self.existed = check(&session);
                    }
                    self.session = Some(session);
                }
            }
            Event::Text(text) => {
                if self.text.total() > 0 {
                    self.text.push("\n");
                }
                self.text.push(&text);
                self.last_text = Some(text);
            }
            Event::Delta(text) => self.text.push(&text),
            Event::Answer(answer) => self.answer = Some(answer),
            Event::Observed(entry) => self.log.push(entry),
            Event::Failure(failure) if !self.signin => {
                self.log.push(serde_json::json!({"kind": "failure"}));
                self.failure = Some(failure);
            }
            Event::Failure(_) => {}
            Event::SignIn(instruction) => {
                if !self.signin && self.failure.is_none() {
                    self.log.push(serde_json::json!({"kind": "failure"}));
                }
                self.signin = true;
                self.failure = Some(instruction);
            }
        }
    }

    /// The turn is over and its output read (or the drain time has passed).
    pub fn ended(&self) -> bool {
        self.end.is_some() && (self.eof || self.ended_at.is_some_and(|at| at.elapsed() >= DRAIN))
    }

    pub fn final_answer(&self) -> Option<&str> {
        self.answer.as_deref().or(self.last_text.as_deref())
    }
}

pub fn lock(shared: &Mutex<Shared>) -> MutexGuard<'_, Shared> {
    shared.lock().unwrap_or_else(PoisonError::into_inner)
}