neosian 3.0.1

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! The harnesses, the modes and one turn's plan (§40.50 items 4, 5, 8):
//! which executable, which argv vector, which variables beside the
//! server's own. The prompt is never part of a plan; it arrives on the
//! harness's standard input.

use std::path::Path;

use super::events::Event;
use super::{claude, codex, cursor, muse, opencode, pi, vibe};

mod check;
pub(super) use check::executable;
pub use check::{
    PROMPT_BYTES, Placed, bare_key, home, model_ok, place, prompt_ok, session_ok, which,
};

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Agent {
    OpenCode,
    Codex,
    ClaudeCode,
    Pi,
    Cursor,
    Vibe,
    Muse,
}

impl Agent {
    pub const ALL: [Self; 7] = [
        Self::OpenCode,
        Self::Codex,
        Self::ClaudeCode,
        Self::Pi,
        Self::Cursor,
        Self::Vibe,
        Self::Muse,
    ];
    pub const NAMES: [&'static str; 7] = [
        "opencode",
        "codex",
        "claude-code",
        "pi",
        "cursor",
        "vibe",
        "muse",
    ];

    pub fn parse(name: &str) -> Option<Self> {
        Self::ALL.into_iter().find(|agent| agent.name() == name)
    }

    /// The tool's name for it, which is also the record verb's `--agent`.
    pub fn name(self) -> &'static str {
        match self {
            Self::OpenCode => "opencode",
            Self::Codex => "codex",
            Self::ClaudeCode => "claude-code",
            Self::Pi => "pi",
            Self::Cursor => "cursor",
            Self::Vibe => "vibe",
            Self::Muse => "muse",
        }
    }

    /// The writer kind the record verb files this child's turns under, and
    /// the store names its conversation by: the tool's name, but Muse Code's
    /// own `muse-code`, as its ordinary recording names it (X6b).
    pub fn kind(self) -> &'static str {
        match self {
            Self::Muse => "muse-code",
            other => other.name(),
        }
    }

    /// Whether neosian names a new session's ID itself, so it is known
    /// before the harness announces it: Claude Code's `--session-id` and
    /// Pi's (X5a).
    pub fn names_session(self) -> bool {
        matches!(self, Self::ClaudeCode | Self::Pi | Self::Muse)
    }

    /// The executable looked up on the server's PATH.
    pub fn program(self) -> &'static str {
        match self {
            Self::OpenCode => "opencode",
            Self::Codex => "codex",
            Self::ClaudeCode => "claude",
            Self::Pi => "pi",
            Self::Cursor => "cursor-agent",
            Self::Vibe => "vibe",
            Self::Muse => "muse",
        }
    }

    /// One line of the harness's headless output, read.
    pub fn read(self, line: &str) -> Vec<Event> {
        let Ok(serde_json::Value::Object(event)) = serde_json::from_str(line) else {
            return Vec::new();
        };
        match self {
            Self::OpenCode => opencode::read(&event),
            Self::Codex => codex::read(&event),
            Self::ClaudeCode => claude::read(&event),
            Self::Pi => pi::read(&event),
            Self::Cursor => cursor::read(&event),
            Self::Vibe => vibe::read(&event),
            Self::Muse => muse::read(&event),
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Mode {
    ReadOnly,
    Write,
}

impl Mode {
    pub const NAMES: [&'static str; 2] = ["read-only", "write"];

    pub fn parse(name: &str) -> Option<Self> {
        match name {
            "read-only" => Some(Self::ReadOnly),
            "write" => Some(Self::Write),
            _ => None,
        }
    }

    pub fn name(self) -> &'static str {
        match self {
            Self::ReadOnly => "read-only",
            Self::Write => "write",
        }
    }
}

/// A Codex registration key that exists, with the tools it already
/// disables and its transport (X4c).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CodexKey {
    pub key: String,
    pub disabled: Vec<String>,
    /// The tools the entry already limits itself to, when it does.
    pub enabled: Option<Vec<String>>,
    pub transport: super::transport::Transport,
}

/// This neosian's own MCP server as a read-only child gets it (#431): the
/// running executable and its store selection, never a command read from a
/// file. With `mounted`, every mount is in `args` and read-only, so every
/// tool may be allowed; without (a profile selects the mounts), only the
/// tools that cannot change state are.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct McpServer {
    pub command: String,
    pub args: Vec<String>,
    pub mounted: bool,
}

/// The key the child's strict MCP configuration names this server under.
pub const SERVER_KEY: &str = "neosian";

