neosian 3.0.0

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! Muse Code's headless form (X6b), from 1.4.25's help and live runs
//! (record/investigation-2026-11-29, section 1): `muse exec --json` reads no
//! pipe, so the prompt is an anonymous file (made and unlinked by the
//! watcher, nowhere by name) given as standard input and read through
//! `--prompt-file /dev/stdin`. neosian names the session with
//! `--session-id`, and the same flag continues it. Hooks are off for the run
//! (`-c hooks={}`), and the child's private `XDG_CONFIG_HOME` holds no MCP
//! server; the workspace is never trusted, so its own hooks, rules and
//! `.mcp.json` do not load. The approval judge and reminder agents (extra
//! model calls) and foreign personal context are off. Read-only is Muse's
//! `--disable-write --disable-shell` with approval `never`. On macOS Muse's
//! own shell sandbox cannot start inside neosian's policy, so it is off there
//! and the policy is the boundary; elsewhere it stays on. Muse's
//! self-update is off through its launcher's variable.

use std::path::Path;

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;

/// The launcher's own switch for Muse's background self-update.
pub const UPDATE_OFF: &str = "MUSE_NO_AUTO_UPDATE";
/// The settings a child keeps of the person's: never hooks or MCP servers.
const KEPT: [&str; 4] = ["schema_version", "provider", "model", "reasoning_effort"];
/// The fields a child's copy of a Keychain sign-in keeps, each a string
/// (X6c U9): how the sign-in was made and where, never a token or the
/// person's name or address.
const SIGNIN: [&str; 4] = ["mechanism", "storage", "obtained_via", "api_base_url"];

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 session = request.resume.unwrap_or(request.new_session);
    let mut argv: Vec<String> = ["muse", "exec", "--json", "--prompt-file", "/dev/stdin"]
        .map(String::from)
        .to_vec();
    argv.extend(["--session-id".to_string(), session.to_string()]);
    for word in [
        "--approval-judge",
        "off",
        "--disable-reminders",
        "--no-foreign-personal-context",
        "-c",
        "hooks={}",
        "--approval-mode",
        "never",
    ] {
        argv.push(word.to_string());
    }
    if request.mode == Mode::ReadOnly {
        argv.extend(["--disable-write".to_string(), "--disable-shell".to_string()]);
    }
    if request.confined {
        argv.push("--disable-sandbox".to_string());
    }
    if let Some(model) = request.model {
        argv.extend(["--model".to_string(), model.to_string()]);
    }
    let env = vec![
        ("XDG_CONFIG_HOME".to_string(), shown(home)?),
        (UPDATE_OFF.to_string(), "1".to_string()),
    ];
    Ok(Plan { argv, env })
}

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

/// One line of Muse's stream, for the parent's display.
pub fn read(event: &Map<String, Value>) -> Vec<Event> {
    let mut events = Vec::new();
    let stream = event.get("stream");
    if text(stream.and_then(|s| s.get("kind"))) == Some("session")
        && let Some(session) = text(stream.and_then(|s| s.get("id")))
    {
        events.push(Event::Session(session.to_string()));
    }
    let payload = event.get("payload");
    let field = |name: &str| text(payload.and_then(|p| p.get(name)));
    match text(event.get("payload_type")).unwrap_or_default() {
        "run.output.delta" => events.extend(field("text").map(|t| Event::Delta(t.to_string()))),
        "tool.result" => {
            let facts = payload.and_then(|p| p.get("correlation_facts"));
            let name = json!(text(facts.and_then(|f| f.get("tool_name"))).unwrap_or_default());
            let outcome = json!(text(facts.and_then(|f| f.get("outcome"))).unwrap_or_default());
            events.push(observed("tool", &[("name", name), ("outcome", outcome)]));
        }
        "run.terminal.completed" => {
            events.push(Event::Answer(field("text").unwrap_or_default().to_string()));
        }
        "run.terminal.failed" => {
            let said = field("reason").unwrap_or("failed");
            events.push(Event::Failure(head(said, ERROR_BYTES).to_string()));
        }
        _ => {}
    }
    events
}

