neosian 3.0.2

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! The history pair on the server (`conversation/recall.py`'s
//! `create_recall_any_tool`, `search_history.py`'s `create_search_any_tool`,
//! `messaging/history.py`'s `augment_history`; DESIGN §21.7, §32, §34):
//! `conversation` required on `recall_turn`, any id the store holds
//! addressable; `search_history` store-wide with `conversation`
//! narrowing; both with the mailbox's annotations merged. On a store that
//! keeps records, or with `kinds`, `search_history` names a record per hit
//! (`history_records.rs`); otherwise it answers turns as released.

use serde_json::{Map, Value};

use super::history_records as records;
use super::{Outcome, Tool, integer, text};
use crate::assets::{TOOLS, mapping, quoted, render};
use crate::conversation::Error;
use crate::conversation::hits::hit_block;
use crate::conversation::recall as recalling;
use crate::conversation::search::parse_query;
use crate::mcp::schema::{Field, Kind, Presence};
use crate::mcp::server::Server;
use crate::messaging::history::{augment_recall, augment_search};
use crate::messaging::mailbox::Mailbox;
use crate::repr::repr;

const MAX_HITS: i64 = 50;

const RECALL_FIELDS: [Field; 6] = [
    Field {
        name: "turn",
        kind: Kind::Int,
        presence: Presence::Required,
    },
    Field {
        name: "conversation",
        kind: Kind::Str,
        presence: Presence::Required,
    },
    Field {
        name: "call",
        kind: Kind::Str,
        presence: Presence::Optional,
    },
    Field {
        name: "view",
        kind: Kind::Literal(&["light", "prompts", "calls", "full"]),
        presence: Presence::Optional,
    },
    Field {
        name: "seq",
        kind: Kind::Int,
        presence: Presence::Optional,
    },
    Field {
        name: "part",
        kind: Kind::Int,
        presence: Presence::Optional,
    },
];

const SEARCH_FIELDS: [Field; 7] = [
    Field {
        name: "query",
        kind: Kind::Str,
        presence: Presence::Required,
    },
    Field {
        name: "conversation",
        kind: Kind::Str,
        presence: Presence::Optional,
    },
    Field {
        name: "limit",
        kind: Kind::Int,
        presence: Presence::Default("10"),
    },
    Field {
        name: "order",
        kind: Kind::Literal(&["relevance", "newest"]),
        presence: Presence::Optional,
    },
    Field {
        name: "since",
        kind: Kind::Str,
        presence: Presence::Optional,
    },
    Field {
        name: "before",
        kind: Kind::Str,
        presence: Presence::Optional,
    },
    Field {
        name: "kinds",
        kind: Kind::StrList,
        presence: Presence::Optional,
    },
];

pub fn recall() -> Tool {
    Tool {
        name: "recall_turn",
        description: quoted(TOOLS, "recall_turn_any").expect("tools.yaml carries recall_turn_any"),
        params: mapping(TOOLS, "recall_turn_any_params").expect("tools.yaml carries the params"),
        fields: &RECALL_FIELDS,
        read_only: true,
        destructive: false,
        call: recall_call,
    }
}

pub fn search() -> Tool {
    Tool {
        name: "search_history",
        description: quoted(TOOLS, "search_history_any")
            .expect("tools.yaml carries search_history_any"),
        params: mapping(TOOLS, "search_history_any_params").expect("tools.yaml carries the params"),
        fields: &SEARCH_FIELDS,
        read_only: true,
        destructive: false,
        call: search_call,
    }
}

fn mailbox(server: &Server) -> Mailbox<'_> {
    let memory = &server.memory;
    Mailbox::of_mounts(memory.store.as_ref(), &memory.mounts, None).with_actor(memory.actor.clone())
}

fn corrective(corrective: recalling::Corrective) -> Outcome {
    let outcome = Outcome::fail(corrective.error);
    match corrective.hint {
        Some(hint) => outcome.hint(hint),
        None => outcome,
    }
}

/// A view or one part of a turn (§40.54 item 19), read through the
/// server's records when its store keeps them; only a view carries the
/// mailbox's annotations.
fn recall_call(server: &Server, arguments: &Map<String, Value>) -> Outcome {
    let turn = integer(arguments, "turn").unwrap_or_default();
    let conversation = text(arguments, "conversation").unwrap_or_default();
    let label = format!("Conversation {}", repr(conversation));
    let view = text(arguments, "view").and_then(recalling::View::parse);
    let (call, seq, part) = (
        text(arguments, "call"),
        integer(arguments, "seq"),
        integer(arguments, "part"),
    );
    let ask = match recalling::Ask::new(conversation, turn, view, call, seq, part) {
        Ok(ask) => ask,
        Err(refused) => return corrective(refused),
    };
    let records = match server.history().records() {
        Ok(records) => records,
        Err(error) => return Outcome::failed("recall_turn", &error.text()),
    };
    let store = server.memory.store.as_ref();
    let text = match recalling::recall(store, records.as_deref(), &ask, &label) {
        Ok(Ok(recalled)) if !recalled.view => return Outcome::ok(recalled.text),
        Ok(Ok(recalled)) => recalled.text,
        Ok(Err(refused)) => return corrective(refused),
        Err(error) => return Outcome::failed("recall_turn", &error.text()),
    };
    match augment_recall(&mailbox(server), text, conversation, turn) {
        Ok(text) => Outcome::ok(text),
        Err(error) => Outcome::failed("recall_turn", &error.text()),
    }
}

