Her agent: agent::step, one bounded turn of a persistent session over KitModel with tools

agent::step owns one agent turn: the loop over executors, its bounds and the
session's freshness. Tool calls (8), model calls (10) and spend ($0.40) per wake
and spend per Mind per UTC day ($3.00, read back from her trace's call rows and
priced by tuning [agent]) are checked before every call; a bound ends the loop
with a cap receipt. Every receipt, call and discard is a trace row (TraceLedger;
turn::is_real reads no agent row as a turn). FileSession keeps the conversation
until the cache is predicted cold (ttl, digest, size, orphan tool call) or observed
cold (a warm prefix read as nothing), when it is discarded with a session_discarded row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-29 21:45:22 +01:00
commit 9d18d84604
7 changed files with 1124 additions and 2 deletions

View file

@ -19,6 +19,7 @@
//! `MouthReader` reads pending chat, `DomainSource` reads her domain, `ReadSource` performs the reads she reaches for, `Model` asks. None of them can put, admit, send, ack or open a conversation, so
//! `project` cannot write and runs under a held brake.
pub mod agent;
pub mod harness;
mod commit;
mod domain;

View file

@ -0,0 +1,523 @@
//! Her agent (map 16.38.6 and 16.38.10): one turn of a persistent session over the connector with tools, bounded per wake and
//! per day.
//!
//! `step` owns one agent turn: the loop, its bounds and the session's freshness. The drain hands it the wake's input (the
//! Persona's monologue, the waking lines, the receipts since her last wake) and the executors; each executor owns its tool's
//! effect and the receipt it returns. The model never writes a receipt: code does, one per tool call, and the receipt's JSON
//! is the `ToolResult` the model reads. Every call, receipt and discard is a row in her trace (`Ledger`), and the trace is
//! the record; the session (`FileSession`) is a cache of her agent's turns and is discarded the moment the provider's cache
//! behind it is gone or cannot be trusted.
//!
//! The bounds are enforced here, before each call: tool calls, model calls and spend per wake, and spend per Mind per UTC
//! day. The day's spend is read back from her trace's `call` rows and priced by the tuning's table, so it survives a restart
//! and no other store holds it. Past a bound the loop ends with a `cap` receipt; a call is never made past one.
use std::path::PathBuf;
use anyhow::{Result, bail};
use chrono::{DateTime, Duration, Utc};
use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore};
use model_connector::{CacheRetention, InputItem, StopReason, ToolDefinition};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use sha2::{Digest, Sha256};
use super::narrate::{Failed, KitModel, Spent, StepRequest, Stepped, ToolCall};
use super::tuning::{AgentTuning, CACHE_MARGIN_S};
use crate::persona::Trace;
/// The connector, as the loop calls it: `KitModel` live, a script in a test.
pub trait Steps {
fn step(&self, request: StepRequest<'_>) -> std::result::Result<Stepped, Failed>;
}
impl Steps for KitModel {
fn step(&self, request: StepRequest<'_>) -> std::result::Result<Stepped, Failed> {
KitModel::step(self, request)
}
}
/// What became of one tool call, said by the executor and never by the model.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Status {
/// The effect happened.
Ok,
/// The tool's owner declined it, with a reason in the fields.
Refused,
/// It was tried and failed.
Error,
/// It was handed over and no answer is known: it may or may not have happened.
Unknown,
/// It was not sent.
NotSent,
/// The loop's bound stopped it, or the loop itself.
Cap,
}
/// One tool call's receipt: the tool, its status and its fields. There is no way to make one without a status, and the
/// fields are private, so a receipt is built by `new` or not at all:
///
/// ```compile_fail
/// let _ = mind_body::projection::agent::Receipt { tool: "say".into(), fields: Default::default() };
/// ```
#[derive(Clone, Debug, PartialEq)]
pub struct Receipt {
tool: String,
status: Status,
fields: Map<String, Value>,
}
impl Receipt {
/// `fields` is a JSON object; any other value is kept under `detail`.
pub fn new(tool: impl Into<String>, status: Status, fields: Value) -> Self {
let fields = match fields {
Value::Object(map) => map,
Value::Null => Map::new(),
other => Map::from_iter([("detail".to_owned(), other)]),
};
Self { tool: tool.into(), status, fields }
}
pub fn tool(&self) -> &str {
&self.tool
}
pub fn status(&self) -> Status {
self.status
}
pub fn fields(&self) -> &Map<String, Value> {
&self.fields
}
/// The receipt as it is written to her trace and as the model reads it.
pub fn json(&self) -> Value {
json!({ "tool": self.tool, "status": self.status, "fields": self.fields })
}
}
/// One tool's owner: it defines the tools it runs and runs each call it is handed, answering with a receipt.
pub trait Executor {
fn definitions(&self) -> Vec<ToolDefinition>;
fn run(&self, call: &ToolCall) -> Receipt;
}
/// Her trace as the loop sees it: her agent's rows, read back and appended. The drain's `TraceLedger` is the live one.
pub trait Ledger {
/// Every agent row, oldest first.
fn rows(&self) -> Result<Vec<Value>>;
fn append(&self, row: Value) -> Result<()>;
}
/// The agent's rows in her trace: each is a record with an `agent` field naming its kind (`call`, `receipt`,
/// `session_discarded`), a `seq` (the place it holds in her trace) and the time it was made. `turn::is_real` knows them as no turn.
pub struct TraceLedger<'a> {
trace: &'a dyn Trace,
stem: String,
}
impl<'a> TraceLedger<'a> {
/// `stem` makes the records' keys: `<stem>-g<place>`.
pub fn new(trace: &'a dyn Trace, stem: impl Into<String>) -> Self {
Self { trace, stem: stem.into() }
}
}
impl Ledger for TraceLedger<'_> {
fn rows(&self) -> Result<Vec<Value>> {
Ok(self.trace.records()?.into_iter().filter(|record| record.get("agent").is_some()).collect())
}
fn append(&self, mut row: Value) -> Result<()> {
let place = self.trace.records()?.len();
row["seq"] = json!(place);
self.trace.record(&format!("{}-g{place}", self.stem), &row)
}
}
/// Her agent session: the conversation verbatim, what it was built under, and the last call's cost.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Session {
pub items: Vec<InputItem>,
/// SHA-256 of the instructions, the tool definitions and the model.
pub digest: String,
pub retention: CacheRetention,
pub created_at: DateTime<Utc>,
pub last_call_at: DateTime<Utc>,
pub last_usage: Option<Spent>,
}
/// The session's one row in its store.
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
#[cultcache(type = "eureka.persona.agent_session.v1", schema = "PersonaAgentSession")]
struct SessionRow {
#[cultcache(key = 0)]
value: Value,
}
const SESSION_KEY: &str = "session";
/// The session in a CultCache single-file store (`agent-session.cc` under the unit's state directory), written only by the drain.
pub struct FileSession {
path: PathBuf,
}
impl FileSession {
pub fn new(path: impl Into<PathBuf>) -> Self {
Self { path: path.into() }
}
fn open(&self) -> Result<CultCache> {
let mut cache = CultCache::new();
cache.register_entry_type::<SessionRow>()?;
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&self.path))?;
cache.pull_all_backing_stores()?;
Ok(cache)
}
/// The session, or none when there is none. A store that cannot be read, or holds a session that does not decode, is an error.
pub fn load(&self) -> Result<Option<Session>> {
match self.open()?.get::<SessionRow>(SESSION_KEY)? {
Some(row) => Ok(Some(serde_json::from_value(row.value)?)),
None => Ok(None),
}
}
pub fn save(&self, session: &Session) -> Result<()> {
self.open()?.put(SESSION_KEY, &SessionRow { value: serde_json::to_value(session)? })?;
Ok(())
}
/// Forget the session. Nothing to forget is no error, and a store that cannot be opened is removed whole: it holds nothing else.
pub fn discard(&self) -> Result<()> {
if self.open().and_then(|mut cache| cache.delete::<SessionRow>(SESSION_KEY).map(|_| ())).is_ok() {
return Ok(());
}
match std::fs::remove_file(&self.path) {
Err(fault) if fault.kind() != std::io::ErrorKind::NotFound => Err(fault.into()),
_ => Ok(()),
}
}
}
/// What stopped a loop at a bound.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Cap {
ToolCalls,
ModelCalls,
WakeSpend,
DaySpend,
}
impl Cap {
fn name(self) -> &'static str {
match self {
Self::ToolCalls => "tool_calls",
Self::ModelCalls => "model_calls",
Self::WakeSpend => "wake_usd",
Self::DaySpend => "day_usd",
}
}
}
/// How the turn ended.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Ended {
/// The model ended its turn.
EndTurn,
/// A bound stopped it; the cap receipt is in `receipts` and in her trace.
Cap(Cap),
/// The turn could not go on. The connector's own failure, kept whole: its `outage` says whether it is a strike.
Failed(Failed),
}
/// One agent turn: what it ended on, its last words, the receipts it earned in order, and what it used.
#[derive(Clone, Debug, PartialEq)]
pub struct Turn {
pub ended: Ended,
pub text: String,
pub receipts: Vec<Receipt>,
pub model_calls: usize,
pub tool_calls: usize,
pub usd: f64,
}
/// What the loop runs on. `clock` is read for every time it stamps or compares.
pub struct Agent<'a> {
pub model: &'a dyn Steps,
pub session: &'a FileSession,
pub executors: &'a [&'a dyn Executor],
pub ledger: &'a dyn Ledger,
pub bounds: &'a AgentTuning,
pub clock: &'a dyn Fn() -> DateTime<Utc>,
}
/// One wake's offering: its identity (request ids and trace keys derive from it, so it is unique per wake), the fixed
/// instructions and the input.
pub struct Wake<'a> {
pub id: &'a str,
pub instructions: &'a str,
pub input: &'a str,
}
/// Her agent's instructions: fixed, naming her. Her prose is hers, and what is said aloud is hers to say, in her words
/// where she gave them; the agent carries no persona text of its own (`say-in-her-words`).
pub fn instructions(name: &str) -> String {
format!(
"You act for {name}. Each wake you are given what {name} has just lived and thought, in her own prose, with the lines that woke her and what came of her last acts. \
You act for her only through your tools; each tool call is answered with a receipt, and the receipt is the only truth about what happened. \
Her prose is hers: do not rewrite it and do not speak as yourself. What is said aloud in chat is hers to say: when you say something, use her own words where her prose gave them, and add no voice of your own. \
When nothing needs doing, end your turn without acting."
)
}
/// Runs one agent turn. Day cap first, then the session's freshness, then the loop; see the module's text. A bug in the
/// caller (two executors defining one tool, an empty input) is an `Err`; everything the world does is in `Turn::ended`.
pub fn step(agent: &Agent<'_>, wake: &Wake<'_>) -> Result<Turn> {
if wake.input.trim().is_empty() {
bail!("a wake with no input");
}
let mut tools: Vec<ToolDefinition> = Vec::new();
let mut owners: Vec<(String, usize)> = Vec::new();
for (at, executor) in agent.executors.iter().enumerate() {
for definition in executor.definitions() {
if owners.iter().any(|(name, _)| *name == definition.name) {
bail!("two executors define the tool {}", definition.name);
}
owners.push((definition.name.clone(), at));
tools.push(definition);
}
}
let bounds = agent.bounds;
let digest = digest_of(&bounds.model, wake.instructions, &tools);
let mut run = Run { agent, wake, receipts: Vec::new(), usd: 0.0, model_calls: 0, tool_calls: 0 };
let now = (agent.clock)();
let day_before = day_usd(&agent.ledger.rows()?, now, bounds);
if day_before >= bounds.day_usd {
let ended = run.cap(Cap::DaySpend, day_before)?;
return Ok(run.turn(ended, String::new()));
}
// The session as it stands, or the reason it cannot be trusted.
let kept = match agent.session.load() {
Ok(Some(held)) => match stale(&held, &digest, now, bounds) {
Some(why) => {
run.discard(why)?;
None
}
None => Some(held),
},
Ok(None) => None,
Err(_) => {
run.discard("unreadable")?;
None
}
};
let created_at = kept.as_ref().map_or(now, |held| held.created_at);
let mut last_usage = kept.as_ref().and_then(|held| held.last_usage.clone());
// The prefix the provider is expected to hold for the next call: what the last call sent, when the session is kept.
let mut warm_prefix = last_usage.as_ref().map_or(0, prompt_tokens);
let mut items = kept.map_or_else(Vec::new, |held| held.items);
items.push(InputItem::UserText { text: wake.input.to_owned() });
let conversation = format!("agent-{}", created_at.timestamp());
let mut text = String::new();
let mut cold = false;
let ended = loop {
if run.model_calls >= bounds.model_calls {
break run.cap(Cap::ModelCalls, bounds.model_calls as f64)?;
}
if run.usd >= bounds.wake_usd {
break run.cap(Cap::WakeSpend, run.usd)?;
}
if day_before + run.usd >= bounds.day_usd {
break run.cap(Cap::DaySpend, day_before + run.usd)?;
}
let request_id = format!("{}-m{}", wake.id, run.model_calls + 1);
let answer = agent.model.step(StepRequest { request_id: &request_id, conversation_id: &conversation, model: &bounds.model, instructions: wake.instructions, tools: &tools, input: items.clone(), retention: Some(bounds.retention), schema: None });
let stepped = match answer {
Ok(stepped) => stepped,
Err(failed) => {
if let Some(usage) = &failed.usage {
run.usd += price(bounds, usage);
}
let row = json!({ "agent": "call", "at": (agent.clock)().to_rfc3339(), "wake": wake.id, "model": bounds.model, "usage": failed.usage, "failed": failed.reason });
if let Err(fault) = agent.ledger.append(row) {
break Ended::Failed(ledger_failed(&fault));
}
break Ended::Failed(failed);
}
};
run.model_calls += 1;
let cost = price(bounds, &stepped.usage);
run.usd += cost;
let at = (agent.clock)();
let row = json!({ "agent": "call", "at": at.to_rfc3339(), "wake": wake.id, "model": bounds.model, "usage": stepped.usage, "usd": cost, "stop": format!("{:?}", stepped.stop) });
if let Err(fault) = agent.ledger.append(row) {
break Ended::Failed(ledger_failed(&fault));
}
// Observed: a prefix the provider should hold was read as nothing, so the cache is gone. The wake finishes on what it has.
if warm_prefix >= bounds.cache_min_tokens && stepped.usage.cache_read_tokens == 0 {
cold = true;
}
warm_prefix = prompt_tokens(&stepped.usage);
last_usage = Some(stepped.usage.clone());
items.extend(stepped.items.iter().cloned());
if !stepped.text.is_empty() {
text.clone_from(&stepped.text);
}
let held = Session { items: items.clone(), digest: digest.clone(), retention: bounds.retention, created_at, last_call_at: at, last_usage: last_usage.clone() };
if let Err(fault) = agent.session.save(&held) {
break Ended::Failed(ledger_failed(&fault));
}
match (stepped.stop, stepped.calls.is_empty()) {
(StopReason::EndTurn, true) => break Ended::EndTurn,
(StopReason::ToolUse, false) => {}
(stop, _) => {
// A stop the loop cannot continue from, or a tool call cut short: nothing in the session can be trusted past it.
run.discard("stopped")?;
break Ended::Failed(Failed { reason: format!("the agent's turn ended early: {stop:?}"), outage: false, usage: None });
}
}
let mut over = false;
let mut broke = None;
for call in &stepped.calls {
let receipt = if run.tool_calls >= bounds.tool_calls {
over = true;
Receipt::new(&call.name, Status::Cap, json!({ "cap": Cap::ToolCalls.name(), "limit": bounds.tool_calls }))
} else {
run.tool_calls += 1;
match owners.iter().find(|(name, _)| *name == call.name) {
Some((_, at)) => agent.executors[*at].run(call),
None => Receipt::new(&call.name, Status::Refused, json!({ "reason": "no such tool" })),
}
};
if let Err(fault) = run.receipt(receipt.clone()) {
broke = Some(Ended::Failed(ledger_failed(&fault)));
break;
}
items.push(InputItem::ToolResult { call_id: call.call_id.clone(), output: receipt.json().to_string() });
}
if let Some(ended) = broke {
// A call without its result in the session: the next start discards it.
break ended;
}
let held = Session { items: items.clone(), digest: digest.clone(), retention: bounds.retention, created_at, last_call_at: at, last_usage: last_usage.clone() };
if let Err(fault) = agent.session.save(&held) {
break Ended::Failed(ledger_failed(&fault));
}
if over {
break run.cap(Cap::ToolCalls, bounds.tool_calls as f64)?;
}
};
if cold {
run.discard("cache_miss")?;
}
Ok(run.turn(ended, text))
}
/// The loop's running account: what the turn has earned and spent so far.
struct Run<'a> {
agent: &'a Agent<'a>,
wake: &'a Wake<'a>,
receipts: Vec<Receipt>,
usd: f64,
model_calls: usize,
tool_calls: usize,
}
impl Run<'_> {
/// A receipt is a row in her trace first, and then the turn's.
fn receipt(&mut self, receipt: Receipt) -> Result<()> {
let row = json!({ "agent": "receipt", "at": (self.agent.clock)().to_rfc3339(), "wake": self.wake.id, "receipt": receipt.json() });
self.agent.ledger.append(row)?;
self.receipts.push(receipt);
Ok(())
}
/// The bound that ended the loop, as a `cap` receipt of the loop's own.
fn cap(&mut self, cap: Cap, reached: f64) -> Result<Ended> {
self.receipt(Receipt::new("agent", Status::Cap, json!({ "cap": cap.name(), "reached": reached })))?;
Ok(Ended::Cap(cap))
}
/// Forget the session, and say why in her trace.
fn discard(&mut self, why: &str) -> Result<()> {
self.agent.session.discard()?;
self.agent.ledger.append(json!({ "agent": "session_discarded", "at": (self.agent.clock)().to_rfc3339(), "wake": self.wake.id, "why": why }))
}
fn turn(self, ended: Ended, text: String) -> Turn {
Turn { ended, text, receipts: self.receipts, model_calls: self.model_calls, tool_calls: self.tool_calls, usd: self.usd }
}
}
fn ledger_failed(fault: &anyhow::Error) -> Failed {
// Her own store failed, not the world: nothing about it is a strike against a line.
Failed { reason: format!("the agent's record could not be written: {fault:#}"), outage: true, usage: None }
}
/// The tokens a call sent as its prompt, whether read from the cache, written to it or plain.
fn prompt_tokens(usage: &Spent) -> u64 {
usage.input_tokens + usage.cache_read_tokens + usage.cache_write_tokens
}
/// What `usage` costs, USD, by the tuning's table.
fn price(bounds: &AgentTuning, usage: &Spent) -> f64 {
let price = bounds.price(&usage.model);
let million = 1_000_000.0;
(usage.input_tokens as f64 * price.input + usage.output_tokens as f64 * price.output + usage.cache_read_tokens as f64 * price.cache_read + usage.cache_write_tokens as f64 * price.cache_write) / million
}
/// The UTC day's spend so far, from the `call` rows of her trace dated `now`'s day.
fn day_usd(rows: &[Value], now: DateTime<Utc>, bounds: &AgentTuning) -> f64 {
rows.iter()
.filter(|row| row["agent"] == "call")
.filter(|row| row["at"].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok()).is_some_and(|at| at.with_timezone(&Utc).date_naive() == now.date_naive()))
.filter_map(|row| serde_json::from_value::<Spent>(row["usage"].clone()).ok())
.map(|usage| price(bounds, &usage))
.sum()
}
fn digest_of(model: &str, instructions: &str, tools: &[ToolDefinition]) -> String {
let mut hash = Sha256::new();
for part in [model, instructions] {
hash.update((part.len() as u64).to_le_bytes());
hash.update(part.as_bytes());
}
for tool in tools {
for part in [&tool.name, &tool.description, &tool.parameters_json] {
hash.update((part.len() as u64).to_le_bytes());
hash.update(part.as_bytes());
}
}
hash.finalize().iter().map(|byte| format!("{byte:02x}")).collect()
}
/// Why a kept session may not be used, or none: a tool call with no result (a start was killed between), a digest that is
/// no longer this agent's, a cache that has run out or is about to, and a prompt grown past what is kept.
fn stale(session: &Session, digest: &str, now: DateTime<Utc>, bounds: &AgentTuning) -> Option<&'static str> {
let orphan = session.items.iter().any(|item| match item {
InputItem::ToolCall { call_id, .. } => !session.items.iter().any(|other| matches!(other, InputItem::ToolResult { call_id: answered, .. } if answered == call_id)),
_ => false,
});
if orphan {
return Some("orphan_tool_call");
}
if session.digest != digest {
return Some("digest");
}
let life = i64::try_from(bounds.ttl(session.retention).saturating_sub(CACHE_MARGIN_S)).unwrap_or(i64::MAX);
if now - session.last_call_at > Duration::seconds(life) {
return Some("ttl");
}
if session.last_usage.as_ref().is_some_and(|usage| prompt_tokens(usage) > bounds.max_session_tokens) {
return Some("too_long");
}
None
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,415 @@
use std::cell::{Cell, RefCell};
use std::collections::VecDeque;
use chrono::TimeZone;
use super::*;
use crate::persona::{FileTrace, TraceView};
const MODEL: &str = "claude-sonnet-5-5";
fn noon() -> DateTime<Utc> {
Utc.with_ymd_and_hms(2026, 11, 29, 12, 0, 0).unwrap()
}
fn usage(input: u64, output: u64, cache_read: u64, cache_write: u64) -> Spent {
Spent { model: MODEL.into(), input_tokens: input, output_tokens: output, cache_read_tokens: cache_read, cache_write_tokens: cache_write, reasoning_tokens: None }
}
fn small() -> Spent {
usage(100, 20, 0, 0)
}
fn asks(call_id: &str, tool: &str, spent: Spent) -> std::result::Result<Stepped, Failed> {
let call = ToolCall { call_id: call_id.into(), name: tool.into(), arguments: "{}".into() };
Ok(Stepped { items: vec![InputItem::ToolCall { call_id: call.call_id.clone(), name: call.name.clone(), arguments: call.arguments.clone() }], text: String::new(), calls: vec![call], stop: StopReason::ToolUse, usage: spent })
}
fn ends(text: &str, spent: Spent) -> std::result::Result<Stepped, Failed> {
Ok(Stepped { items: vec![InputItem::AssistantText { text: text.into() }], text: text.into(), calls: vec![], stop: StopReason::EndTurn, usage: spent })
}
/// The connector as a script: each call answers the next entry and keeps the conversation it was sent.
struct Script {
answers: RefCell<VecDeque<std::result::Result<Stepped, Failed>>>,
seen: RefCell<Vec<Vec<InputItem>>>,
ids: RefCell<Vec<String>>,
}
impl Script {
fn new(answers: Vec<std::result::Result<Stepped, Failed>>) -> Self {
Self { answers: RefCell::new(answers.into()), seen: RefCell::default(), ids: RefCell::default() }
}
/// A model that asks `tool` on every call, whatever it is told.
fn endless(tool: &str, calls: usize) -> Self {
Self::new((0..calls).map(|at| asks(&format!("c{at}"), tool, small())).collect())
}
}
impl Steps for Script {
fn step(&self, request: StepRequest<'_>) -> std::result::Result<Stepped, Failed> {
self.seen.borrow_mut().push(request.input.clone());
self.ids.borrow_mut().push(request.request_id.to_owned());
assert!(!request.tools.is_empty() && request.retention.is_some(), "the loop always sends its tools and asks for the cache");
self.answers.borrow_mut().pop_front().expect("the loop called the model past the script")
}
}
/// Two stub tools; each call is answered `ok` with the arguments echoed.
struct Stub {
ran: RefCell<Vec<String>>,
}
impl Stub {
fn new() -> Self {
Self { ran: RefCell::default() }
}
}
impl Executor for Stub {
fn definitions(&self) -> Vec<ToolDefinition> {
["alpha", "beta"].map(|name| ToolDefinition { name: name.into(), description: format!("the {name} stub"), parameters_json: "{\"type\":\"object\"}".into() }).to_vec()
}
fn run(&self, call: &ToolCall) -> Receipt {
self.ran.borrow_mut().push(call.name.clone());
Receipt::new(&call.name, Status::Ok, json!({ "arguments": call.arguments }))
}
}
#[derive(Default)]
struct Memory {
rows: RefCell<Vec<Value>>,
}
impl Ledger for Memory {
fn rows(&self) -> Result<Vec<Value>> {
Ok(self.rows.borrow().clone())
}
fn append(&self, row: Value) -> Result<()> {
self.rows.borrow_mut().push(row);
Ok(())
}
}
impl Memory {
fn kinds(&self, kind: &str) -> Vec<Value> {
self.rows.borrow().iter().filter(|row| row["agent"] == kind).cloned().collect()
}
}
struct Rig {
dir: tempfile::TempDir,
session: FileSession,
ledger: Memory,
stub: Stub,
clock: Cell<DateTime<Utc>>,
bounds: AgentTuning,
}
impl Rig {
fn new() -> Self {
let dir = tempfile::tempdir().unwrap();
let session = FileSession::new(dir.path().join("agent-session.cc"));
Self { dir, session, ledger: Memory::default(), stub: Stub::new(), clock: Cell::new(noon()), bounds: AgentTuning::default() }
}
fn wake(&self, model: &Script, id: &str, instructions: &str, input: &str) -> Turn {
let clock = || self.clock.get();
let executors: [&dyn Executor; 1] = [&self.stub];
let agent = Agent { model, session: &self.session, executors: &executors, ledger: &self.ledger, bounds: &self.bounds, clock: &clock };
step(&agent, &Wake { id, instructions, input }).unwrap()
}
fn run(&self, model: &Script, input: &str) -> Turn {
self.wake(model, "w1", "You act for her.", input)
}
fn discards(&self) -> Vec<String> {
self.ledger.kinds("session_discarded").iter().map(|row| row["why"].as_str().unwrap().to_owned()).collect()
}
}
#[test]
fn t_a1_loop_runs_tool_calls() {
let rig = Rig::new();
let model = Script::new(vec![asks("c1", "alpha", small()), asks("c2", "beta", small()), ends("Done.", small())]);
let turn = rig.run(&model, "She wants to know.");
assert_eq!(turn.ended, Ended::EndTurn);
assert_eq!((turn.model_calls, turn.tool_calls, turn.text.as_str()), (3, 2, "Done."));
assert_eq!(turn.receipts.iter().map(|receipt| (receipt.tool(), receipt.status())).collect::<Vec<_>>(), [("alpha", Status::Ok), ("beta", Status::Ok)]);
// Two receipts in her trace, and the ToolResults the model read are those receipts' JSON.
let rows = rig.ledger.kinds("receipt");
assert_eq!(rows.iter().map(|row| row["receipt"].clone()).collect::<Vec<_>>(), turn.receipts.iter().map(Receipt::json).collect::<Vec<_>>());
let results: Vec<(String, String)> = rig.session.load().unwrap().unwrap().items.into_iter().filter_map(|item| if let InputItem::ToolResult { call_id, output } = item { Some((call_id, output)) } else { None }).collect();
assert_eq!(results, [("c1".to_owned(), turn.receipts[0].json().to_string()), ("c2".to_owned(), turn.receipts[1].json().to_string())]);
// The model's third call saw both results, in order, after its own calls.
let third = &model.seen.borrow()[2];
assert!(matches!(third.as_slice(), [InputItem::UserText { .. }, InputItem::ToolCall { .. }, InputItem::ToolResult { .. }, InputItem::ToolCall { .. }, InputItem::ToolResult { .. }]));
assert_eq!(rig.ledger.kinds("call").len(), 3);
assert_eq!(*model.ids.borrow(), ["w1-m1", "w1-m2", "w1-m3"]);
}
#[test]
fn t_a1_an_unknown_tool_is_refused_not_run() {
let rig = Rig::new();
let model = Script::new(vec![asks("c1", "nope", small()), ends("Ok.", small())]);
let turn = rig.run(&model, "x");
assert_eq!((turn.receipts[0].status(), turn.receipts[0].tool()), (Status::Refused, "nope"));
assert!(rig.stub.ran.borrow().is_empty());
}
#[test]
fn t_a1_tool_cap() {
let rig = Rig::new();
let model = Script::endless("alpha", 10);
let turn = rig.run(&model, "x");
assert_eq!(turn.ended, Ended::Cap(Cap::ToolCalls));
assert_eq!(rig.stub.ran.borrow().len(), 8, "eight tool calls ran and no ninth");
assert_eq!(turn.model_calls, 9, "the ninth ask was answered with a cap, not run");
let statuses: Vec<Status> = turn.receipts.iter().map(Receipt::status).collect();
assert_eq!(statuses, [vec![Status::Ok; 8], vec![Status::Cap, Status::Cap]].concat(), "the refused ninth call and the loop's own cap receipt");
assert_eq!(turn.receipts.last().unwrap().tool(), "agent");
assert_eq!(turn.receipts.last().unwrap().fields()["cap"], "tool_calls");
// The session still holds a result for every call it holds.
assert!(stale(&rig.session.load().unwrap().unwrap(), &digest_of(MODEL, "You act for her.", &rig.stub.definitions()), noon(), &rig.bounds).is_none());
}
#[test]
fn t_a1_model_call_cap_and_wake_spend_cap() {
let mut rig = Rig::new();
rig.bounds.model_calls = 2;
let model = Script::endless("alpha", 5);
let turn = rig.run(&model, "x");
assert_eq!((turn.ended, turn.model_calls), (Ended::Cap(Cap::ModelCalls), 2));
assert_eq!(model.seen.borrow().len(), 2, "no third call");
let rig = Rig::new();
// 50k output tokens at $10 a million is $0.50: past the wake's $0.40 after one call.
let model = Script::new(vec![asks("c1", "alpha", usage(10, 50_000, 0, 0))]);
let turn = rig.run(&model, "x");
assert_eq!((turn.ended, turn.model_calls, turn.tool_calls), (Ended::Cap(Cap::WakeSpend), 1, 1));
assert!(turn.usd > 0.40);
assert_eq!(turn.receipts.last().unwrap().fields()["cap"], "wake_usd");
}
#[test]
fn t_a1_day_cap() {
let rig = Rig::new();
// 1.505M input tokens at $2 a million is $3.01, today.
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "usage": usage(1_505_000, 0, 0, 0) })).unwrap();
let model = Script::new(vec![]);
let turn = rig.run(&model, "x");
assert_eq!(turn.ended, Ended::Cap(Cap::DaySpend));
assert!(model.seen.borrow().is_empty(), "no call was made");
assert_eq!(turn.receipts[0].status(), Status::Cap);
assert_eq!(rig.ledger.kinds("receipt").len(), 1, "and the cap is recorded");
assert!(rig.session.load().unwrap().is_none(), "a capped wake leaves no session behind");
// Yesterday's spend and the same sum under the cap do not stop her.
let rig = Rig::new();
rig.ledger.append(json!({ "agent": "call", "at": (noon() - Duration::days(1)).to_rfc3339(), "usage": usage(5_000_000, 0, 0, 0) })).unwrap();
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "usage": usage(1_490_000, 0, 0, 0) })).unwrap();
let turn = rig.run(&Script::new(vec![ends("Fine.", small())]), "x");
assert_eq!(turn.ended, Ended::EndTurn);
// The sum rolls in what the wake itself spends: $2.99 behind her, then a call of about $0.04 reaches $3.03 and stops the next one.
let rig = Rig::new();
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "usage": usage(1_495_000, 0, 0, 0) })).unwrap();
let turn = rig.run(&Script::new(vec![asks("c1", "alpha", usage(20_000, 0, 0, 0))]), "x");
assert_eq!(turn.ended, Ended::Cap(Cap::DaySpend));
assert_eq!(turn.tool_calls, 1);
}
#[test]
fn t_a1_day_cap_survives_a_restart() {
let dir = tempfile::tempdir().unwrap();
let trace = FileTrace::new(dir.path().join("trace.cc"));
let session = FileSession::new(dir.path().join("agent-session.cc"));
let (bounds, stub) = (AgentTuning::default(), Stub::new());
let clock = noon;
let executors: [&dyn Executor; 1] = [&stub];
// One expensive wake: 400k output tokens at $10 a million is $4.00.
{
let ledger = TraceLedger::new(&trace, "w1");
let agent = Agent { model: &Script::new(vec![ends("Long.", usage(10, 400_000, 0, 0))]), session: &session, executors: &executors, ledger: &ledger, bounds: &bounds, clock: &clock };
assert_eq!(step(&agent, &Wake { id: "w1", instructions: "i", input: "x" }).unwrap().ended, Ended::EndTurn);
}
// A restart: nothing of the first run is held but her trace and the session file.
let trace = FileTrace::new(dir.path().join("trace.cc"));
let ledger = TraceLedger::new(&trace, "w2");
let model = Script::new(vec![]);
let agent = Agent { model: &model, session: &session, executors: &executors, ledger: &ledger, bounds: &bounds, clock: &clock };
let turn = step(&agent, &Wake { id: "w2", instructions: "i", input: "y" }).unwrap();
assert_eq!(turn.ended, Ended::Cap(Cap::DaySpend));
assert!(model.seen.borrow().is_empty());
// Her trace holds the call and the cap as agent rows, and `is_real` reads neither as a turn.
let records = trace.records().unwrap();
assert!(records.len() == 2 && records.iter().all(|record| record.get("agent").is_some() && !crate::projection::turn::is_real(record)), "{records:?}");
}
#[test]
fn t_a1_session_persists_while_warm() {
let rig = Rig::new();
rig.run(&Script::new(vec![ends("First.", usage(100, 5, 0, 4900))]), "one");
rig.clock.set(noon() + Duration::minutes(58));
let model = Script::new(vec![ends("Second.", usage(100, 5, 4900, 40))]);
rig.wake(&model, "w2", "You act for her.", "two");
assert_eq!(model.seen.borrow()[0], [InputItem::UserText { text: "one".into() }, InputItem::AssistantText { text: "First.".into() }, InputItem::UserText { text: "two".into() }]);
assert!(rig.discards().is_empty());
assert!(rig.session.load().unwrap().is_some());
}
#[test]
fn t_a1_session_ttl_discard() {
let rig = Rig::new();
rig.run(&Script::new(vec![ends("First.", usage(100, 5, 0, 4900))]), "one");
rig.clock.set(noon() + Duration::minutes(61));
let model = Script::new(vec![ends("Second.", usage(5000, 5, 0, 0))]);
rig.wake(&model, "w2", "You act for her.", "two");
assert_eq!(model.seen.borrow()[0], [InputItem::UserText { text: "two".into() }], "the input starts fresh");
assert_eq!(rig.discards(), ["ttl"]);
// The short retention's table is shorter: five minutes less a minute.
let mut rig = Rig::new();
rig.bounds.retention = CacheRetention::Short;
rig.run(&Script::new(vec![ends("First.", usage(100, 5, 0, 4900))]), "one");
rig.clock.set(noon() + Duration::seconds(250));
let model = Script::new(vec![ends("Second.", usage(5000, 5, 0, 0))]);
rig.wake(&model, "w2", "You act for her.", "two");
assert_eq!(model.seen.borrow()[0].len(), 1);
assert_eq!(rig.discards(), ["ttl"]);
}
#[test]
fn t_a1_cache_miss_discard() {
let rig = Rig::new();
rig.run(&Script::new(vec![ends("First.", usage(100, 5, 0, 4900))]), "one");
rig.clock.set(noon() + Duration::minutes(5));
// The cached prefix was 5,000 tokens; the provider read none of it.
let turn = rig.wake(&Script::new(vec![ends("Second.", usage(5000, 5, 0, 0))]), "w2", "You act for her.", "two");
assert_eq!(turn.ended, Ended::EndTurn, "the wake finishes on the session it had");
assert!(rig.session.load().unwrap().is_none(), "and the session is discarded at its end");
assert_eq!(rig.discards(), ["cache_miss"]);
// A read of some, or a prefix under the provider's minimum, is no miss.
let rig = Rig::new();
rig.run(&Script::new(vec![ends("First.", usage(100, 5, 0, 400))]), "one");
rig.wake(&Script::new(vec![ends("Second.", usage(500, 5, 0, 0))]), "w2", "You act for her.", "two");
assert!(rig.session.load().unwrap().is_some() && rig.discards().is_empty(), "500 tokens is under the minimum");
let rig = Rig::new();
rig.run(&Script::new(vec![ends("First.", usage(100, 5, 0, 4900))]), "one");
rig.wake(&Script::new(vec![ends("Second.", usage(100, 5, 4900, 0))]), "w2", "You act for her.", "two");
assert!(rig.session.load().unwrap().is_some() && rig.discards().is_empty());
}
#[test]
fn t_a1_a_miss_inside_a_wake_discards_at_its_end() {
let rig = Rig::new();
rig.run(&Script::new(vec![ends("First.", usage(100, 5, 0, 4900))]), "one");
// Second wake: the first call reads the cache, the second (after a tool) finds it gone.
let model = Script::new(vec![asks("c1", "alpha", usage(100, 5, 4900, 40)), ends("Done.", usage(5100, 5, 0, 0))]);
let turn = rig.wake(&model, "w2", "You act for her.", "two");
assert_eq!((turn.ended, turn.tool_calls), (Ended::EndTurn, 1));
assert_eq!(rig.discards(), ["cache_miss"]);
}
#[test]
fn t_a1_orphan_tool_call_discard() {
let rig = Rig::new();
let tools = rig.stub.definitions();
let held = Session { items: vec![InputItem::UserText { text: "old".into() }, InputItem::ToolCall { call_id: "c9".into(), name: "alpha".into(), arguments: "{}".into() }], digest: digest_of(MODEL, "You act for her.", &tools), retention: CacheRetention::Long, created_at: noon(), last_call_at: noon(), last_usage: None };
rig.session.save(&held).unwrap();
let model = Script::new(vec![ends("Ok.", small())]);
rig.run(&model, "new");
assert_eq!(model.seen.borrow()[0], [InputItem::UserText { text: "new".into() }]);
assert_eq!(rig.discards(), ["orphan_tool_call"]);
// The same session with its result is kept.
let mut whole = held.clone();
whole.items.push(InputItem::ToolResult { call_id: "c9".into(), output: "{}".into() });
rig.session.save(&whole).unwrap();
let model = Script::new(vec![ends("Ok.", small())]);
rig.wake(&model, "w2", "You act for her.", "newer");
assert_eq!(model.seen.borrow()[0].len(), 4);
}
#[test]
fn t_a1_a_changed_agent_or_a_grown_prompt_discards() {
let rig = Rig::new();
rig.run(&Script::new(vec![ends("First.", small())]), "one");
let model = Script::new(vec![ends("Second.", small())]);
rig.wake(&model, "w2", "A different agent.", "two");
assert_eq!((model.seen.borrow()[0].len(), rig.discards()), (1, vec!["digest".to_owned()]));
let mut rig = Rig::new();
rig.bounds.max_session_tokens = 1000;
rig.run(&Script::new(vec![ends("First.", usage(900, 5, 0, 200))]), "one");
rig.wake(&Script::new(vec![ends("Second.", small())]), "w2", "You act for her.", "two");
assert_eq!(rig.discards(), ["too_long"]);
}
#[test]
fn t_a1_an_unreadable_session_is_discarded_not_fatal() {
let rig = Rig::new();
std::fs::write(rig.dir.path().join("agent-session.cc"), b"not a store").unwrap();
let model = Script::new(vec![ends("Ok.", small())]);
assert_eq!(rig.run(&model, "x").ended, Ended::EndTurn);
assert_eq!(rig.discards(), ["unreadable"]);
}
#[test]
fn t_a1_a_failed_call_keeps_its_outage_and_its_cost() {
let rig = Rig::new();
let cut = Failed { reason: "the provider failed the call: RateLimited".into(), outage: true, usage: Some(usage(1000, 0, 0, 0)) };
let turn = rig.run(&Script::new(vec![Err(cut.clone())]), "x");
assert_eq!(turn.ended, Ended::Failed(cut));
assert!((turn.usd - 0.002).abs() < 1e-9);
let calls = rig.ledger.kinds("call");
assert_eq!((calls.len(), calls[0]["failed"].as_str()), (1, Some("the provider failed the call: RateLimited")));
assert!(rig.session.load().unwrap().is_none(), "a call that never came back left nothing to keep");
// A retry of the same wake sends the input once.
let model = Script::new(vec![ends("Ok.", small())]);
rig.run(&model, "x");
assert_eq!(model.seen.borrow()[0].len(), 1);
}
#[test]
fn t_a1_a_stop_the_loop_cannot_continue_from_is_a_failure_that_discards() {
let rig = Rig::new();
let mut cut = ends("Half a", small()).unwrap();
cut.stop = StopReason::MaxOutputTokens;
let turn = rig.run(&Script::new(vec![Ok(cut)]), "x");
assert!(matches!(&turn.ended, Ended::Failed(failed) if failed.reason.contains("MaxOutputTokens") && !failed.outage), "{:?}", turn.ended);
assert!(rig.session.load().unwrap().is_none());
}
#[test]
fn t_a1_receipt_status_required() {
// The type check is the compile_fail example on `Receipt`; here, every status reads back in the receipt a model is shown.
for status in [Status::Ok, Status::Refused, Status::Error, Status::Unknown, Status::NotSent, Status::Cap] {
let json = Receipt::new("say", status, json!({ "room": "swarm" })).json();
assert!(json["status"].is_string() && json["tool"] == "say" && json["fields"]["room"] == "swarm", "{json}");
}
assert_eq!(Receipt::new("say", Status::NotSent, json!({})).json()["status"], "not_sent");
assert_eq!(Receipt::new("say", Status::Ok, json!("text")).fields()["detail"], "text");
}
#[test]
fn two_executors_may_not_define_one_tool() {
let rig = Rig::new();
let (first, second) = (Stub::new(), Stub::new());
let executors: [&dyn Executor; 2] = [&first, &second];
let clock = || noon();
let model = Script::new(vec![]);
let agent = Agent { model: &model, session: &rig.session, executors: &executors, ledger: &rig.ledger, bounds: &rig.bounds, clock: &clock };
assert!(step(&agent, &Wake { id: "w", instructions: "i", input: "x" }).is_err());
assert!(step(&Agent { executors: &[&first], ..agent }, &Wake { id: "w", instructions: "i", input: " " }).is_err());
}
#[test]
fn her_agent_is_named_and_carries_no_persona_of_its_own() {
let text = instructions("Eureka");
assert!(text.starts_with("You act for Eureka.") && text.contains("her own words where her prose gave them"));
}