/// The prompt as an anonymous regular file, read from its start: made in
/// the watcher's temporary directory with mode 0600 and unlinked at once,
/// so it exists by no name (Muse reads `/dev/stdin` only as a regular
/// file).
#[cfg(unix)]
pub fn prompt_file(prompt: &[u8]) -> std::io::Result<std::fs::File> {
    use std::io::{Seek, Write};
    use std::os::unix::fs::OpenOptionsExt;
    let path = std::env::temp_dir().join(format!(
        "neosian-prompt-{}-{}",
        std::process::id(),
        uuid::Uuid::new_v4().simple()
    ));
    let mut file = std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .create_new(true)
        .mode(0o600)
        .open(&path)?;
    std::fs::remove_file(&path)?;
    file.write_all(prompt)?;
    file.rewind()?;
    Ok(file)
}

/// The person's Muse configuration directory, where the server reads what
/// a child keeps.
fn config() -> Option<std::path::PathBuf> {
    let xdg = std::env::var_os("XDG_CONFIG_HOME").filter(|v| !v.is_empty());
    let base = xdg
        .map(std::path::PathBuf::from)
        .filter(|p| p.is_absolute());
    let home = super::adapter::home().map(|home| home.join(".config"));
    base.or(home).map(|base| base.join("muse"))
}

/// The sign-in record a child gets, rebuilt from the person's (X6c U9):
/// `schema_version` (an integer) and, for each provider, only the `SIGNIN`
/// fields, when every provider keeps its credential in the Keychain. Any
/// other shape, or a sign-in kept in the file, is refused; nothing else of
/// the file is ever copied.
pub fn keychain_only(auth: &[u8]) -> Result<Value, String> {
    let refused = || say("muse_auth_file", &[]);
    let parsed: Value = serde_json::from_slice(auth).map_err(|_| refused())?;
    let version = parsed.get("schema_version").filter(|v| v.is_u64());
    let providers = parsed.get("providers").and_then(Value::as_object);
    let (Some(version), Some(providers)) = (version, providers) else {
        return Err(refused());
    };
    let mut kept = Map::new();
    for (name, provider) in providers {
        let provider = provider.as_object().ok_or_else(refused)?;
        if provider.get("storage") != Some(&json!("keychain")) {
            return Err(refused());
        }
        let mut fields = Map::new();
        for field in SIGNIN {
            match provider.get(field) {
                Some(Value::String(value)) => drop(fields.insert(field.into(), json!(value))),
                None => {}
                Some(_) => return Err(refused()),
            }
        }
        kept.insert(name.clone(), Value::Object(fields));
    }
    if kept.is_empty() {
        return Err(refused());
    }
    Ok(json!({"schema_version": version, "providers": kept}))
}

/// A Muse child's private configuration filled in its new home: the
/// person's settings less everything but the model choice (so no hooks and
/// no MCP servers), and their sign-in metadata when every provider keeps
/// its credential in the Keychain (`keychain_only`). A sign-in kept in the
/// file is never copied: the child is refused.
#[cfg(unix)]
pub fn fill(home: &Path) -> Result<(), String> {
    use std::os::unix::fs::DirBuilderExt;
    let failed = |e: std::io::Error| {
        say(
            "spawn_failed",
            &[("agent", "muse"), ("error", &e.to_string())],
        )
    };
    let dir = home.join("muse");
    std::fs::DirBuilder::new()
        .mode(0o700)
        .create(&dir)
        .map_err(failed)?;
    let read = |name: &str| config().and_then(|c| std::fs::read(c.join(name)).ok());
    let parsed = |bytes: &[u8]| serde_json::from_slice::<Value>(bytes).unwrap_or_default();
    let settings = read("settings.json")
        .map(|b| parsed(&b))
        .unwrap_or_default();
    let kept: Map<String, Value> = KEPT
        .iter()
        .filter_map(|key| settings.get(*key).map(|v| ((*key).to_string(), v.clone())))
        .collect();
    std::fs::write(dir.join("settings.json"), Value::Object(kept).to_string()).map_err(failed)?;
    let Some(auth) = read("auth.json") else {
        return Ok(());
    };
    let rebuilt = keychain_only(&auth)?;
    std::fs::write(dir.join("auth.json"), rebuilt.to_string()).map_err(failed)
}

#[cfg(test)]
mod tests;