/// A turn search's failure: a refusal in its code's words, else the tool's
/// failure with guidance past the candidate bound.
pub(super) fn turn_failure(error: Error) -> Outcome {
    if let Error::Conversation(refused) = error {
        return Outcome::fail(format!("[{}] {}", refused.code, refused.message));
    }
    let text = error.text();
    let outcome = Outcome::failed("search_history", &text);
    match crate::assets::too_broad(&text, TOOLS, "search_history_too_broad") {
        Some(guidance) => outcome.hint(guidance),
        None => outcome,
    }
}

fn search_call(server: &Server, arguments: &Map<String, Value>) -> Outcome {
    let query = text(arguments, "query").unwrap_or_default();
    let terms = match parse_query(query) {
        Ok(terms) => terms,
        Err(_) => {
            // Version 1's hint stands wherever the order is newest.
            let newest = text(arguments, "order") == Some("newest")
                || !server.memory.store.history_ranking();
            let hint = if newest {
                "A turn matches when it holds every term, case-insensitively.".to_string()
            } else {
                quoted(TOOLS, "search_history_blank_ranked").expect("tools.yaml carries the hint")
            };
            return Outcome::fail("Give at least one search term").hint(hint);
        }
    };
    let limit = integer(arguments, "limit").unwrap_or(10);
    if limit < 1 {
        return Outcome::fail(format!("limit must be at least 1; got {limit}"));
    }
    let shown = limit.min(MAX_HITS) as usize;
    let narrowed = match text(arguments, "conversation") {
        Some(id) => Some(vec![id.to_string()]),
        None if server.memory.store.profile().is_some() => {
            match server.memory.store.conversations() {
                Ok(ids) => Some(ids),
                Err(error) => return Outcome::failed("search_history", &Error::from(error).text()),
            }
        }
        None => None,
    };
    let ids = narrowed.as_deref();
    // A store that keeps records names a record per hit; without records,
    // only a call naming kinds leaves the turn search's answer (§40.54
    // items 15.2 and 19).
    let kinds = match records::kinds(arguments) {
        Ok(kinds) => kinds,
        Err(outcome) => return outcome,
    };
    let kept = match server.history().records() {
        Ok(kept) => kept,
        Err(error) => return Outcome::failed("search_history", &error.text()),
    };
    if kept.is_some() || kinds.is_some() {
        let call = records::Call {
            server,
            arguments,
            query,
            terms: &terms,
            ids,
            shown,
            kinds,
        };
        return records::search(call, kept.as_deref());
    }
    let ranking = match super::history_rank::resolve(server, arguments, &terms, ids, shown) {
        Ok(ranking) => ranking,
        Err(outcome) => return outcome,
    };
    let turns = match ranking.found(server, &terms, ids, shown) {
        Ok(turns) => turns,
        Err(error) => return turn_failure(error),
    };
    let relevance = ranking.relevance();
    let key = if relevance {
        "search_history_footer_ranked"
    } else {
        "search_history_footer"
    };
    let footer = render(
        &quoted(TOOLS, key).expect("tools.yaml carries the footer"),
        &[("shown", &shown.to_string())],
    );
    let merged = augment_search(
        &mailbox(server),
        &turns,
        &terms,
        ids,
        shown,
        relevance,
        ranking.bounds(),
    );
    match merged {
        // A relevance answer always names its order (§40.43); version 1's
        // merged answer keeps its bytes, without a footer.
        Ok(Some(merged)) if relevance => {
            return Outcome::ok(ranking.frame(format!("{merged}\n\n{footer}")));
        }
        Ok(Some(merged)) => return Outcome::ok(ranking.frame(merged)),
        Ok(None) => {}
        Err(error) => return Outcome::failed("search_history", &error.text()),
    }
    if turns.is_empty() {
        let listed: Vec<String> = terms.iter().map(|term| repr(term)).collect();
        let listed = listed.join(", ");
        let text = if relevance {
            let template =
                quoted(TOOLS, "search_history_none_ranked").expect("tools.yaml carries the note");
            render(&template, &[("terms", &listed)])
        } else {
            format!("No turn matches every term: {listed}. Try fewer or different terms.")
        };
        return Outcome::ok(ranking.frame(text));
    }
    let mut lines: Vec<String> = turns.iter().map(hit_block).collect();
    lines.push(footer);
    Outcome::ok(ranking.frame(lines.join("\n")))
}