neosian 3.0.2

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! `neosian harness-watch` (hidden; ยง40.50 item 3, amended by #430 and
//! #431): one turn's watcher. It runs only where the tool is enabled, not
//! in a child and with a home directory, and reads a plan, never a command:
//! one line of JSON, then exactly that many bytes of prompt on its standard
//! input, which the server then holds open. It checks the plan with the
//! tool's own rules, builds the harness's argument vector through the
//! adapter, on macOS under neosian's common filesystem policy (`sandbox/`,
//! X4b), hands it the prompt on a pipe and relays its output, which also
//! reaches the turn's record (X4a). When the harness exits, the watcher
//! files the turn through the record verb (`filing.rs`), reports its status
//! and ends what the harness left in its group after a grace; when its
//! standard input ends first (the server stopped the turn, or the server is
//! gone by any cause), it ends the harness and every descendant it can find,
//! and files nothing.

use std::io::{self, BufRead, Read, Write};
use std::path::Path;
use std::time::Duration;

use clap::Args;

use super::adapter::{self, Agent, McpServer, Request};
use super::plan::{Checked, PLAN_BYTES, WirePlan, check};
use super::probe;
use super::sandbox::{self, Private};
use super::text::say;

/// How long a turn's processes have to end after SIGTERM.
pub const GRACE: Duration = Duration::from_secs(5);
/// The line the watcher ends its stderr with: the nonce and the status.
pub const EXIT_LINE: &str = "neosian-harness-exit";

/// One turn's watcher (hidden; started only by the MCP server).
#[derive(Args)]
pub struct Watch {}

fn refuse(err: &mut impl Write, sentence: &str) -> io::Result<u8> {
    writeln!(err, "{sentence}")?;
    Ok(2)
}

/// The plan line and the prompt that follows it.
fn read_plan(input: &mut impl BufRead) -> Result<(WirePlan, Vec<u8>), String> {
    let mut line = Vec::new();
    input
        .take(PLAN_BYTES as u64)
        .read_until(b'\n', &mut line)
        .map_err(|e| e.to_string())?;
    let plan: WirePlan =
        serde_json::from_slice(&line).map_err(|_| say("watch_bad_field", &[("field", "plan")]))?;
    let wanted = plan.prompt_bytes.min(adapter::PROMPT_BYTES);
    let mut prompt = vec![0; wanted];
    input
        .read_exact(&mut prompt)
        .map_err(|_| say("watch_bad_field", &[("field", "prompt_bytes")]))?;
    Ok((plan, prompt))
}

/// This neosian's own server for a read-only child (#431): the running
/// executable, the server's pinned selection, every mount read-only, and
/// the server itself read-only (X7c Y2).
fn own_server(plan: &Checked) -> io::Result<McpServer> {
    let exe = std::env::current_exe()?;
    let exe = exe.canonicalize().unwrap_or(exe);
    Ok(McpServer {
        command: exe.display().to_string(),
        args: super::memory::args(plan, adapter::Mode::ReadOnly),
        mounted: !plan.mounts.is_empty(),
    })
}

pub fn run(_args: &Watch, err: &mut impl Write) -> io::Result<u8> {
    let mut warned = Vec::new();
    let Some(settings) = super::served(&mut |line: &str| warned.push(line.to_string())) else {
        return refuse(err, &say("watch_off", &[]));
    };
    let read = read_plan(&mut io::stdin().lock());
    let (wire, prompt) = match read {
        Ok(read) => read,
        Err(sentence) => return refuse(err, &sentence),
    };
    let home = adapter::home();
    let plan = match check(wire, home.as_deref(), &settings.directories) {
        Ok(plan) => plan,
        Err(sentence) => return refuse(err, &sentence),
    };
    let path = std::env::var_os("PATH");
    let Some(program) = adapter::which(plan.agent.program(), path.as_deref()) else {
        let sentence = say("watch_missing", &[("agent", plan.agent.name())]);
        return refuse(err, &sentence);
    };
    // The file the server probed, and no other (X4f Q5).
    let same =
        |named: &Path| named == program && named.canonicalize().ok() == program.canonicalize().ok();
    if plan.program.as_deref().is_some_and(|named| !same(named)) {
        return refuse(err, &say("watch_bad_field", &[("field", "program")]));
    }
    // The destination the server resolved is still the one on disk (X4f Q1).
    let drift =
        super::selection::drifted(&plan.selection, plan.identity.as_deref(), &plan.directory);
    if let Err(sentence) = drift {
        return refuse(err, &sentence);
    }
    let session = plan.resume.as_deref().unwrap_or(&plan.new_session);
    let resume = plan.resume.is_some();
    let private = Private::make_for(plan.agent)?;
    let state = (
        private.path(),
        plan.child_home.as_deref(),
        plan.session_dir.as_deref(),
    );
    let pi = match sandbox::ready(plan.agent, (session, resume), &plan.directory, state) {
        Ok(paths) => paths,
        Err(sentence) => return refuse(err, &sentence),
    };
    // On macOS the common policy is built and proved on a probe write before
    // any client command runs; a failure refuses the turn (X4b, X4e P4).
    let turn = sandbox::Turn {
        agent: plan.agent,
        mode: plan.mode,
        directory: &plan.directory,
        private: private.path(),
        selection: &plan.selection,
        // A Cursor chat is known once announced (X5b).
        session: (plan.agent != Agent::Cursor || resume).then_some(session),
        child_home: plan.child_home.as_deref(),
        session_dir: plan.session_dir.as_deref(),
    };
    let launch = match sandbox::prepare(&turn) {
        Ok(launch) => launch,
        Err(sentence) => return refuse(err, &sentence),
    };
    if launch.writable(&program) {
        let shown = program.display().to_string();
        return refuse(err, &say("program_writable", &[("program", &shown)]));
    }
    let (codex_keys, codex_off) = if plan.agent == Agent::Codex {
        match probe::codex(&launch, &program, &plan.directory, plan.mode) {
            Ok(found) => found,
            Err(sentence) => return refuse(err, &sentence),
        }
    } else {
        (Vec::new(), Vec::new())
    };
    // A Vibe or Muse child's own neosian server, written into the private
    // home made fresh above (X7b).
    let memory = super::memory::server(&plan, private.path())?;
    let registered = plan.child_home.as_deref().map_or(Ok(()), |home| {
        super::memory::register(plan.agent, home, memory.as_ref())
    });
    if let Err(sentence) = registered {
        return refuse(err, &sentence);
    }
    let server = own_server(&plan)?;
    let opencode_config = std::env::var(super::opencode::CONFIG_ENV).ok();
    let request = Request {
        agent: plan.agent,
        mode: plan.mode,
        model: plan.model.as_deref(),
        directory: &plan.directory,
        resume: plan.resume.as_deref(),
        new_session: &plan.new_session,
        private: private.path(),
        codex_keys: &codex_keys,
        opencode_config: opencode_config.as_deref(),
        parent: plan.parent.as_deref(),
        server: Some(&server),
        codex_off: &codex_off,
        confined: launch.confined(),
        pi: pi.as_ref(),
        child_home: plan.child_home.as_deref(),
        memory: memory.as_ref(),
    };
    match adapter::plan(&request) {
        Ok(built) => {
            super::drive::drive(&plan, &launch, &program, (&built.argv, &built.env), prompt)
        }
        Err(unplanned) => refuse(err, &unplanned.sentence()),
    }
}