neosian 3.0.3

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! Pi's headless form (X5a), from Pi 1.7.0's installed documentation
//! (`json.md`, `cli.md`, `message-types.md`), its source and its run without
//! a provider (record/investigation-2026-11-28, section 1): `-p --mode json`
//! with the prompt on standard input only, an explicit agent directory and a
//! session directory of the child's own, project files, extensions, skills,
//! prompt templates, themes and context files off, no MCP at all
//! (`--no-mcp`), and the mode as Pi's own built-in tool allowlist. A new
//! session is named with `--session-id`; a continued one is opened by its
//! exact file with `--session`, since `--session-id` also creates a session
//! it does not find. Run live as a child with a local model behind an
//! OpenAI-compatible provider (X7a): a start, a continued session, write.

use std::path::{Path, PathBuf};

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

use super::adapter::{Mode, Plan, Request, Unplanned};
use super::events::{ERROR_BYTES, Event, head, observed};
use super::text::say;

/// Where a Pi child's state lies: the agent directory Pi reads its sign-in
/// and settings from, the child's own session directory, and the session's
/// file when the turn continues it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Paths {
    pub agent_dir: PathBuf,
    pub session_dir: PathBuf,
    pub file: Option<PathBuf>,
}

/// Pi's built-in tools for each mode; MCP is off in both.
pub fn tools(mode: Mode) -> &'static str {
    match mode {
        Mode::ReadOnly => "read,grep,find,ls",
        Mode::Write => "read,bash,edit,write",
    }
}

/// Every resource Pi would otherwise load from the project, the agent
/// directory or a package, off; and MCP off, every server and alias.
const OFF: [&str; 7] = [
    "--no-approve",
    "--no-extensions",
    "--no-mcp",
    "--no-skills",
    "--no-prompt-templates",
    "--no-themes",
    "--no-context-files",
];

fn shown(path: &Path) -> Result<String, Unplanned> {
    path.to_str().map(str::to_string).ok_or(Unplanned::PiState)
}

pub fn plan(request: &Request) -> Result<Plan, Unplanned> {
    let paths = request.pi.ok_or(Unplanned::PiState)?;
    let mut argv: Vec<String> = ["pi", "-p", "--mode", "json", "--offline", "--agent-dir"]
        .map(String::from)
        .to_vec();
    argv.push(shown(&paths.agent_dir)?);
    argv.extend(["--session-dir".to_string(), shown(&paths.session_dir)?]);
    argv.extend(OFF.map(String::from));
    argv.extend(["--tools".to_string(), tools(request.mode).to_string()]);
    if let Some(model) = request.model {
        argv.extend(["--model".to_string(), model.to_string()]);
    }
    match (request.resume, &paths.file) {
        (None, _) => argv.extend(["--session-id".to_string(), request.new_session.to_string()]),
        (Some(_), Some(file)) => argv.extend(["--session".to_string(), shown(file)?]),
        (Some(_), None) => return Err(Unplanned::PiState),
    }
    Ok(Plan {
        argv,
        env: Vec::new(),
    })
}

pub(super) fn text(value: Option<&Value>) -> Option<&str> {
    value.and_then(Value::as_str)
}

/// A message's text blocks, joined as Pi's own recording extension joins
/// them.
pub(super) fn words(message: Option<&Value>) -> String {
    let blocks = message.and_then(|m| m.get("content"));
    match blocks {
        Some(Value::String(said)) => said.clone(),
        Some(Value::Array(blocks)) => blocks
            .iter()
            .filter(|block| text(block.get("type")) == Some("text"))
            .filter_map(|block| text(block.get("text")))
            .collect::<Vec<_>>()
            .join("\n"),
        _ => String::new(),
    }
}

pub(super) fn role(message: Option<&Value>) -> Option<&str> {
    text(message.and_then(|m| m.get("role")))
}

/// The last assistant message an `agent_end` carries.
fn last_assistant(event: &Map<String, Value>) -> Option<&Value> {
    event
        .get("messages")
        .and_then(Value::as_array)?
        .iter()
        .rev()
        .find(|message| role(Some(message)) == Some("assistant"))
}

/// What a run that will not be retried ended with, when it did not succeed.
fn ended(message: &Value) -> Option<Event> {
    let stop = text(message.get("stopReason")).unwrap_or_default();
    match stop {
        "stop" | "toolUse" => None,
        "error" if text(message.get("errorMessage")).is_some() => {
            let said = text(message.get("errorMessage")).unwrap_or_default();
            Some(Event::Failure(head(said, ERROR_BYTES).to_string()))
        }
        _ => Some(Event::Failure(say("pi_incomplete", &[("reason", stop)]))),
    }
}

/// One line of Pi's JSON stream, for the parent's display: the session,
/// each assistant message's text once complete, tool calls and errors,
/// retries and how a run that ends unsuccessfully ended.
pub fn read(event: &Map<String, Value>) -> Vec<Event> {
    let mut events = Vec::new();
    let name = || json!(text(event.get("toolName")).unwrap_or_default());
    match text(event.get("type")).unwrap_or_default() {
        "session" => {
            if let Some(session) = text(event.get("id")) {
                events.push(Event::Session(session.to_string()));
            }
        }
        "message_end" if role(event.get("message")) == Some("assistant") => {
            let said = words(event.get("message"));
            if !said.is_empty() {
                events.push(Event::Text(said));
            }
        }
        "tool_execution_start" => events.push(observed("tool", &[("name", name())])),
        "tool_execution_end" if event.get("isError") == Some(&Value::Bool(true)) => {
            let said = words(event.get("result"));
            events.push(observed(
                "tool_error",
                &[("name", name()), ("text", json!(said))],
            ));
        }
        "auto_retry_start" => {
            let attempt = event.get("attempt").cloned().unwrap_or(Value::Null);
            let error = json!(text(event.get("errorMessage")).unwrap_or_default());
            events.push(observed("retry", &[("attempt", attempt), ("error", error)]));
        }
        "auto_retry_end" if event.get("success") == Some(&Value::Bool(false)) => {
            let said = text(event.get("finalError")).unwrap_or("retry failed");
            events.push(Event::Failure(head(said, ERROR_BYTES).to_string()));
        }
        "agent_end" if event.get("willRetry") != Some(&Value::Bool(true)) => {
            events.extend(last_assistant(event).and_then(ended));
        }
        "agent_settled" if event.get("aborted") == Some(&Value::Bool(true)) => {
            events.push(Event::Failure(say(
                "pi_incomplete",
                &[("reason", "aborted")],
            )));
        }
        _ => {}
    }
    events
}

#[cfg(test)]
mod tests;