neosian 3.0.0

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! Mistral Vibe's headless form (X6a), from 3.1.5's help and live runs
//! (record/investigation-2026-11-29, section 3): `-p` with no text, so the
//! prompt is read from standard input, `--output streaming`, the validated
//! directory as `--workdir`, and the mode as Vibe's own approval policy:
//! `ask` with only `read_file` enabled (a headless "ask" is a denial, never a
//! stall) or `--auto-approve`. A first turn takes the session Vibe
//! announces; `send` passes it back with `--resume`. Every run has a private
//! `VIBE_HOME` that neosian made for the child, so no user hook, MCP server,
//! plugin, trusted folder or `.env` of the person's own Vibe home loads. Its
//! only MCP server is neosian's own, registered there by the watcher
//! (`memory.rs`, X7b), whose allowed tools a read-only child is given as
//! enabled tools. `VIBE_ENABLE_MCP` is set either way, so an inherited value
//! never decides: `true` with the server registered, `false` without one
//! (X7c Y6). The API key still comes from the Keychain by HOME or from the
//! environment. Vibe's self-update is switched off through its own
//! configuration variables.

use std::path::Path;

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

use super::adapter::{Mode, Plan, Request, Unplanned};
use super::events::{Event, observed};

/// The tools a read-only child may use: Vibe 3.1.5 has no other read tool
/// (`grep` matches no tool; searching goes through `bash`).
pub const READ_TOOLS: [&str; 1] = ["read_file"];

/// The variables every Vibe child is started with, beside `VIBE_HOME`.
const ENV: [(&str, &str); 2] = [
    ("VIBE_ENABLE_AUTO_UPDATE", "false"),
    ("VIBE_ENABLE_UPDATE_CHECKS", "false"),
];
/// Vibe's MCP switch: on exactly when neosian's server is registered.
const MCP_SWITCH: &str = "VIBE_ENABLE_MCP";

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

pub fn plan(request: &Request) -> Result<Plan, Unplanned> {
    let home = request.child_home.ok_or(Unplanned::ChildHome)?;
    let mut argv: Vec<String> = ["vibe", "-p", "--output", "streaming", "--workdir"]
        .map(String::from)
        .to_vec();
    argv.push(shown(request.directory)?);
    match request.mode {
        Mode::ReadOnly => {
            argv.extend(["--approval-policy".to_string(), "ask".to_string()]);
            for tool in READ_TOOLS {
                argv.extend(["--enabled-tools".to_string(), tool.to_string()]);
            }
            let allowed = request.memory.and_then(|server| server.tools.as_ref());
            for tool in allowed.into_iter().flatten() {
                argv.extend([
                    "--enabled-tools".to_string(),
                    super::server::vibe_tool(tool),
                ]);
            }
        }
        Mode::Write => argv.push("--auto-approve".to_string()),
    }
    // A resumed session keeps its own model (Vibe: new sessions only).
    match (request.resume, request.model) {
        (Some(session), _) => argv.extend(["--resume".to_string(), session.to_string()]),
        (None, Some(model)) => argv.extend(["--model".to_string(), model.to_string()]),
        (None, None) => {}
    }
    let mut env = vec![("VIBE_HOME".to_string(), shown(home)?)];
    let on = if request.memory.is_some() {
        "true"
    } else {
        "false"
    };
    env.push((MCP_SWITCH.to_string(), on.to_string()));
    env.extend(ENV.map(|(k, v)| (k.to_string(), v.to_string())));
    Ok(Plan { argv, env })
}

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

/// An entry's text blocks, joined.
pub(super) fn words(entry: &Map<String, Value>) -> String {
    entry
        .get("content")
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
        .filter_map(|block| text(block.get("text")))
        .collect::<Vec<_>>()
        .join("\n")
}

/// One line of Vibe's stream, for the parent's display.
pub fn read(event: &Map<String, Value>) -> Vec<Event> {
    let mut events = Vec::new();
    if let Some(session) = text(event.get("sessionId")) {
        events.push(Event::Session(session.to_string()));
    }
    match text(event.get("type")).unwrap_or_default() {
        "message" if text(event.get("role")) == Some("assistant") => {
            let said = words(event);
            if !said.is_empty() {
                events.push(Event::Text(said));
            }
        }
        "effect" => {
            let detail = event.get("detail");
            let state = event.get("state");
            let name = json!(text(detail.and_then(|d| d.get("toolName"))).unwrap_or_default());
            let status = json!(text(state.and_then(|s| s.get("status"))).unwrap_or_default());
            let mut fields = vec![("name", name), ("status", status)];
            let error = state
                .and_then(|s| s.get("error"))
                .and_then(|e| e.get("message"));
            if let Some(error) = text(error) {
                fields.push(("error", json!(error)));
            }
            events.push(observed("tool", &fields));
        }
        _ => {}
    }
    events
}

#[cfg(test)]
mod tests;