neosian 3.0.3

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! Cursor CLI's headless form (X5b), from the installed 2026.09.10-fd3934a's
//! help and print-mode handler, run live as a child on 2026.11.22-e9042b2
//! (X7a: read-only and write starts, a resumed chat). `-p
//! --output-format stream-json` with the prompt on standard input only (with
//! no positional prompt Cursor reads all of a non-terminal stdin, trimmed),
//! complete assistant chunks (no `--stream-partial-output`), `--trust`, the
//! validated directory as both the process directory and `--workspace`,
//! Cursor's own sandbox off (`--sandbox disabled`), since on macOS neosian's
//! policy is the boundary and a nested sandbox may not start inside it, and
//! the mode as Cursor's own: `--mode ask` (read-only Q&A) or `--force` (run
//! commands without asking), the latter only in `write`. A first turn takes
//! the chat ID Cursor announces; `send` passes it back with `--resume`. No
//! `--approve-mcps`, `--plugin-dir`, `--add-dir`, `create-chat` or
//! `--continue`: the policy keeps Cursor's MCP, hook and plugin files from
//! being read at all (`sandbox/cursor.rs`). Off macOS no Cursor child starts.

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

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

/// The variable that keeps Node from writing its compile cache, which
/// Cursor's launcher points into the home directory's caches.
pub const COMPILE_CACHE_OFF: &str = "NODE_DISABLE_COMPILE_CACHE";

pub fn plan(request: &Request) -> Result<Plan, Unplanned> {
    let directory = request.directory.to_str().ok_or(Unplanned::CursorPath)?;
    let mut argv: Vec<String> = [
        "cursor-agent",
        "-p",
        "--output-format",
        "stream-json",
        "--trust",
        "--workspace",
    ]
    .map(String::from)
    .to_vec();
    argv.extend([directory.to_string(), "--sandbox".into(), "disabled".into()]);
    match request.mode {
        Mode::ReadOnly => argv.extend(["--mode".to_string(), "ask".to_string()]),
        Mode::Write => argv.push("--force".to_string()),
    }
    if let Some(model) = request.model {
        argv.extend(["--model".to_string(), model.to_string()]);
    }
    if let Some(chat) = request.resume {
        argv.extend(["--resume".to_string(), chat.to_string()]);
    }
    Ok(Plan {
        argv,
        env: vec![(COMPILE_CACHE_OFF.to_string(), "1".to_string())],
    })
}

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

/// A tool call's kind (`readToolCall`, `globToolCall`, `shellToolCall`,
/// `mcpToolCall`, ...) and its value, with `args` and, once completed,
/// `result` (the protobuf JSON form Cursor prints): the one member named
/// `...ToolCall` holding an object. Cursor 2026.11.22 prints others beside
/// it (`toolCallId`, `startedAtMs`, `completedAtMs`,
/// `hookAdditionalContexts`; seen live, X7a).
pub(super) fn tool(event: &Map<String, Value>) -> Option<(&str, &Map<String, Value>)> {
    let call = event.get("tool_call")?.as_object()?;
    let mut kinds = call
        .iter()
        .filter(|(name, value)| name.ends_with("ToolCall") && value.is_object());
    match (kinds.next(), kinds.next()) {
        (Some((kind, Value::Object(value))), None) => Some((kind, value)),
        _ => None,
    }
}

/// The record's name for a tool call: an MCP call keeps its server and
/// tool, as Codex's are named.
pub(super) fn name(kind: &str, value: &Map<String, Value>) -> String {
    let args = value.get("args");
    let server = text(args.and_then(|a| a.get("providerIdentifier")));
    let tool = text(args.and_then(|a| a.get("toolName")));
    match (kind, server, tool) {
        ("mcpToolCall", Some(server), Some(tool)) => format!("mcp__{server}__{tool}"),
        _ => kind.to_string(),
    }
}

/// One line of Cursor's stream, for the parent's display.
pub fn read(event: &Map<String, Value>) -> Vec<Event> {
    let mut events = Vec::new();
    match text(event.get("type")).unwrap_or_default() {
        "system" if text(event.get("subtype")) == Some("init") => {
            if let Some(session) = text(event.get("session_id")) {
                events.push(Event::Session(session.to_string()));
            }
        }
        "assistant" => {
            let blocks = event
                .get("message")
                .and_then(|m| m.get("content"))
                .and_then(Value::as_array);
            for block in blocks.into_iter().flatten() {
                if let Some(said) = text(block.get("text")).filter(|t| !t.is_empty()) {
                    events.push(Event::Text(said.to_string()));
                }
            }
        }
        "tool_call" => {
            let Some((kind, value)) = tool(event) else {
                return events;
            };
            let subtype = text(event.get("subtype")).unwrap_or_default();
            let mut fields = vec![
                ("name", json!(name(kind, value))),
                ("status", json!(subtype)),
            ];
            let outcome = value.get("result").and_then(Value::as_object);
            if let Some((case, _)) = outcome.and_then(|r| r.iter().next()) {
                fields.push(("result", json!(case)));
            }
            events.push(observed("tool", &fields));
        }
        "interaction_query" => {
            let query = json!(text(event.get("query_type")).unwrap_or_default());
            events.push(observed("interaction", &[("query", query)]));
        }
        "result" => {
            let success = text(event.get("subtype")) == Some("success")
                && event.get("is_error") == Some(&Value::Bool(false));
            let said = text(event.get("result")).unwrap_or_default();
            if success {
                events.push(Event::Answer(said.to_string()));
            } else {
                events.push(Event::Failure(head(said, ERROR_BYTES).to_string()));
            }
        }
        _ => {}
    }
    events
}

#[cfg(test)]
mod tests;