neosian 3.0.2

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! The synchronous wire client for the Rust doors (DESIGN §18, §39.11).
//! The handshake precedes every opened-store lifetime; one pooled agent
//! serves its calls. No application retries, redirects or async runtime.

mod changes;
pub(crate) mod codec;
mod errors;
mod history;
mod pages;
pub(crate) mod records;
mod scope_body;
pub mod selection;
mod state;
pub(crate) use scope_body::restore_scope_body;
#[cfg(test)]
mod tests;

use std::io;
use std::time::Duration;

use serde_json::{Value, json};
use ureq::tls::{PemItem, RootCerts, TlsConfig, parse_pem};

use crate::pyfmt::py_repr;
use crate::store::error::{Error, MemoryError};
use crate::wire::WIRE_VERSION;

enum Authorization {
    Static(String),
    Machine(crate::login::local::MachineCredential),
}

impl Authorization {
    fn header(&self) -> Result<String, Error> {
        let token = match self {
            Self::Static(s) => s.clone(),
            Self::Machine(machine) => machine.token().map_err(MemoryError::configuration)?,
        };
        Ok(format!("Bearer {token}"))
    }
}

pub struct RemoteStore {
    agent: ureq::Agent,
    base: String,
    authorization: Authorization,
    client: Option<String>,
    // Retained verbatim, never inferred from the name of the backend. The
    // operator erasers consult the advertised protocol before a call.
    capabilities: Value,
}

impl RemoteStore {
    pub fn profile_connect(
        url: &str,
        token: &str,
        login: Option<crate::login::local::MachineCredential>,
    ) -> Result<Self, Error> {
        let store = Self::with_timeout(url, token, Duration::from_secs(30), login)?;
        if store.capabilities["authorization"]["version"] != 1
            || store.capabilities["authorization"]["mode"] != "scoped"
        {
            return Err(MemoryError::configuration(
                "profile HTTP sources require scoped authorization version 1",
            )
            .into());
        }
        Ok(store)
    }
    pub fn connect(url: &str, token: &str) -> Result<Self, Error> {
        Self::with_timeout(url, token, Duration::from_secs(30), None)
    }

    fn with_timeout(
        url: &str,
        token: &str,
        timeout: Duration,
        login: Option<crate::login::local::MachineCredential>,
    ) -> Result<Self, Error> {
        let config = ureq::Agent::config_builder()
            .http_status_as_error(false)
            .max_redirects(0)
            .max_redirects_will_error(false)
            .timeout_connect(Some(timeout))
            .timeout_resolve(Some(timeout))
            .timeout_per_read(Some(timeout))
            .timeout_per_write(Some(timeout))
            .tls_config(tls()?)
            .build();
        let mut remote = Self {
            agent: config.new_agent(),
            base: url.trim_end_matches('/').to_string(),
            authorization: login
                .map(Authorization::Machine)
                .unwrap_or_else(|| Authorization::Static(token.to_owned())),
            client: None,
            capabilities: Value::Null,
        };
        let response = remote
            .agent
            .get(format!("{}/v1/capabilities", remote.base))
            .header("Authorization", remote.authorization.header()?)
            .call()
            .map_err(driver)?;
        if response.status() == 401 {
            if matches!(remote.authorization, Authorization::Machine(_)) {
                return Err(MemoryError::configuration(
                    "the host rejected this machine credential; run neosian login",
                )
                .into());
            }
            return Err(MemoryError::configuration(
                "the server rejected the bearer token — it must equal the server's NEOSIAN_SERVE_TOKEN",
            ).into());
        }
        let data = remote.answer(response, "capabilities", false)?;
        let wire = data.get("wire_version").unwrap_or(&Value::Null);
        if wire.as_u64() != Some(WIRE_VERSION) {
            return Err(MemoryError::configuration(format!(
                "wire version skew: the server speaks {}, this client speaks {WIRE_VERSION} — align the neosian versions on both ends (the wire is versioned with the library, DESIGN §18)",
                py_repr(wire)
            )).into());
        }
        remote.client = data
            .get("client")
            .and_then(Value::as_str)
            .map(str::to_string);
        remote.capabilities = data;
        Ok(remote)
    }

