neosian 3.0.1

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! A child's sign-in (X4c). A child cannot sign in or renew a sign-in for
//! itself: on macOS neosian's policy allows no credential file and no
//! keychain write (X4b), and no client's sign-in flow can run headless. So
//! before a turn the watcher's server runs the client's own read-only
//! status command outside the sandbox (`status.rs`), and what it answers is
//! read here; a sign-in failure the client reports in its own structured
//! error during a turn becomes the same instruction.
//!
//! Only an answer that plainly says the client is not signed in counts as
//! signed out: the expected exit code and nothing else in the answer. A
//! timeout, a command that cannot run, an error and anything not
//! recognised are unknown: the turn starts, with a fixed note that says so
//! and nothing of what the command printed (X4f Q9).

use serde_json::Value;

use super::adapter::Agent;
use super::events::{Event, head};
use super::text::say;

mod answers;
use answers::{
    MUSE_SIGNED_OUT, MUSE_TURN_SIGNED_OUT, cursor_signed_out, cursor_turn_signed_out,
    vibe_turn_signed_out,
};

/// The client's own status command, or None where the client has none
/// that answers for a run: OpenCode's `opencode auth list` lists stored
/// credentials, but a free model needs none and an environment variable
/// counts, so its answer cannot say that a run would be signed out.
pub fn command(agent: Agent) -> Option<&'static [&'static str]> {
    match agent {
        // Claude Code 2.1.332: JSON with `loggedIn`, exit 1 when false.
        Agent::ClaudeCode => Some(&["auth", "status"]),
        // codex-cli 0.172.0: one line on stderr, exit 1 when not logged in.
        Agent::Codex => Some(&["login", "status"]),
        Agent::OpenCode => None,
        // Pi 1.7.0: JSON with `status`, exit 0, 1 or 2 (ready, not_ready,
        // invalid); it needs a model or provider, so `status.rs` adds the
        // model, and with none the check is not run (X5a).
        Agent::Pi => Some(&["auth", "check", "--json"]),
        // Cursor 2026.09.10-fd3934a: its model listing, which needs a usable
        // sign-in; its `status` says signed in with stale tokens (X5b).
        Agent::Cursor => Some(&["models"]),
        // Vibe has no status command; a missing key shows in the turn (X6a).
        Agent::Vibe => None,
        // Muse Code 1.4.25: its usage summary, no model call (X6b).
        Agent::Muse => Some(&["usage", "--json"]),
    }
}

/// The status command as the person would type it.
pub fn typed(agent: Agent) -> String {
    let words = command(agent).unwrap_or_default();
    std::iter::once(agent.program())
        .chain(words.iter().copied())
        .collect::<Vec<_>>()
        .join(" ")
}

/// What a status command's answer said.
#[derive(Debug, PartialEq, Eq)]
pub enum Status {
    SignedIn,
    SignedOut,
    /// The client said the model it was asked about is not valid (Pi).
    Invalid,
    /// Not known; why, in a sentence safe to show.
    Unknown(String),
}

/// The client's answer read: the exit code (None for a signal) and what it
/// printed on each stream, already bounded by the caller.
pub fn classify(agent: Agent, code: Option<i32>, stdout: &str, stderr: &str) -> Status {
    // Both clients exit 1 when not signed in.
    let failed = code == Some(1);
    match agent {
        Agent::ClaudeCode => {
            let logged_in = serde_json::from_str::<Value>(stdout.trim())
                .ok()
                .and_then(|answer| answer.get("loggedIn").and_then(Value::as_bool));
            match logged_in {
                Some(true) if code == Some(0) => Status::SignedIn,
                Some(false) if failed => Status::SignedOut,
                _ => unrecognized(code, stdout, stderr),
            }
        }
        Agent::Codex => {
            let lines = || stderr.lines().chain(stdout.lines()).map(str::trim);
            let signed_in = lines().any(|line| {
                line.starts_with("Logged in using") || line.starts_with("API key configured")
            });
            let said: Vec<&str> = lines().filter(|line| !line.is_empty()).collect();
            if code == Some(0) && signed_in {
                Status::SignedIn
            } else if failed && said == ["Not logged in"] {
                Status::SignedOut
            } else {
                unrecognized(code, stdout, stderr)
            }
        }
        Agent::OpenCode => unrecognized(code, stdout, stderr),
        Agent::Pi => {
            let answer = serde_json::from_str::<Value>(stdout.trim()).unwrap_or_default();
            let field = |name: &str| answer.get(name).and_then(Value::as_str);
            match (code, field("status"), field("reason")) {
                (Some(0), Some("ready"), _) => Status::SignedIn,
                // Captured signed out (record/investigation-2026-11-28).
                (Some(1), Some("not_ready"), Some("credentials_not_configured")) => {
                    Status::SignedOut
                }
                (Some(2), Some("invalid"), _) => Status::Invalid,
                _ => unrecognized(code, stdout, stderr),
            }
        }
        Agent::Vibe => unrecognized(code, stdout, stderr),
        Agent::Muse => {
            let answer = serde_json::from_str::<Value>(stdout.trim()).unwrap_or_default();
            if code == Some(0) && answer.get("schemaVersion").is_some() {
                Status::SignedIn
            } else if failed && stdout.trim().is_empty() && stderr.trim() == MUSE_SIGNED_OUT {
                Status::SignedOut
            } else {
                unrecognized(code, stdout, stderr)
            }
        }
        Agent::Cursor => {
            let listed = stdout.lines().map(str::trim).find(|l| !l.is_empty());
            if code == Some(0) && listed == Some("Available models") {
                Status::SignedIn
            } else if failed && stdout.trim().is_empty() && cursor_signed_out(stderr) {
                Status::SignedOut
            } else {
                unrecognized(code, stdout, stderr)
            }
        }
    }
}

