neosian 3.0.3

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! Antigravity CLI's headless form (X6a), from 1.5.20's live runs and
//! installed help (record/investigation-2026-11-29, section 2): `-p` never
//! reads standard input, so the turn runs with `--input-format stream-json
//! --output-format stream-json`, the prompt as one `user` line on stdin, and
//! ends when stdin closes. The process directory is the validated directory
//! (agy has no directory flag). Read-only is agy's own permission deny list
//! passed with `--settings`; write is `--dangerously-skip-permissions`, only
//! inside neosian's policy. A first turn takes the conversation agy
//! announces; `send` passes it back with `--conversation`. agy has no switch
//! for hooks, MCP or plugins and no relocation, so the policy keeps their
//! files unreadable (`sandbox/agy.rs`) and no Antigravity child starts off
//! macOS. Set the documented opt-out from automatic updates for child runs.

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

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

/// What a read-only child may not do, in agy's permission grammar.
pub const READ_ONLY: &str = r#"{"permissions":{"deny":["write_file(*)","command(*)","mcp(*)","read_url(*)","execute_url(*)","download_url(*)"]}}"#;
/// Antigravity's documented automatic update opt-out.
pub const UPDATE_OFF: &str = "AGY_CLI_DISABLE_AUTO_UPDATE";
/// agy's error for a sign-in that failed or timed out (captured signed out).
pub const SIGNIN_ERROR: &str = "authentication failed or timed out";

/// The prompt as the one stream-json line agy reads, then the end of input.
pub fn stdin(prompt: &[u8]) -> Vec<u8> {
    let said = String::from_utf8_lossy(prompt);
    let mut line = json!({"event": "user", "message": {"content": said}}).to_string();
    line.push('\n');
    line.into_bytes()
}

pub fn plan(request: &Request) -> Result<Plan, Unplanned> {
    let mut argv: Vec<String> = [
        "agy",
        "--input-format",
        "stream-json",
        "--output-format",
        "stream-json",
    ]
    .map(String::from)
    .to_vec();
    match request.mode {
        Mode::ReadOnly => argv.extend(["--settings".to_string(), READ_ONLY.to_string()]),
        Mode::Write => argv.push("--dangerously-skip-permissions".to_string()),
    }
    if let Some(model) = request.model {
        argv.extend(["--model".to_string(), model.to_string()]);
    }
    if let Some(conversation) = request.resume {
        argv.extend(["--conversation".to_string(), conversation.to_string()]);
    }
    Ok(Plan {
        argv,
        env: vec![(UPDATE_OFF.to_string(), "true".to_string())],
    })
}

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

/// One line of agy'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("event")).unwrap_or_default() {
        "init" => {
            if let Some(conversation) = text(event.get("conversation_id")) {
                events.push(Event::Session(conversation.to_string()));
            }
        }
        "step_update" => {
            let Some(step) = event.get("step_update") else {
                return events;
            };
            let state = text(step.get("state")).unwrap_or_default();
            match text(step.get("step_type")).unwrap_or_default() {
                "agent_response" => {
                    if let Some(said) = text(step.get("text_delta")).filter(|t| !t.is_empty()) {
                        events.push(Event::Delta(said.to_string()));
                    }
                }
                "tool" if state != "ACTIVE" => {
                    let info = step.get("tool_info");
                    let name = json!(text(step.get("tool_name")).unwrap_or_default());
                    let mut fields = vec![("name", name), ("status", json!(state))];
                    let error = info
                        .and_then(|i| i.get("error"))
                        .and_then(|e| e.get("message"));
                    if let Some(error) = text(error) {
                        fields.push(("error", json!(error)));
                    }
                    events.push(observed("tool", &fields));
                }
                _ => {}
            }
        }
        "result" => {
            let result = event.get("result");
            let status = text(result.and_then(|r| r.get("status")));
            let error = text(result.and_then(|r| r.get("error"))).unwrap_or("error");
            match status {
                Some("SUCCESS") => {
                    let said = text(result.and_then(|r| r.get("response"))).unwrap_or_default();
                    events.push(Event::Answer(said.to_string()));
                }
                _ if error == SIGNIN_ERROR => {
                    events.push(signin::failed(super::adapter::Agent::Agy))
                }
                _ => events.push(Event::Failure(head(error, ERROR_BYTES).to_string())),
            }
        }
        _ => {}
    }
    events
}

#[cfg(test)]
mod tests;