    fn call(&self, endpoint: &str, payload: Value) -> Result<Value, Error> {
        self.attempt(endpoint, payload)
            .map_err(|failed| failed.error)
    }

    /// A call whose failure says whether a size-paged retry may answer it
    /// (DESIGN §40.46, #418).
    fn attempt(&self, endpoint: &str, payload: Value) -> Result<Value, Failed> {
        let response = self
            .agent
            .post(format!("{}/v1/{endpoint}", self.base))
            .header(
                "Authorization",
                self.authorization.header().map_err(Failed::other)?,
            )
            .send_json(payload)
            .map_err(|error| Failed::other(driver(error)))?;
        self.answered(response, endpoint, true)
    }

    fn answer(
        &self,
        response: ureq::http::Response<ureq::Body>,
        endpoint: &str,
        envelope: bool,
    ) -> Result<Value, Error> {
        self.answered(response, endpoint, envelope)
            .map_err(|failed| failed.error)
    }

    fn answered(
        &self,
        mut response: ureq::http::Response<ureq::Body>,
        endpoint: &str,
        envelope: bool,
    ) -> Result<Value, Failed> {
        let status = response.status();
        // Bound untrusted response bytes before JSON allocation. Operators may
        // raise the local budget without changing a server's authorization.
        let maximum = crate::limits::response_bytes().map_err(Failed::other)?;
        let mut bytes = Vec::new();
        io::Read::read_to_end(
            &mut io::Read::take(response.body_mut().as_reader(), maximum + 1),
            &mut bytes,
        )
        .map_err(|error| Failed::other(error.into()))?;
        crate::limits::check(crate::limits::RESPONSE, bytes.len() as u64, maximum)
            .map_err(Failed::own)?;
        let decoded = serde_json::from_slice::<Value>(&bytes);
        if !status.is_success() {
            if envelope
                && let Ok(data) = &decoded
                && data["error"].is_object()
            {
                return Err(Failed::server(errors::decode(&data["error"])));
            }
            return Err(Failed::other(driver(ureq::Error::StatusCode(
                status.as_u16(),
            ))));
        }
        let data = decoded.map_err(|error| Failed::other(Error::Value(error.to_string())))?;
        if !data.is_object() {
            return Err(Failed::other(Error::Value(format!(
                "malformed wire response for '{}'",
                endpoint
            ))));
        }
        Ok(data)
    }

    /// Python's `_follow`: limits count rows, projections advance by whole
    /// turns on the server, and a missing continuation is malformed data.
    /// A memory listing's page refused for its size (this client's response
    /// budget, or a server's named answer-byte budget) is asked again
    /// with half the rows, down to one; the first refusal is reported if
    /// even that fails (DESIGN §40.46, #418). Every first request is 2.16.0's.
    fn follow(
        &self,
        endpoint: &str,
        mut payload: Value,
        items: &str,
        after: bool,
    ) -> Result<Vec<Value>, Error> {
        let (send, answer) = if after {
            ("after", "next_after")
        } else {
            ("cursor", "next_cursor")
        };
        let limit = payload["limit"].as_u64();
        let mut rows = Vec::new();
        let (mut smaller, mut first): (Option<u64>, Option<Error>) = (None, None);
        loop {
            let mut body = payload.clone();
            if let Some(size) = smaller {
                body["limit"] = json!(size);
            }
            let data = match self.attempt(endpoint, body) {
                Ok(data) => {
                    // A smaller page answered: an earlier size refusal is
                    // settled, and a later failure is reported as itself.
                    first = None;
                    data
                }
                Err(failed) if !after && self.listing_may_shrink(&failed) => {
                    let current = smaller
                        .unwrap_or_else(|| payload["limit"].as_u64().unwrap_or(500).min(500));
                    if first.is_none() {
                        first = Some(failed.error);
                    }
                    if current <= 1 {
                        return Err(first.take().expect("the size refusal is kept"));
                    }
                    smaller = Some(current / 2);
                    continue;
                }
                // Not a size refusal: the retry's own error, as it is.
                Err(failed) => return Err(failed.error),
            };
            let page = codec::array(&data, items)?;
            let next = codec::key(&data, answer)?;
            rows.extend(page.iter().cloned());
            if next.is_null() || page.is_empty() {
                return Ok(rows);
            }
            let remaining = limit.map(|limit| limit.saturating_sub(rows.len() as u64));
            if remaining == Some(0) {
                return Ok(rows);
            }
            if (after && next.as_u64().is_none()) || (!after && !next.is_string()) {
                return Err(codec::malformed(answer));
            }
            payload[send] = next.clone();
            payload["limit"] = json!(remaining);
            smaller = smaller.map(|size| remaining.map_or(size, |left| size.min(left)));
        }
    }