View file

@ -718,6 +718,27 @@ fn tuning_absent_is_the_defaults_and_a_file_overrides_and_an_unknown_key_refuses
assert!(format!("{:#}", tuning::load(&path).unwrap_err()).contains("temprature"), "a mistyped knob refuses the file");
}
#[test]
fn the_agent_bounds_are_the_maps_and_a_file_prices_another_model() {
let defaults = Tuning::default().agent;
assert_eq!((defaults.tool_calls, defaults.model_calls, defaults.wake_usd, defaults.day_usd, defaults.ttl_s.short, defaults.ttl_s.long), (8, 10, 0.40, 3.00, 300, 3600));
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join(TUNING_FILE);
std::fs::write(&path, "[agent]
model = \"claude-opus-5-5\"
retention = \"short\"
[agent.prices.claude-opus-5-5]
input = 5.0
output = 25.0
cache_read = 0.5
cache_write = 10.0
").unwrap();
let agent = tuning::load(&path).unwrap().tuning.agent;
assert_eq!((agent.model.as_str(), agent.retention, agent.prices["claude-opus-5-5"].output), ("claude-opus-5-5", model_connector::CacheRetention::Short, 25.0));
assert_eq!(agent.tool_calls, 8, "an unnamed knob keeps its default");
}
#[test]
fn the_hash_is_of_the_effective_tuning() {
let dir = tempfile::tempdir().unwrap();

View file

@ -12,6 +12,7 @@ use std::collections::BTreeMap;
use std::path::Path;
use anyhow::{Context, Result, bail};
use model_connector::CacheRetention;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
@ -58,6 +59,7 @@ pub struct Tuning {
pub projector: ProjectorTuning,
pub persona: PersonaTuning,
pub interpreter: InterpreterTuning,
pub agent: AgentTuning,
pub select: SelectTuning,
pub lens: LensWeights,
/// Each person's pronouns by Matrix id, for everyone the packet names: the persona schema has no pronoun field for
@ -86,6 +88,7 @@ impl Default for Tuning {
projector: ProjectorTuning::default(),
persona: PersonaTuning::default(),
interpreter: InterpreterTuning::default(),
agent: AgentTuning::default(),
select: SelectTuning::default(),
lens: LensWeights::default(),
pronouns: PRONOUNS.iter().map(|(id, pronouns)| ((*id).to_owned(), (*pronouns).to_owned())).collect(),
@ -114,6 +117,125 @@ pub struct PersonaTuning {
pub words: usize,
}
/// Her agent's turn (map 16.38.6, 16.38.10): the model, the bounds that are enforced in code (`agent::step`), the price table
/// they are priced by, and when her session's cache is taken to be cold. Prices are USD per million tokens.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct AgentTuning {
pub model: String,
/// The most tool calls a wake runs, and the most model calls it makes.
pub tool_calls: usize,
pub model_calls: usize,
/// The most a wake may spend, and the most a Mind may spend in a UTC day, summed from her trace.
pub wake_usd: f64,
pub day_usd: f64,
/// The prompt size past which her session is discarded and re-seeded.
pub max_session_tokens: u64,
/// The cache the session's prefix asks for.
pub retention: CacheRetention,
/// How long each retention keeps a cache, in seconds, from the provider's table.
pub ttl_s: CacheTtl,
/// The provider's least cacheable prefix, in tokens: below it a read of 0 says nothing.
pub cache_min_tokens: u64,
pub prices: BTreeMap<String, Price>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct CacheTtl {
pub short: u64,
pub long: u64,
}
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Price {
pub input: f64,
pub output: f64,
pub cache_read: f64,
pub cache_write: f64,
}
impl Default for CacheTtl {
fn default() -> Self {
Self { short: 300, long: 3600 }
}
}
impl Default for AgentTuning {
fn default() -> Self {
// Sonnet-class at the map's prices; a cache write is priced at the one-hour rate whatever the retention, so a cap errs high.
let sonnet = Price { input: 2.0, output: 10.0, cache_read: 0.2, cache_write: 4.0 };
Self {
model: "claude-sonnet-5-5".into(),
tool_calls: 8,
model_calls: 10,
wake_usd: 0.40,
day_usd: 3.00,
max_session_tokens: 80_000,
retention: CacheRetention::Long,
ttl_s: CacheTtl::default(),
cache_min_tokens: 2048,
prices: BTreeMap::from([("claude-sonnet-5-5".to_owned(), sonnet)]),
}
}
}
impl AgentTuning {
/// The price of `model`'s tokens, USD per call: the table's entry, or the dearest entry when the model is not listed.
pub(crate) fn price(&self, model: &str) -> Price {
self.prices.get(model).copied().unwrap_or_else(|| {
self.prices.values().copied().fold(Price { input: 0.0, output: 0.0, cache_read: 0.0, cache_write: 0.0 }, |a, b| Price { input: a.input.max(b.input), output: a.output.max(b.output), cache_read: a.cache_read.max(b.cache_read), cache_write: a.cache_write.max(b.cache_write) })
})
}
/// How long a cache of `retention` lives, in seconds.
pub(crate) fn ttl(&self, retention: CacheRetention) -> u64 {
match retention {
CacheRetention::Short => self.ttl_s.short,
CacheRetention::Long => self.ttl_s.long,
}
}
fn validate(&self) -> Result<()> {
if self.model.trim().is_empty() {
bail!("agent.model must name a model");
}
if !self.prices.contains_key(&self.model) {
bail!("agent.prices has no entry for agent.model {}: a cap cannot be priced without one", self.model);
}
for (model, price) in &self.prices {
if ![price.input, price.output, price.cache_read, price.cache_write].iter().all(|usd| usd.is_finite() && *usd >= 0.0) {
bail!("agent.prices.{model} must be finite and not negative");
}
}
if !(1..=AGENT_CALLS_MAX).contains(&self.tool_calls) || !(1..=AGENT_CALLS_MAX).contains(&self.model_calls) {
bail!("agent.tool_calls and agent.model_calls must be from 1 to {AGENT_CALLS_MAX}");
}
let usd = |name: &str, value: f64, most: f64| if value.is_finite() && value > 0.0 && value <= most { Ok(()) } else { Err(anyhow::anyhow!("{name} must be above 0 and at most {most}, not {value}")) };
usd("agent.wake_usd", self.wake_usd, AGENT_WAKE_USD_MAX)?;
usd("agent.day_usd", self.day_usd, AGENT_DAY_USD_MAX)?;
if self.wake_usd > self.day_usd {
bail!("agent.wake_usd must be at most agent.day_usd");
}
if self.max_session_tokens == 0 || self.cache_min_tokens == 0 {
bail!("agent.max_session_tokens and agent.cache_min_tokens must be above 0");
}
if self.ttl_s.short <= CACHE_MARGIN_S || self.ttl_s.long <= CACHE_MARGIN_S {
bail!("agent.ttl_s must be above {CACHE_MARGIN_S} seconds: a session is discarded that long before its cache ends");
}
Ok(())
}
}
/// A session is discarded this long before its cache is due to end: a call that starts inside it may not finish inside the cache.
pub(crate) const CACHE_MARGIN_S: u64 = 60;
/// The most calls of either kind a wake may be tuned to, and the most it and a day may be tuned to spend: a mistyped bound fails
/// the file, never the budget.
const AGENT_CALLS_MAX: usize = 32;
const AGENT_WAKE_USD_MAX: f64 = 5.0;
const AGENT_DAY_USD_MAX: f64 = 50.0;
/// The selection: its temperature and inclusion, its budgets, its half-life, the freshness decay and the pool caps.
///
/// The `*_bytes` of the identity, a bond, an item and each section are guards, not focus controls (map 16.8): a seed
@ -290,6 +412,7 @@ impl Tuning {
if self.persona.model.trim().is_empty() {
bail!("persona.model must name a model");
}
self.agent.validate()?;
if !ADDRESSED_RANGE.contains(&select.addressed_bytes) {
bail!("select.addressed_bytes must be from {} to {}, not {}", ADDRESSED_RANGE.start(), ADDRESSED_RANGE.end(), select.addressed_bytes);
}

View file

@ -52,10 +52,10 @@ pub(crate) struct Past {
pub last_wake: Option<DateTime<Utc>>,
}
/// A real turn: a record that decided something. A failed turn decided nothing, and a record that only set lines aside is no turn. The one
/// A real turn: a record that decided something. A failed turn decided nothing, a record that only set lines aside is no turn, and a row of her agent's (`agent`) is a call, a receipt or a discard, never a turn. The one
/// definition, for what she is told of her last turn (`history`) and for what her trace holds untold (`untold`).
pub(crate) fn is_real(record: &Value) -> bool {
record.get("failed").is_none() && record.get("set_aside").is_none()
record.get("failed").is_none() && record.get("set_aside").is_none() && record.get("agent").is_none()
}
/// What her trace holds that she has not been told, from whichever record holds it: each line set aside, each put refused and a failed

View file

@ -254,6 +254,7 @@ mind_body::projection: impl HuginnPersonaSource
mind_body::projection: impl HuginnPersonaSource: fn new (client : HuginnClient) -> Self
mind_body::projection: impl PersonaSource for HuginnPersonaSource
mind_body::projection: impl< T : Chat > MouthReader for T
mind_body::projection: mod agent
mind_body::projection: mod harness
mind_body::projection: pub trait MouthReader { fn pending (& self) -> Result < ChatPending > ; }
mind_body::projection: pub trait PersonaSource { fn persona (& self) -> Result < (Value , String) > ; }
@ -266,6 +267,38 @@ mind_body::projection: pub use tuning :: { TUNING_FILE , TUNING_ROOT } ;
mind_body::projection: struct HuginnPersonaSource pub-fields[]
mind_body::projection: struct Organs< 'a > pub-fields[persona: Option < & 'a dyn PersonaSource >, chat: Option < & 'a dyn MouthReader >, addressing: Option < & 'a dyn HeartbeatView >, model: Option < & 'a dyn Model >, domain: Option < & 'a dyn DomainSource >, reads: Option < & 'a dyn ReadSource >]
mind_body::projection: struct Request # [derive (Clone)] pub-fields[instance: String, kind: TurnKind, state: Option < Value >, rooms: Vec < String >, seed: u64, renders: Option < usize >, judge_against: Option < Value >, operators: Vec < String >, minds: Vec < String >, own_sender: String, tuning: PathBuf, through: Through, last_heard: Vec < (String , u64) >, recent: Vec < Vec < String > >, own_rooms: Vec < String >, woken_for: Vec < String >, last_outcome: Option < Value >, last_wake: Option < DateTime < Utc > >, records: Vec < Value >]
mind_body::projection::agent: # [derive (Clone , Copy , Debug , PartialEq , Eq , Serialize)] # [serde (rename_all = "snake_case")] pub enum Status { Ok , Refused , Error , Unknown , NotSent , Cap , }
mind_body::projection::agent: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum Cap { ToolCalls , ModelCalls , WakeSpend , DaySpend , }
mind_body::projection::agent: # [derive (Clone , Debug , PartialEq , Eq)] pub enum Ended { EndTurn , Cap (Cap) , Failed (Failed) , }
mind_body::projection::agent: fn instructions (name : & str) -> String
mind_body::projection::agent: fn step (agent : & Agent < '_ > , wake : & Wake < '_ >) -> Result < Turn >
mind_body::projection::agent: impl Cap
mind_body::projection::agent: impl FileSession
mind_body::projection::agent: impl FileSession: fn discard (& self) -> Result < () >
mind_body::projection::agent: impl FileSession: fn load (& self) -> Result < Option < Session > >
mind_body::projection::agent: impl FileSession: fn new (path : impl Into < PathBuf >) -> Self
mind_body::projection::agent: impl FileSession: fn save (& self , session : & Session) -> Result < () >
mind_body::projection::agent: impl Ledger for TraceLedger < '_ >
mind_body::projection::agent: impl Receipt
mind_body::projection::agent: impl Receipt: fn fields (& self) -> & Map < String , Value >
mind_body::projection::agent: impl Receipt: fn json (& self) -> Value
mind_body::projection::agent: impl Receipt: fn new (tool : impl Into < String > , status : Status , fields : Value) -> Self
mind_body::projection::agent: impl Receipt: fn status (& self) -> Status
mind_body::projection::agent: impl Receipt: fn tool (& self) -> & str
mind_body::projection::agent: impl Run < '_ >
mind_body::projection::agent: impl Steps for KitModel
mind_body::projection::agent: impl TraceLedger < 'a >: fn new (trace : & 'a dyn Trace , stem : impl Into < String >) -> Self
mind_body::projection::agent: impl< 'a > TraceLedger < 'a >
mind_body::projection::agent: pub trait Executor { fn definitions (& self) -> Vec < ToolDefinition > ; fn run (& self , call : & ToolCall) -> Receipt ; }
mind_body::projection::agent: pub trait Ledger { fn rows (& self) -> Result < Vec < Value > > ; fn append (& self , row : Value) -> Result < () > ; }
mind_body::projection::agent: pub trait Steps { fn step (& self , request : StepRequest < '_ >) -> std :: result :: Result < Stepped , Failed > ; }
mind_body::projection::agent: struct Agent< 'a > pub-fields[model: & 'a dyn Steps, session: & 'a FileSession, executors: & 'a [& 'a dyn Executor], ledger: & 'a dyn Ledger, bounds: & 'a AgentTuning, clock: & 'a dyn Fn () -> DateTime < Utc >]
mind_body::projection::agent: struct FileSession pub-fields[]
mind_body::projection::agent: struct Receipt # [derive (Clone , Debug , PartialEq)] pub-fields[]
mind_body::projection::agent: struct Session # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[items: Vec < InputItem >, digest: String, retention: CacheRetention, created_at: DateTime < Utc >, last_call_at: DateTime < Utc >, last_usage: Option < Spent >]
mind_body::projection::agent: struct TraceLedger< 'a > pub-fields[]
mind_body::projection::agent: struct Turn # [derive (Clone , Debug , PartialEq)] pub-fields[ended: Ended, text: String, receipts: Vec < Receipt >, model_calls: usize, tool_calls: usize, usd: f64]
mind_body::projection::agent: struct Wake< 'a > pub-fields[id: & 'a str, instructions: & 'a str, input: & 'a str]
mind_body::projection::domain: impl DomainSource for DomainFacts
mind_body::projection::domain: impl DomainSource for MindDomain
mind_body::projection::domain: impl ForgeGet for HttpForge
@ -350,6 +383,9 @@ mind_body::projection::simulate: impl ReadSource for CastReads < '_ >
mind_body::projection::tuning: const TUNING_FILE : & str
mind_body::projection::tuning: const TUNING_ROOT : & str
mind_body::projection::tuning: fn load (path : & Path) -> Result < Loaded >
mind_body::projection::tuning: impl AgentTuning
mind_body::projection::tuning: impl Default for AgentTuning
mind_body::projection::tuning: impl Default for CacheTtl
mind_body::projection::tuning: impl Default for InterpreterTuning
mind_body::projection::tuning: impl Default for LensWeights
mind_body::projection::tuning: impl Default for PersonaTuning
@ -358,11 +394,14 @@ mind_body::projection::tuning: impl Default for ProjectorTuning
mind_body::projection::tuning: impl Default for SelectTuning
mind_body::projection::tuning: impl Default for Tuning
mind_body::projection::tuning: impl Tuning
mind_body::projection::tuning: struct AgentTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[model: String, tool_calls: usize, model_calls: usize, wake_usd: f64, day_usd: f64, max_session_tokens: u64, retention: CacheRetention, ttl_s: CacheTtl, cache_min_tokens: u64, prices: BTreeMap < String , Price >]
mind_body::projection::tuning: struct CacheTtl # [derive (Clone , Copy , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[short: u64, long: u64]
mind_body::projection::tuning: struct InterpreterTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[model: String, guidance: String, reads_per_wake: usize, read_bytes: usize, wake_read_bytes: usize]
mind_body::projection::tuning: struct LensWeights # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[body_and_hour: f64, person_present: f64, unresolved_want: f64, memory_surfacing: f64, wondering: f64]
mind_body::projection::tuning: struct Loaded # [derive (Clone , Debug , PartialEq , Serialize)] pub-fields[tuning: Tuning, source: & 'static str, sha256: String]
mind_body::projection::tuning: struct PersonaTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[model: String, guidance: String, words: usize]
mind_body::projection::tuning: struct PoolCaps # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[memories_about_present: usize, other_memories: usize, needs: usize, incubation: usize, stance: usize, value: usize]
mind_body::projection::tuning: struct Price # [derive (Clone , Copy , Debug , PartialEq , Serialize , Deserialize)] pub-fields[input: f64, output: f64, cache_read: f64, cache_write: f64]
mind_body::projection::tuning: struct ProjectorTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[model: String, guidance: String, words: usize, beat_words: usize]
mind_body::projection::tuning: struct SelectTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[temperature: f64, inclusion_score: f64, notes_bytes: usize, here_bytes: usize, outcome_bytes: usize, domain_bytes: usize, exchange_bytes: usize, stimulus_bytes: usize, heard_bytes: usize, addressed_bytes: usize, identity_bytes: usize, bond_summary_bytes: usize, item_bytes: usize, body_bytes: usize, freshness_base: f64, freshness_window: usize, people_full: usize, beat_tail_lines: usize, group_state: bool, group_lines: usize, group_bytes: usize, caps: PoolCaps]
mind_body::projection::tuning: struct Tuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[projector: ProjectorTuning, persona: PersonaTuning, interpreter: InterpreterTuning, select: SelectTuning, lens: LensWeights, pronouns: BTreeMap < String , String >]