/// An answer neosian does not recognise: a fixed sentence with its exit
/// status, never any of what it printed, which may hold a secret.
fn unrecognized(code: Option<i32>, _stdout: &str, _stderr: &str) -> Status {
    let status = code.map_or_else(|| "a signal".to_string(), |code| code.to_string());
    Status::Unknown(say("signin_unrecognized", &[("status", &status)]))
}

/// The most of a status answer's line an unknown result shows.
const SHOWN_BYTES: usize = 160;

/// The first non-empty line of `answer`, bounded, control characters
/// dropped, and every word that may be a credential, a key's masked form,
/// an e-mail address or another personal detail replaced by `[hidden]`.
pub fn scrub(answer: &str) -> String {
    let line = answer
        .lines()
        .map(str::trim)
        .find(|line| !line.is_empty())
        .unwrap_or_default();
    let printable: String = line.chars().filter(|c| !c.is_control()).collect();
    let words: Vec<&str> = printable
        .split_whitespace()
        .map(|word| if hidden(word) { "[hidden]" } else { word })
        .collect();
    head(&words.join(" "), SHOWN_BYTES).to_string()
}

/// A word that may be secret or personal: long, or letters mixed with
/// digits (keys, tokens, IDs), or marked as a key's masked form (`*`), an
/// assignment (`=`) or an address (`@`).
fn hidden(word: &str) -> bool {
    let digits = word.chars().any(|c| c.is_ascii_digit());
    let letters = word.chars().any(|c| c.is_alphabetic());
    word.chars().count() >= 20
        || (digits && letters && word.len() >= 8)
        || word.contains(['*', '=', '@'])
        || word.starts_with("sk-")
}

/// The one instruction a signed-out client gets, before a turn or during
/// one: how to sign in, outside the child.
pub fn instruction(agent: Agent) -> String {
    let key = match agent {
        Agent::ClaudeCode => "signin_claude_code",
        Agent::Codex => "signin_codex",
        Agent::OpenCode => "signin_opencode",
        Agent::Pi => "signin_pi",
        Agent::Cursor => "signin_cursor",
        Agent::Vibe => "signin_vibe",
        Agent::Muse => "signin_muse",
    };
    say(key, &[])
}

/// Pi's line on stderr when it has no key for the model, with exit 1 and
/// only the session header on stdout (Pi 1.7.0, captured in
/// record/investigation-2026-11-28/streams/pi-no-model.stderr.txt).
pub const PI_NO_KEY: &str = "No API key found for the selected model.";

/// Whether a turn that exited 1 said on stderr that its sign-in failed:
/// Pi and Cursor say so only there, each with one exact line.
pub fn stderr_said(agent: Agent, code: i32, stderr: &str) -> bool {
    let said = |line: &str| match agent {
        Agent::Pi => line == PI_NO_KEY,
        Agent::Cursor => cursor_turn_signed_out(line),
        Agent::Vibe => vibe_turn_signed_out(line),
        Agent::Muse => line.starts_with(MUSE_TURN_SIGNED_OUT),
        _ => false,
    };
    code == 1 && stderr.lines().map(str::trim).any(said)
}

/// Pi's warning before that line when no provider is configured at all, so
/// no model exists to sign in for (same capture; seen again live, X7d).
pub const PI_NO_MODELS: &str =
    "Warning: No models available. Use /login to log into a provider via OAuth or API key. See:";

/// The turn failed because the client's sign-in failed.
pub fn failed(agent: Agent) -> Event {
    Event::SignIn(instruction(agent))
}

/// The same, from the turn's stderr: a Pi with no provider at all is told
/// to configure one, not to sign in for a model it does not have (X7d).
pub fn failed_after(agent: Agent, stderr: &str) -> Event {
    let none = stderr.lines().any(|line| line.trim() == PI_NO_MODELS);
    if agent == Agent::Pi && none {
        return Event::SignIn(say("signin_pi_no_model", &[]));
    }
    failed(agent)
}

/// The note for a status neosian could not read; the turn starts anyway.
pub fn unknown(agent: Agent, reason: &str) -> String {
    say(
        "signin_unknown",
        &[
            ("agent", agent.name()),
            ("command", &typed(agent)),
            ("reason", reason),
        ],
    )
}

/// Claude Code's structured error for a failed sign-in, on an assistant
/// message (2.1.332's `error` member).
pub const CLAUDE_ERROR: &str = "authentication_failed";

/// A failed Claude Code result that tells the person to sign in: "Not
/// logged in · Please run /login", "Login expired · Please run /login",
/// "Authentication required · Sign in again to continue" (2.1.332). An
/// external API key's refusal ("Invalid API key · Fix external API key")
/// is not one: signing in does not fix it.
pub fn claude_said(result: &str) -> bool {
    result.contains("Please run /login") || said_again(result)
}

/// A failed Codex turn whose message tells the person to sign in again:
/// "Your access token could not be refreshed. Please log out and sign in
/// again." and its kin (codex-cli 0.172.0).
pub fn codex_said(message: &str) -> bool {
    said_again(message) || message.contains("re-run `codex login`")
}

fn said_again(text: &str) -> bool {
    text.to_ascii_lowercase().contains("sign in again")
}

/// OpenCode's error type for a provider that refused the sign-in (2.3.2).
pub const OPENCODE_ERROR: &str = "provider.auth";

#[cfg(test)]
mod answers_tests;
#[cfg(test)]
mod tests;