    /// Whether a memory listing's refused page may be asked again smaller:
    /// this client's own response budget, or a paging server's byte budget.
    fn listing_may_shrink(&self, failed: &Failed) -> bool {
        failed.own || self.pages_may_answer(failed)
    }
}

impl RemoteStore {
    fn names(&self, kind: &str) -> Result<Vec<String>, Error> {
        let data = self.call(&format!("store/{kind}"), json!({}))?;
        codec::array(&data, kind)?
            .iter()
            .map(|name| {
                name.as_str()
                    .map(str::to_string)
                    .ok_or_else(|| codec::malformed(kind))
            })
            .collect()
    }
    fn require_erasable(&self) -> Result<(), Error> {
        if self
            .capabilities
            .get("erasable")
            .is_some_and(|value| !crate::conversation::message::falsy(value))
        {
            return Ok(());
        }
        Err(MemoryError::configuration(
            "the server's backend does not implement Erasable — \
             its turns cannot be redacted (DESIGN §38)",
        )
        .into())
    }
}

/// A failed call. A smaller answer can help when either side reports its
/// answer-byte budget, or the server reports its spool-byte budget.
struct Failed {
    error: Error,
    sized: bool,
    own: bool,
}

impl Failed {
    fn server(error: Error) -> Self {
        let sized = matches!(&error, Error::Value(message) if matches!(
            message.strip_prefix("resource limit ").and_then(|msg| msg.split_once(" exceeded: ")),
            Some((crate::limits::RESPONSE | crate::limits::TEMP, _))
        ));
        Self {
            error,
            sized,
            own: false,
        }
    }
    fn own(error: Error) -> Self {
        Self {
            error,
            sized: true,
            own: true,
        }
    }
    fn other(error: Error) -> Self {
        Self {
            error,
            sized: false,
            own: false,
        }
    }
}

fn driver(error: ureq::Error) -> Error {
    io::Error::other(error).into()
}

/// Match httpx's custom CA-file door, with verification always enabled.
/// Otherwise rustls uses the Mozilla roots, as Python's certifi does.
pub(crate) fn tls() -> Result<TlsConfig, Error> {
    let mut config = TlsConfig::builder();
    if let Some(path) = std::env::var_os("SSL_CERT_FILE").filter(|s| !s.is_empty()) {
        let pem = std::fs::read(path)?;
        let mut certs = Vec::new();
        for item in parse_pem(&pem) {
            if let PemItem::Certificate(cert) = item.map_err(driver)? {
                certs.push(cert);
            }
        }
        if certs.is_empty() {
            return Err(driver(ureq::Error::Tls("No pem encoded cert found")));
        }
        config = config.root_certs(RootCerts::new_with_certs(&certs));
    }
    Ok(config.build())
}