neosian 3.0.0

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! One queued turn given to its store (DESIGN §40.54 items 15.2, 17.3,
//! 17.4 and 25.13; rulings D8, D10, E8 and E9 of the T1e1 plan), a local
//! store or a server alike: as records in one draft when the store keeps
//! records and they can carry every message, else whole as one
//! `append_turn` (a server without turn records, a 404 on `write_records`,
//! a call id or name over 1,024 bytes).
//!
//! The draft follows the rules of 17.4 (`rules.rs`, `seal.rs`). A draft
//! that does not match the turn (`draft_mismatch`, `draft_size`, a draft
//! longer than the turn) is discarded and the turn written again under the
//! fresh id, once: the state's `attempt` and draft id move first, so a run
//! cut meanwhile resumes the fresh draft, and a refusal of the fresh id
//! holds the turn `mismatch`. A draft that expired (`draft_gap`, 410)
//! starts again from `seq` 0 under the same id, once in a run.
//! `agent_configuration_error` reads the capability again once: gone, the
//! turn goes whole; still there, or the store cannot be opened again, the
//! turn is kept and the destination waits (ruling E15). An answer to the
//! fallback that cannot be read holds the turn `unreadable`: it may be
//! stored, and it is never removed nor sent again by itself (ruling E14).
//!
//! A 429 with a `Retry-After` of at most 10 s is waited out and the part
//! asked again (a draft probes first, so it repeats from what the store
//! holds), within the run's 30 s (`Patience`); past them, or without a
//! budget, the destination waits as after a longer `Retry-After` (17.4).
//! The attempt at a blocked destination (`gate.rs`) is decided by its
//! first part: here, by the one `append_turn` of a turn sent whole. Each
//! `append_turn`, a repeat after a wait too, and each write of the state
//! starts only as the lander's admission allows (`admit.rs`, rulings G1
//! and G2). A sealed turn reports what its listing counts: the kinds of
//! the records packed and the bytes of the sealed header.

use std::path::Path;

use super::admit::Admit;
use super::answer::Answer;
use super::cap::Halt;
use super::draft::fresh_id;
use super::pack::{Draft, turn_bytes};
use super::rules::{Action, Route, Stop, WAIT_SECONDS, decide, unopened};
use super::seal::{Sent, send};
use super::sink::{Appended, Sink};
use super::state::{Reason, State};
use crate::conversation::message::Message;
use crate::conversation::sessions::listing::{Kinds, Landed};
use crate::conversation::turn_records::records_of;
use crate::conversation::{Error, Turn};
use crate::remote::selection::Selection;

/// The message of a turn whose `append_turn` was answered with a 2xx that
/// could not be read (ruling E14); its reason file marks it `may_be_stored`.
pub const UNREADABLE_ANSWER: &str = "a 2xx was answered but could not be read; it may be stored";

/// How a queued turn ended in this run.
#[derive(Debug)]
pub enum Ended {
    /// The store has the turn.
    Stored(Turn),
    /// Held with the reason; the next turn goes on.
    Held(Reason),
    /// The turn stays queued.
    Kept(Stop),
    /// The conversation was paused mid-turn; its draft is discarded.
    Paused,
}

/// The queued turn being landed: its conversation, its opening line (the
/// fresh id is derived from it) and its state file.
pub struct Queued<'a> {
    pub id: &'a str,
    pub line: &'a str,
    pub file: &'a Path,
}

/// `store_until` without a halt, as the tests of `remote/` call it.
#[cfg(test)]
pub fn store(
    sink: &mut Sink,
    selection: &Selection,
    queued: &Queued,
    state: &mut State,
    messages: Vec<Message>,
) -> Result<Ended, Error> {
    store_until(sink, selection, &Halt::NONE, queued, state, messages).map(|(ended, _)| ended)
}

/// Gives the queued turn, whose messages are `messages` and whose state is
/// `state`, to the store `sink` opened from `selection`; no part starts
/// once `halt` says to stop. Beside its end, what a sealed turn's listing
/// counts.
pub fn store_until(
    sink: &mut Sink,
    selection: &Selection,
    halt: &Halt,
    queued: &Queued,
    state: &mut State,
    messages: Vec<Message>,
) -> Result<(Ended, Option<Landed>), Error> {
    let mut landed = None;
    let ended = until(sink, selection, halt, queued, state, messages, &mut landed)?;
    Ok((ended, landed))
}