/// The neosian tools that cannot change state, allowed by name when the
/// mounts cannot be made read-only.
pub const READ_ONLY_TOOLS: [&str; 10] = [
    "list_skills",
    "load_skill",
    "recall_turn",
    "search_history",
    "docs",
    "memory_history",
    "search_memory",
    "upkeep_review",
    "knowledge",
    "changes",
];

/// What one turn needs to be planned.
pub struct Request<'a> {
    pub agent: Agent,
    pub mode: Mode,
    pub model: Option<&'a str>,
    pub directory: &'a Path,
    /// The harness session to continue; None starts a new one.
    pub resume: Option<&'a str>,
    /// The session ID neosian chose for a new Claude Code session.
    pub new_session: &'a str,
    /// The turn's private directory (Codex's TMPDIR, holding the marker).
    pub private: &'a Path,
    /// Codex: which of our keys its configuration has.
    pub codex_keys: &'a [CodexKey],
    /// OpenCode: the `OPENCODE_CONFIG_CONTENT` the server itself carries.
    pub opencode_config: Option<&'a str>,
    /// The calling session, which the child's record hook names as parent.
    pub parent: Option<&'a str>,
    /// Read-only: this neosian's server, for Claude Code's strict
    /// configuration and Codex's entry arguments.
    pub server: Option<&'a McpServer>,
    /// Codex read-only: the other configured MCP servers, switched off.
    pub codex_off: &'a [String],
    /// Only a launch under neosian's common policy changes a preset (X4b).
    pub confined: bool,
    /// Pi: its agent directory, the child's session directory and, to
    /// continue, the session's exact file (X5a).
    pub pi: Option<&'a pi::Paths>,
    /// Vibe and Muse Code: the child's private home (X6a, X6b).
    pub child_home: Option<&'a Path>,
    /// A Vibe or Muse child's one MCP server, neosian's own (X7b).
    pub memory: Option<&'a super::server::ChildServer>,
}

/// One turn's command: argv[0] is the program, resolved by the caller.
#[derive(Debug, PartialEq, Eq)]
pub struct Plan {
    pub argv: Vec<String>,
    pub env: Vec<(String, String)>,
}

/// Why a plan cannot be made.
#[derive(Debug, PartialEq, Eq)]
pub enum Unplanned {
    OpenCodeConfig,
    /// Pi's directories, or the file of the session to continue, are missing.
    PiState,
    /// A directory Cursor is given is not UTF-8.
    CursorPath,
    /// A Vibe or Muse Code child's private home is missing or not UTF-8.
    ChildHome,
}

impl Unplanned {
    /// The watcher's refusal.
    pub fn sentence(&self) -> String {
        let say = super::text::say;
        match self {
            Self::OpenCodeConfig => say("bad_opencode_config", &[]),
            Self::PiState => say("watch_bad_field", &[("field", "pi")]),
            Self::CursorPath => say("watch_bad_field", &[("field", "directory")]),
            Self::ChildHome => say("watch_bad_field", &[("field", "child_home")]),
        }
    }
}

/// The variables the child's record hook reads (§40.50 amended, #430).
pub const PARENT_ENV: &str = "NEOSIAN_HARNESS_PARENT";
pub const SESSION_ENV: &str = "NEOSIAN_HARNESS_SESSION";

pub fn plan(request: &Request) -> Result<Plan, Unplanned> {
    let mut plan = match request.agent {
        Agent::ClaudeCode => claude::plan(request),
        Agent::Codex => codex::plan(request),
        Agent::OpenCode => opencode::plan(request)?,
        Agent::Pi => pi::plan(request)?,
        Agent::Cursor => cursor::plan(request)?,
        Agent::Vibe => vibe::plan(request)?,
        Agent::Muse => muse::plan(request)?,
    };
    let directory = request.directory.display().to_string();
    plan.env
        .push((super::CHILD_ENV.to_string(), "1".to_string()));
    // `opencode run` takes its project from PWD, not the working directory.
    plan.env.push(("PWD".to_string(), directory));
    if let Some(parent) = request.parent {
        plan.env.push((PARENT_ENV.to_string(), parent.to_string()));
    }
    let known = match request.resume {
        Some(session) => Some(session),
        None => request.agent.names_session().then_some(request.new_session),
    };
    if let Some(session) = known {
        plan.env
            .push((SESSION_ENV.to_string(), session.to_string()));
    }
    Ok(plan)
}

#[cfg(test)]
mod inputs;
#[cfg(test)]
mod read_only;
#[cfg(test)]
mod tests;