neosian 3.0.3

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! `neosian harness-file` (hidden; X6c U1): one event of a watched turn,
//! filed by the turn's watcher (`filing.rs`). It runs only where the tool
//! is served (enabled, not in a child) and reads one JSON object on its
//! standard input: the watcher's plan, the session the turn is filed under,
//! the event and its fields. The plan is checked again with the tool's own
//! rules, the session must be the one the plan started or continued (or,
//! for a client that announces its own, a session ID), and the event one of
//! the recorder's own. The payload is built here, the session and the
//! turn's generation from the plan, and the record verb runs in this
//! process with the plan's store selection and `--project` the child's
//! directory. `neosian record` never takes a payload for a watcher's: what
//! reaches it from anywhere goes through the client's own hook readers.

use std::io::{self, Read, Write};

use clap::Args;
use serde::Deserialize;
use serde_json::{Map, Value, json};

use super::adapter::{self, Agent};
use super::plan::{Checked, PLAN_BYTES, WirePlan, check};
use super::text::say;
use crate::record::payload::{PROMPT_EVENT, RESPONSE_EVENT, STOP_EVENT, TOOL_EVENT};

/// The verb's name, as the watcher calls it.
pub const FILE_VERB: &str = "harness-file";
/// The most read on standard input: the plan and one event, whose tool
/// result the capture already bounds to the turn's 64 MiB.
const FILED_BYTES: u64 = (64 << 20) + PLAN_BYTES as u64;
const EVENTS: [&str; 4] = [PROMPT_EVENT, TOOL_EVENT, RESPONSE_EVENT, STOP_EVENT];

/// One watched turn's event (hidden; started only by a turn's watcher).
#[derive(Args)]
pub struct File {}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Filed {
    plan: WirePlan,
    session: String,
    event: String,
    fields: Map<String, Value>,
}

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

pub fn run(_args: &File, out: &mut impl Write, err: &mut impl Write) -> io::Result<u8> {
    let Some(settings) = super::served(&mut |_| {}) else {
        return refuse(err, &say("watch_off", &[]));
    };
    let mut text = Vec::new();
    io::stdin().take(FILED_BYTES).read_to_end(&mut text)?;
    let bad = |field: &str| say("watch_bad_field", &[("field", field)]);
    let Ok(filed) = serde_json::from_slice::<Filed>(&text) else {
        return refuse(err, &bad("plan"));
    };
    let home = adapter::home();
    let plan = match check(filed.plan, home.as_deref(), &settings.directories) {
        Ok(plan) => plan,
        Err(sentence) => return refuse(err, &sentence),
    };
    let resume = plan.resume.as_deref();
    let session = Some(filed.session.as_str());
    let Ok(native) = super::filing::identity(plan.agent, resume, &plan.new_session, session) else {
        return refuse(err, &bad("session"));
    };
    if !EVENTS.contains(&filed.event.as_str()) {
        return refuse(err, &bad("event"));
    }
    let payload = shaped(&plan, &native, &filed.event, filed.fields);
    let record = crate::record::watched::record(
        plan.agent.kind(),
        &plan.selection,
        plan.directory.clone(),
        (payload, &native),
        plan.parent.clone(),
    );
    match record {
        Ok(record) => crate::record::cli::run(&record, out, err),
        Err(sentence) => refuse(err, &sentence),
    }
}

/// The payload for `event`, with the session and the turn's identity. The
/// record verb reads a Cursor turn in Cursor's own hook vocabulary, so a
/// Cursor child's payloads are shaped as its hooks would send them (X5b).
fn shaped(
    plan: &Checked,
    native: &str,
    event: &str,
    mut fields: Map<String, Value>,
) -> Map<String, Value> {
    fields.insert("session_id".into(), json!(native));
    fields.insert("hook_event_name".into(), json!(event));
    // The watcher's turn is one generation, as a plugin names its turns.
    fields.insert("generation_id".into(), json!(plan.nonce));
    if plan.agent == Agent::Cursor {
        let named = match event {
            PROMPT_EVENT => "beforeSubmitPrompt",
            TOOL_EVENT => "postToolUse",
            RESPONSE_EVENT => "afterAgentResponse",
            _ => "stop",
        };
        fields.insert("hook_event_name".into(), json!(named));
        fields.insert("conversation_id".into(), json!(native));
        if let Some(response) = fields.remove("tool_response") {
            fields.insert("tool_output".into(), response);
        }
    }
    fields
}