fn until(
    sink: &mut Sink,
    selection: &Selection,
    halt: &Halt,
    queued: &Queued,
    state: &mut State,
    mut messages: Vec<Message>,
    landed: &mut Option<Landed>,
) -> Result<Ended, Error> {
    let id = queued.id;
    sink.admit(id)?;
    let (mut restarted, mut reread) = (false, false);
    loop {
        let (sent, kinds) = {
            let Some(records) = sink.records()? else {
                return whole(sink, halt, id, &mut messages, &state.actor);
            };
            let Ok(turn) = records_of(&messages) else {
                return whole(sink, halt, id, &mut messages, &state.actor);
            };
            let kinds = Kinds::of(&turn);
            let (draft_id, actor) = (state.draft.clone(), state.actor.clone());
            let draft = Draft {
                conversation: id,
                draft: &draft_id,
                actor: &actor,
                turn_bytes: turn_bytes(&turn),
            };
            (
                send(&records, &draft, turn, state, queued.file, halt)?,
                kinds,
            )
        };
        match sent {
            Sent::Sealed(header) => {
                let bytes = header.bytes;
                *landed = Some(Landed { kinds, bytes });
                return Ok(Ended::Stored(Turn {
                    conversation_id: id.to_string(),
                    turn: header.turn,
                    messages,
                    created_at: header.created_at,
                    actor: header.actor,
                    redacted: false,
                }));
            }
            Sent::Held(reason) => return Ok(Ended::Held(reason)),
            Sent::Fresh(_) | Sent::Restart if !halt.ours()? => return Ok(Ended::Paused),
            // No seal of the fresh draft, or of the draft started again, has
            // been sent: the answer that ended the old one says it was open.
            Sent::Fresh(_) if state.attempt == 0 => {
                state.attempt = 1;
                state.draft = fresh_id(id, queued.line);
                (state.next_seq, state.sealing) = (0, false);
                state.write(queued.file)?;
            }
            Sent::Fresh(reason) => return Ok(Ended::Held(reason)),
            Sent::Restart if !restarted => {
                restarted = true;
                (state.next_seq, state.sealing) = (0, false);
                state.write(queued.file)?;
            }
            Sent::Restart => {
                let message = format!("draft {} expired twice in one run", state.draft);
                return Ok(Ended::Kept(Stop::Conversation(message)));
            }
            Sent::Reread(message) if !reread => {
                reread = true;
                match Sink::open(selection) {
                    Ok(opened) => *sink = opened,
                    Err(error) => return Ok(Ended::Kept(unopened(&error))),
                }
                if sink.records()?.is_some() {
                    return Ok(waits(message));
                }
            }
            Sent::Reread(message) => return Ok(waits(message)),
            Sent::Whole => return whole(sink, halt, id, &mut messages, &state.actor),
            Sent::Kept(stop) => {
                if let Some(stop) = retried(halt, stop) {
                    return Ok(Ended::Kept(stop));
                }
            }
            Sent::Paused => return Ok(Ended::Paused),
        }
    }
}

/// A stop after a 429 of at most 10 s, once its wait is waited out within
/// the run's budget: `None`, and the request is asked again. Past the
/// budget, the destination waits as after a longer `Retry-After`. Any
/// other stop is kept as it is.
fn retried(halt: &Halt, stop: Stop) -> Option<Stop> {
    match stop {
        Stop::Retry { seconds, .. } if halt.patience.is_some_and(|p| p.wait(seconds)) => None,
        Stop::Retry { seconds, message } => Some(Stop::Wait {
            seconds,
            failing: false,
            message,
        }),
        other => Some(other),
    }
}

/// The turn kept and its destination waiting, as after a fault.
fn waits(message: String) -> Ended {
    Ended::Kept(Stop::Wait {
        seconds: WAIT_SECONDS,
        failing: true,
        message,
    })
}

/// The turn whole, as one `append_turn` (DESIGN §40.54 item 15.2), asked
/// again after a 429 of at most 10 s within the run's budget.
fn whole(
    sink: &Sink,
    halt: &Halt,
    id: &str,
    messages: &mut Vec<Message>,
    actor: &str,
) -> Result<Ended, Error> {
    loop {
        match halt.admit()? {
            Admit::Go => {}
            Admit::Paused => return Ok(Ended::Paused),
            Admit::Off(message) => return Ok(Ended::Kept(Stop::Conversation(message))),
        }
        match appended(sink, halt, id, messages, actor)? {
            Ended::Kept(stop) => {
                if let Some(stop) = retried(halt, stop) {
                    return Ok(Ended::Kept(stop));
                }
            }
            ended => return Ok(ended),
        }
    }
}

/// One `append_turn`: stored, held for a refused value, a 413 or any other
/// 4xx, kept for what passes. An unreadable 2xx may have stored it, so it
/// is held, never removed and never sent again by itself (ruling E14). A
/// 2xx takes the attempt at a blocked destination; any other answer ends
/// it with the turn kept.
fn appended(
    sink: &Sink,
    halt: &Halt,
    id: &str,
    messages: &mut Vec<Message>,
    actor: &str,
) -> Result<Ended, Error> {
    let answer = match sink.append(id, messages, actor.to_string())? {
        Appended::Stored(turn) => {
            if let Some(trial) = halt.trying() {
                trial.taken()?;
            }
            return Ok(Ended::Stored(turn));
        }
        Appended::Not(Answer::Unreadable(_)) => {
            if let Some(trial) = halt.trying() {
                trial.taken()?;
            }
            return Ok(Ended::Held(Reason::may_be_stored(UNREADABLE_ANSWER.into())));
        }
        Appended::Not(answer) => answer,
    };
    if let Some(trial) = halt.trying() {
        return Ok(Ended::Kept(
            trial.refused(decide(Route::Whole, &answer), &answer),
        ));
    }
    Ok(match decide(Route::Whole, &answer) {
        Action::Hold(reason) | Action::HoldAside(reason) | Action::Fresh(reason) => {
            Ended::Held(reason)
        }
        Action::Keep(stop) => Ended::Kept(stop),
        _ => Ended::Kept(Stop::Wait {
            seconds: WAIT_SECONDS,
            failing: true,
            message: format!(
                "append_turn was answered as a records route: {}",
                super::answer::said(&answer)
            ),
        }),
    })
}