agent: the day cap fails closed; cache prices follow the pricing page; the session's edges are pinned
A call row is written to her trace before the call is made, holding its place in the day at the wake cap; a settle row after it names the usage and prices it. A trace that cannot be read or cannot take the call row makes no call; a settle row that cannot be written ends the wake with no further call and the call still at the worst case; a failed call that reports no usage is charged the worst case. A row whose time or usage does not read counts against the day. Every ledger fault is the turn's Failed (outage), never an Err. Price carries the 5-minute and 1-hour cache write rates; Sonnet 5.5 is $0.10 a cache hit, $2.50 and $4 a write. The compile_fail doctests name every field so privacy is all they can fail on. Tests pin the digest's model and tool parameters, the mid-wake cold update, cache_min_tokens, ttl, too_long and the wake and day caps at equality, created_at, every priced term, the agent tuning's bounds, the plain ask over a kit, and the session store's discard. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
9d18d84604
commit
ad5e9ed13b
5 changed files with 481 additions and 78 deletions
|
|
@ -11,7 +11,14 @@
|
|||
//! 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.
|
||||
//!
|
||||
//! The day's sum fails closed. A `call` row is written before its call is made, holding the call's place in the day at the
|
||||
//! worst case (`unmetered_usd`, the wake's cap); a `settle` row after it names the usage, and the call is priced by that
|
||||
//! instead. So a trace that cannot be read, or cannot take the `call` row, makes no call; a `settle` row that cannot be
|
||||
//! written ends the wake with its call still at the worst case; and a call whose usage is not known, a failed one that
|
||||
//! reports none included, is charged the worst case and never nothing.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::{Result, bail};
|
||||
|
|
@ -56,10 +63,32 @@ pub enum Status {
|
|||
}
|
||||
|
||||
/// 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:
|
||||
/// fields are private, so a receipt is built by `new` or not at all. Each example below is complete, so that privacy is the one
|
||||
/// thing it can fail on: a literal that names every field, a read of a field and a write to one.
|
||||
///
|
||||
/// ```compile_fail
|
||||
/// let _ = mind_body::projection::agent::Receipt { tool: "say".into(), fields: Default::default() };
|
||||
/// use mind_body::projection::agent::{Receipt, Status};
|
||||
/// let _ = Receipt { tool: "say".into(), status: Status::Ok, fields: Default::default() };
|
||||
/// ```
|
||||
///
|
||||
/// ```compile_fail
|
||||
/// use mind_body::projection::agent::{Receipt, Status};
|
||||
/// let receipt = Receipt::new("say", Status::Ok, serde_json::json!({}));
|
||||
/// let _ = receipt.status;
|
||||
/// ```
|
||||
///
|
||||
/// ```compile_fail
|
||||
/// use mind_body::projection::agent::{Receipt, Status};
|
||||
/// let mut receipt = Receipt::new("say", Status::Ok, serde_json::json!({}));
|
||||
/// receipt.status = Status::Refused;
|
||||
/// ```
|
||||
///
|
||||
/// The same lines compile once they go through the methods:
|
||||
///
|
||||
/// ```
|
||||
/// use mind_body::projection::agent::{Receipt, Status};
|
||||
/// let receipt = Receipt::new("say", Status::Ok, serde_json::json!({}));
|
||||
/// assert_eq!((receipt.tool(), receipt.status()), ("say", Status::Ok));
|
||||
/// ```
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Receipt {
|
||||
|
|
@ -273,7 +302,8 @@ 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`.
|
||||
/// caller (two executors defining one tool, an empty input) is an `Err`; everything the world does, her own trace
|
||||
/// failing included, 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");
|
||||
|
|
@ -289,20 +319,26 @@ pub fn step(agent: &Agent<'_>, wake: &Wake<'_>) -> Result<Turn> {
|
|||
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 digest = digest_of(&agent.bounds.model, wake.instructions, &tools);
|
||||
let mut run = Run { agent, wake, receipts: Vec::new(), usd: 0.0, model_calls: 0, tool_calls: 0, text: String::new() };
|
||||
let ended = drive(&mut run, &tools, &owners, &digest).unwrap_or_else(Ended::Failed);
|
||||
Ok(run.turn(ended))
|
||||
}
|
||||
|
||||
/// The loop. A fault in her own trace or session store is an `Err` from anywhere in it, and ends the turn: no call is made
|
||||
/// that her trace has not first been able to record (the `call` row written before it).
|
||||
fn drive(run: &mut Run<'_>, tools: &[ToolDefinition], owners: &[(String, usize)], digest: &str) -> std::result::Result<Ended, Failed> {
|
||||
let (agent, wake) = (run.agent, run.wake);
|
||||
let bounds = agent.bounds;
|
||||
let now = (agent.clock)();
|
||||
let day_before = day_usd(&agent.ledger.rows()?, now, bounds);
|
||||
let day_before = day_usd(&agent.ledger.rows().map_err(|fault| ledger_failed(&fault))?, now, bounds);
|
||||
if day_before >= bounds.day_usd {
|
||||
let ended = run.cap(Cap::DaySpend, day_before)?;
|
||||
return Ok(run.turn(ended, String::new()));
|
||||
return run.cap(Cap::DaySpend, day_before);
|
||||
}
|
||||
|
||||
// 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) {
|
||||
Ok(Some(held)) => match stale(&held, digest, now, bounds) {
|
||||
Some(why) => {
|
||||
run.discard(why)?;
|
||||
None
|
||||
|
|
@ -323,7 +359,6 @@ pub fn step(agent: &Agent<'_>, wake: &Wake<'_>) -> Result<Turn> {
|
|||
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 {
|
||||
|
|
@ -336,28 +371,24 @@ pub fn step(agent: &Agent<'_>, wake: &Wake<'_>) -> Result<Turn> {
|
|||
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 });
|
||||
// The row comes first: it holds the call's place in the day's spend at the worst case, and a trace that cannot take it is a call not made.
|
||||
run.record(json!({ "agent": "call", "at": (agent.clock)().to_rfc3339(), "wake": wake.id, "call": request_id, "model": bounds.model }))?;
|
||||
let answer = agent.model.step(StepRequest { request_id: &request_id, conversation_id: &conversation, model: &bounds.model, instructions: wake.instructions, 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);
|
||||
// A failure that reports no usage is charged at the worst case, never at nothing.
|
||||
let usd = failed.usage.as_ref().map_or_else(|| unmetered_usd(bounds), |usage| price(bounds, usage));
|
||||
run.usd += usd;
|
||||
run.record(json!({ "agent": "settle", "at": (agent.clock)().to_rfc3339(), "wake": wake.id, "call": request_id, "usage": failed.usage, "usd": usd, "failed": failed.reason }))?;
|
||||
return Ok(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));
|
||||
}
|
||||
run.record(json!({ "agent": "settle", "at": at.to_rfc3339(), "wake": wake.id, "call": request_id, "usage": stepped.usage, "usd": cost, "stop": format!("{:?}", stepped.stop) }))?;
|
||||
// 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;
|
||||
|
|
@ -366,23 +397,20 @@ pub fn step(agent: &Agent<'_>, wake: &Wake<'_>) -> Result<Turn> {
|
|||
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));
|
||||
run.text.clone_from(&stepped.text);
|
||||
}
|
||||
let held = |items: &[InputItem]| Session { items: items.to_vec(), digest: digest.to_owned(), retention: bounds.retention, created_at, last_call_at: at, last_usage: last_usage.clone() };
|
||||
agent.session.save(&held(&items)).map_err(|fault| 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 });
|
||||
return Ok(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;
|
||||
|
|
@ -394,20 +422,11 @@ pub fn step(agent: &Agent<'_>, wake: &Wake<'_>) -> Result<Turn> {
|
|||
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;
|
||||
}
|
||||
// A receipt that cannot be written ends the turn with its call lacking a result in the session: the next start discards it.
|
||||
run.receipt(receipt.clone())?;
|
||||
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));
|
||||
}
|
||||
agent.session.save(&held(&items)).map_err(|fault| ledger_failed(&fault))?;
|
||||
if over {
|
||||
break run.cap(Cap::ToolCalls, bounds.tool_calls as f64)?;
|
||||
}
|
||||
|
|
@ -415,7 +434,7 @@ pub fn step(agent: &Agent<'_>, wake: &Wake<'_>) -> Result<Turn> {
|
|||
if cold {
|
||||
run.discard("cache_miss")?;
|
||||
}
|
||||
Ok(run.turn(ended, text))
|
||||
Ok(ended)
|
||||
}
|
||||
|
||||
/// The loop's running account: what the turn has earned and spent so far.
|
||||
|
|
@ -426,31 +445,36 @@ struct Run<'a> {
|
|||
usd: f64,
|
||||
model_calls: usize,
|
||||
tool_calls: usize,
|
||||
text: String,
|
||||
}
|
||||
|
||||
impl Run<'_> {
|
||||
/// One row in her trace; a trace that cannot take it is the turn's failure.
|
||||
fn record(&self, row: Value) -> std::result::Result<(), Failed> {
|
||||
self.agent.ledger.append(row).map_err(|fault| ledger_failed(&fault))
|
||||
}
|
||||
|
||||
/// 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)?;
|
||||
fn receipt(&mut self, receipt: Receipt) -> std::result::Result<(), Failed> {
|
||||
self.record(json!({ "agent": "receipt", "at": (self.agent.clock)().to_rfc3339(), "wake": self.wake.id, "receipt": receipt.json() }))?;
|
||||
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> {
|
||||
fn cap(&mut self, cap: Cap, reached: f64) -> std::result::Result<Ended, Failed> {
|
||||
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 discard(&mut self, why: &str) -> std::result::Result<(), Failed> {
|
||||
self.agent.session.discard().map_err(|fault| ledger_failed(&fault))?;
|
||||
self.record(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 turn(self, ended: Ended) -> Turn {
|
||||
Turn { ended, text: self.text, receipts: self.receipts, model_calls: self.model_calls, tool_calls: self.tool_calls, usd: self.usd }
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -464,20 +488,31 @@ 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.
|
||||
/// What `usage` costs, USD, by the tuning's table; cache writes at the rate of the retention the session asks for.
|
||||
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
|
||||
(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(bounds.retention)) / million
|
||||
}
|
||||
|
||||
/// The UTC day's spend so far, from the `call` rows of her trace dated `now`'s day.
|
||||
/// What a call costs that no usage is known for: the most a wake may spend, the dearest a call can be taken to cost. Every
|
||||
/// price that cannot be read from her trace is this, so a trace that fails never lowers the day's sum.
|
||||
fn unmetered_usd(bounds: &AgentTuning) -> f64 {
|
||||
bounds.wake_usd
|
||||
}
|
||||
|
||||
/// The UTC day's spend so far, from the `call` rows of her trace dated `now`'s day. A call row is priced by its own usage, or by
|
||||
/// the `settle` row that answers it; a call with neither, or with a usage that does not read, is `unmetered_usd`. A row whose
|
||||
/// time does not read counts as today's.
|
||||
fn day_usd(rows: &[Value], now: DateTime<Utc>, bounds: &AgentTuning) -> f64 {
|
||||
let settled: BTreeMap<&str, &Value> = rows.iter().filter(|row| row["agent"] == "settle").filter_map(|row| Some((row["call"].as_str()?, row))).collect();
|
||||
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))
|
||||
.filter(|row| row["at"].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok()).is_none_or(|at| at.with_timezone(&Utc).date_naive() == now.date_naive()))
|
||||
.map(|row| {
|
||||
let usage = if row.get("usage").is_some() { &row["usage"] } else { row["call"].as_str().and_then(|id| settled.get(id)).map_or(&Value::Null, |settle| &settle["usage"]) };
|
||||
serde_json::from_value::<Spent>(usage.clone()).map_or_else(|_| unmetered_usd(bounds), |usage| price(bounds, &usage))
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -34,11 +34,12 @@ struct Script {
|
|||
answers: RefCell<VecDeque<std::result::Result<Stepped, Failed>>>,
|
||||
seen: RefCell<Vec<Vec<InputItem>>>,
|
||||
ids: RefCell<Vec<String>>,
|
||||
conversations: 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() }
|
||||
Self { answers: RefCell::new(answers.into()), seen: RefCell::default(), ids: RefCell::default(), conversations: RefCell::default() }
|
||||
}
|
||||
|
||||
/// A model that asks `tool` on every call, whatever it is told.
|
||||
|
|
@ -51,6 +52,7 @@ 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());
|
||||
self.conversations.borrow_mut().push(request.conversation_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")
|
||||
}
|
||||
|
|
@ -59,17 +61,19 @@ impl Steps for Script {
|
|||
/// Two stub tools; each call is answered `ok` with the arguments echoed.
|
||||
struct Stub {
|
||||
ran: RefCell<Vec<String>>,
|
||||
parameters: RefCell<String>,
|
||||
description: RefCell<String>,
|
||||
}
|
||||
|
||||
impl Stub {
|
||||
fn new() -> Self {
|
||||
Self { ran: RefCell::default() }
|
||||
Self { ran: RefCell::default(), parameters: RefCell::new("{\"type\":\"object\"}".into()), description: RefCell::new("stub".into()) }
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
["alpha", "beta"].map(|name| ToolDefinition { name: name.into(), description: format!("the {name} {}", self.description.borrow()), parameters_json: self.parameters.borrow().clone() }).to_vec()
|
||||
}
|
||||
|
||||
fn run(&self, call: &ToolCall) -> Receipt {
|
||||
|
|
@ -81,14 +85,23 @@ impl Executor for Stub {
|
|||
#[derive(Default)]
|
||||
struct Memory {
|
||||
rows: RefCell<Vec<Value>>,
|
||||
/// The kinds of row the trace refuses to write.
|
||||
refuses: RefCell<Vec<&'static str>>,
|
||||
unreadable: Cell<bool>,
|
||||
}
|
||||
|
||||
impl Ledger for Memory {
|
||||
fn rows(&self) -> Result<Vec<Value>> {
|
||||
if self.unreadable.get() {
|
||||
bail!("the trace cannot be read");
|
||||
}
|
||||
Ok(self.rows.borrow().clone())
|
||||
}
|
||||
|
||||
fn append(&self, row: Value) -> Result<()> {
|
||||
if self.refuses.borrow().iter().any(|kind| row["agent"] == *kind) {
|
||||
bail!("the trace cannot be written");
|
||||
}
|
||||
self.rows.borrow_mut().push(row);
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -148,7 +161,7 @@ fn t_a1_loop_runs_tool_calls() {
|
|||
// 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!((rig.ledger.kinds("call").len(), rig.ledger.kinds("settle").len()), (3, 3), "each call is reserved before it is made and settled after");
|
||||
assert_eq!(*model.ids.borrow(), ["w1-m1", "w1-m2", "w1-m3"]);
|
||||
}
|
||||
|
||||
|
|
@ -245,9 +258,9 @@ fn t_a1_day_cap_survives_a_restart() {
|
|||
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.
|
||||
// Her trace holds the call, its settlement 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:?}");
|
||||
assert!(records.len() == 3 && records.iter().all(|record| record.get("agent").is_some() && !crate::projection::turn::is_real(record)), "{records:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -366,8 +379,8 @@ fn t_a1_a_failed_call_keeps_its_outage_and_its_cost() {
|
|||
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")));
|
||||
let (calls, settled) = (rig.ledger.kinds("call"), rig.ledger.kinds("settle"));
|
||||
assert_eq!((calls.len(), settled.len(), settled[0]["failed"].as_str()), (1, 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())]);
|
||||
|
|
@ -413,3 +426,289 @@ 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"));
|
||||
}
|
||||
|
||||
fn near(left: f64, right: f64) -> bool {
|
||||
(left - right).abs() < 1e-9
|
||||
}
|
||||
|
||||
fn day_of(rig: &Rig) -> f64 {
|
||||
day_usd(&rig.ledger.rows.borrow(), noon(), &rig.bounds)
|
||||
}
|
||||
|
||||
// ---- The day cap fails closed.
|
||||
|
||||
#[test]
|
||||
fn t_a1_a_trace_that_cannot_be_read_makes_no_call() {
|
||||
let rig = Rig::new();
|
||||
rig.ledger.unreadable.set(true);
|
||||
let model = Script::new(vec![]);
|
||||
let turn = rig.run(&model, "x");
|
||||
assert!(matches!(&turn.ended, Ended::Failed(failed) if failed.outage && failed.reason.contains("the trace cannot be read")), "{:?}", turn.ended);
|
||||
assert!(model.seen.borrow().is_empty() && turn.model_calls == 0 && rig.session.load().unwrap().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn t_a1_a_trace_that_cannot_take_the_call_row_makes_no_call() {
|
||||
let rig = Rig::new();
|
||||
rig.ledger.refuses.borrow_mut().push("call");
|
||||
let model = Script::new(vec![]);
|
||||
let turn = rig.run(&model, "x");
|
||||
assert!(matches!(&turn.ended, Ended::Failed(failed) if failed.outage), "{:?}", turn.ended);
|
||||
assert!(model.seen.borrow().is_empty(), "the model was not asked");
|
||||
assert!(near(turn.usd, 0.0) && rig.session.load().unwrap().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn t_a1_a_trace_that_cannot_take_a_cap_receipt_or_a_discard_is_a_failed_start() {
|
||||
let rig = Rig::new();
|
||||
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "usage": usage(1_505_000, 0, 0, 0) })).unwrap();
|
||||
rig.ledger.refuses.borrow_mut().push("receipt");
|
||||
let turn = rig.run(&Script::new(vec![]), "x");
|
||||
assert!(matches!(turn.ended, Ended::Failed(_)), "a cap that cannot be recorded is not a quiet cap: {:?}", turn.ended);
|
||||
|
||||
let rig = Rig::new();
|
||||
std::fs::write(rig.dir.path().join("agent-session.cc"), b"not a store").unwrap();
|
||||
rig.ledger.refuses.borrow_mut().push("session_discarded");
|
||||
let model = Script::new(vec![]);
|
||||
assert!(matches!(rig.run(&model, "x").ended, Ended::Failed(_)));
|
||||
assert!(model.seen.borrow().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn t_a1_a_settle_row_that_cannot_be_written_ends_the_wake_and_keeps_the_worst_case() {
|
||||
// ledger-fail-call: the call came back, its row cannot be written. No tool runs, no further call is made, and the day
|
||||
// still holds the call at the wake cap, from the row written before it.
|
||||
let rig = Rig::new();
|
||||
rig.ledger.refuses.borrow_mut().push("settle");
|
||||
let model = Script::new(vec![asks("c1", "alpha", small()), ends("Never.", small())]);
|
||||
let turn = rig.run(&model, "x");
|
||||
assert!(matches!(&turn.ended, Ended::Failed(failed) if failed.outage && failed.reason.contains("could not be written")), "{:?}", turn.ended);
|
||||
assert_eq!((model.seen.borrow().len(), turn.tool_calls, rig.stub.ran.borrow().len()), (1, 0, 0));
|
||||
assert!(near(day_of(&rig), rig.bounds.wake_usd), "{}", day_of(&rig));
|
||||
assert!(turn.usd > 0.0, "what the wake spent is still counted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn t_a1_a_failed_call_whose_settle_row_cannot_be_written_says_so() {
|
||||
// ledger-fail-failrow: the connector's failure is not what the turn reports when her own trace cannot keep it.
|
||||
let rig = Rig::new();
|
||||
rig.ledger.refuses.borrow_mut().push("settle");
|
||||
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!(matches!(&turn.ended, Ended::Failed(failed) if failed.reason.contains("could not be written") && failed != &cut), "{:?}", turn.ended);
|
||||
assert!(near(turn.usd, 0.002));
|
||||
assert!(near(day_of(&rig), rig.bounds.wake_usd), "unsettled, so at the worst case");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn t_a1_a_failed_call_with_no_usage_is_charged_the_worst_case() {
|
||||
let rig = Rig::new();
|
||||
let outage = Failed { reason: "the connector did not answer".into(), outage: true, usage: None };
|
||||
let turn = rig.run(&Script::new(vec![Err(outage.clone())]), "x");
|
||||
assert_eq!(turn.ended, Ended::Failed(outage), "the connector's own failure, outage flag intact");
|
||||
assert!(near(turn.usd, rig.bounds.wake_usd), "{}", turn.usd);
|
||||
assert!(near(day_of(&rig), rig.bounds.wake_usd), "and the day carries it: {}", day_of(&rig));
|
||||
// A failure that did report usage is charged what it used.
|
||||
let rig = Rig::new();
|
||||
rig.run(&Script::new(vec![Err(Failed { reason: "cut".into(), outage: false, usage: Some(usage(1000, 0, 0, 0)) })]), "x");
|
||||
assert!(near(day_of(&rig), 0.002), "{}", day_of(&rig));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn t_a1_a_call_that_was_never_settled_stands_at_the_worst_case() {
|
||||
// A start killed between the call row and its answer leaves a call row alone.
|
||||
let rig = Rig::new();
|
||||
for at in 0..7 {
|
||||
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "call": format!("seed{at}") })).unwrap();
|
||||
}
|
||||
assert!(near(day_of(&rig), 7.0 * 0.40));
|
||||
let turn = rig.run(&Script::new(vec![ends("Fine.", small())]), "x");
|
||||
assert_eq!(turn.ended, Ended::EndTurn, "$2.80 is under the day's $3");
|
||||
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "call": "seed9" })).unwrap();
|
||||
let model = Script::new(vec![]);
|
||||
assert_eq!(rig.wake(&model, "w10", "You act for her.", "y").ended, Ended::Cap(Cap::DaySpend));
|
||||
assert!(model.seen.borrow().is_empty());
|
||||
// A settle row prices its call; a usage that does not read, and a time that does not read, fail high.
|
||||
let rig = Rig::new();
|
||||
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "call": "a" })).unwrap();
|
||||
rig.ledger.append(json!({ "agent": "settle", "at": noon().to_rfc3339(), "call": "a", "usage": usage(1000, 0, 0, 0) })).unwrap();
|
||||
assert!(near(day_of(&rig), 0.002));
|
||||
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "usage": "garbage" })).unwrap();
|
||||
assert!(near(day_of(&rig), 0.002 + 0.40));
|
||||
rig.ledger.append(json!({ "agent": "call", "at": "not a time", "usage": usage(1000, 0, 0, 0) })).unwrap();
|
||||
assert!(near(day_of(&rig), 0.002 + 0.40 + 0.002), "a row dated by nothing is today's");
|
||||
rig.ledger.append(json!({ "agent": "call", "at": (noon() - Duration::days(1)).to_rfc3339(), "call": "old" })).unwrap();
|
||||
assert!(near(day_of(&rig), 0.404), "yesterday's reservation is not today's");
|
||||
}
|
||||
|
||||
// ---- The caps hold at equality, and nowhere short of it.
|
||||
|
||||
#[test]
|
||||
fn t_a1_the_day_cap_stops_at_exactly_the_cap() {
|
||||
let rig = Rig::new();
|
||||
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "usage": usage(1_500_000, 0, 0, 0) })).unwrap();
|
||||
let model = Script::new(vec![]);
|
||||
assert_eq!(rig.run(&model, "x").ended, Ended::Cap(Cap::DaySpend), "$3.00 is the cap");
|
||||
assert!(model.seen.borrow().is_empty());
|
||||
let rig = Rig::new();
|
||||
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "usage": usage(1_499_999, 0, 0, 0) })).unwrap();
|
||||
assert_eq!(rig.run(&Script::new(vec![ends("Ok.", small())]), "x").ended, Ended::EndTurn);
|
||||
|
||||
// Inside a wake: $2.70 behind her and a $0.30 call reaches the cap on the nose.
|
||||
let rig = Rig::new();
|
||||
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "usage": usage(1_350_000, 0, 0, 0) })).unwrap();
|
||||
let model = Script::new(vec![asks("c1", "alpha", usage(0, 30_000, 0, 0))]);
|
||||
let turn = rig.run(&model, "x");
|
||||
assert_eq!(turn.ended, Ended::Cap(Cap::DaySpend));
|
||||
assert!(near(turn.receipts.last().unwrap().fields()["reached"].as_f64().unwrap(), 3.0), "the cap receipt says what the day had reached: {:?}", turn.receipts.last());
|
||||
let rig = Rig::new();
|
||||
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "usage": usage(1_350_000, 0, 0, 0) })).unwrap();
|
||||
let model = Script::new(vec![asks("c1", "alpha", usage(0, 29_999, 0, 0)), ends("Ok.", small())]);
|
||||
assert_eq!(rig.run(&model, "x").ended, Ended::EndTurn, "a hair under");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn t_a1_the_wake_cap_stops_at_exactly_the_cap() {
|
||||
let rig = Rig::new();
|
||||
let model = Script::new(vec![asks("c1", "alpha", usage(0, 40_000, 0, 0))]);
|
||||
let turn = rig.run(&model, "x");
|
||||
assert_eq!((turn.ended, turn.model_calls), (Ended::Cap(Cap::WakeSpend), 1), "$0.40 is the cap");
|
||||
let rig = Rig::new();
|
||||
let model = Script::new(vec![asks("c1", "alpha", usage(0, 39_999, 0, 0)), ends("Ok.", small())]);
|
||||
let turn = rig.run(&model, "x");
|
||||
assert_eq!((turn.ended, turn.model_calls), (Ended::EndTurn, 2));
|
||||
}
|
||||
|
||||
// ---- Prices.
|
||||
|
||||
#[test]
|
||||
fn t_a1_every_priced_term_is_the_pages() {
|
||||
let mut bounds = AgentTuning::default();
|
||||
let million = 1_000_000;
|
||||
// Claude Sonnet 5.5, platform.claude.com pricing, 2026-11-29.
|
||||
assert!(near(price(&bounds, &usage(million, 0, 0, 0)), 2.0));
|
||||
assert!(near(price(&bounds, &usage(0, million, 0, 0)), 10.0));
|
||||
assert!(near(price(&bounds, &usage(0, 0, million, 0)), 0.10), "a cache hit is 0.05x input");
|
||||
assert!(near(price(&bounds, &usage(0, 0, 0, million)), 4.0), "Long writes the one-hour cache");
|
||||
bounds.retention = CacheRetention::Short;
|
||||
assert!(near(price(&bounds, &usage(0, 0, 0, million)), 2.50), "Short writes the five-minute cache");
|
||||
// A model the table does not list is priced at the dearest of each term.
|
||||
let other = Spent { model: "claude-unlisted".into(), ..usage(0, 0, 0, million) };
|
||||
assert!(near(price(&bounds, &other), 2.50));
|
||||
}
|
||||
|
||||
// ---- The session's freshness, pinned at its edges.
|
||||
|
||||
#[test]
|
||||
fn t_a1_a_changed_model_or_tool_discards() {
|
||||
let mut rig = Rig::new();
|
||||
rig.run(&Script::new(vec![ends("First.", small())]), "one");
|
||||
rig.bounds.model = "claude-other".into();
|
||||
let model = Script::new(vec![ends("Second.", small())]);
|
||||
rig.wake(&model, "w2", "You act for her.", "two");
|
||||
assert_eq!((model.seen.borrow()[0].len(), rig.discards()), (1, vec!["digest".to_owned()]));
|
||||
|
||||
for change in ["parameters", "description"] {
|
||||
let rig = Rig::new();
|
||||
rig.run(&Script::new(vec![ends("First.", small())]), "one");
|
||||
if change == "parameters" {
|
||||
rig.stub.parameters.replace("{\"type\":\"object\",\"properties\":{\"room\":{\"type\":\"string\"}}}".into());
|
||||
} else {
|
||||
rig.stub.description.replace("stub, changed".into());
|
||||
}
|
||||
let model = Script::new(vec![ends("Second.", small())]);
|
||||
rig.wake(&model, "w2", "You act for her.", "two");
|
||||
assert_eq!((model.seen.borrow()[0].len(), rig.discards()), (1, vec!["digest".to_owned()]), "{change}");
|
||||
}
|
||||
// Nothing changed: kept.
|
||||
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", "You act for her.", "two");
|
||||
assert_eq!(model.seen.borrow()[0].len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn t_a1_a_miss_inside_a_wake_is_judged_on_the_prefix_the_wake_itself_sent() {
|
||||
// A fresh session: nothing was warm at the start. The first call writes a 3,100 token prefix; the second, which
|
||||
// should read it, reads nothing. The cold judgement needs the prefix the wake's own first call left.
|
||||
let rig = Rig::new();
|
||||
let model = Script::new(vec![asks("c1", "alpha", usage(100, 5, 0, 3000)), ends("Done.", usage(3200, 5, 0, 0))]);
|
||||
let turn = rig.run(&model, "x");
|
||||
assert_eq!(turn.ended, Ended::EndTurn);
|
||||
assert_eq!(rig.discards(), ["cache_miss"]);
|
||||
assert!(rig.session.load().unwrap().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn t_a1_the_cache_minimum_is_inclusive() {
|
||||
for (prefix, cold) in [(2048, true), (2047, false)] {
|
||||
let rig = Rig::new();
|
||||
rig.run(&Script::new(vec![ends("First.", usage(prefix - 1000, 5, 0, 1000))]), "one");
|
||||
rig.wake(&Script::new(vec![ends("Second.", usage(prefix + 10, 5, 0, 0))]), "w2", "You act for her.", "two");
|
||||
assert_eq!(rig.discards() == ["cache_miss"], cold, "a prefix of {prefix}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn t_a1_a_session_lives_to_its_ttl_less_the_margin_and_not_a_second_past() {
|
||||
for (retention, life) in [(CacheRetention::Long, 3540), (CacheRetention::Short, 240)] {
|
||||
let mut rig = Rig::new();
|
||||
rig.bounds.retention = retention;
|
||||
rig.run(&Script::new(vec![ends("First.", usage(100, 5, 0, 4900))]), "one");
|
||||
rig.clock.set(noon() + Duration::seconds(life));
|
||||
let model = Script::new(vec![ends("Second.", usage(100, 5, 4900, 0))]);
|
||||
rig.wake(&model, "w2", "You act for her.", "two");
|
||||
assert!(rig.discards().is_empty() && model.seen.borrow()[0].len() == 3, "{retention:?} at {life} s is kept");
|
||||
// The wake just made renewed it: one second past that life it goes.
|
||||
rig.clock.set(noon() + Duration::seconds(2 * life + 1));
|
||||
let model = Script::new(vec![ends("Third.", usage(5000, 5, 0, 0))]);
|
||||
rig.wake(&model, "w3", "You act for her.", "three");
|
||||
assert_eq!((rig.discards(), model.seen.borrow()[0].len()), (vec!["ttl".to_owned()], 1), "{retention:?} one second past");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn t_a1_a_prompt_is_kept_to_the_session_ceiling_and_not_a_token_past() {
|
||||
for (written, kept) in [(100, true), (101, false)] {
|
||||
let mut rig = Rig::new();
|
||||
rig.bounds.max_session_tokens = 1000;
|
||||
rig.run(&Script::new(vec![ends("First.", usage(900, 5, 0, written))]), "one");
|
||||
rig.wake(&Script::new(vec![ends("Second.", small())]), "w2", "You act for her.", "two");
|
||||
assert_eq!(rig.discards().is_empty(), kept, "a prompt of {}", 900 + written);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn t_a1_a_session_keeps_its_birth_and_a_new_one_takes_the_time_of_its_first_call() {
|
||||
let rig = Rig::new();
|
||||
let first = Script::new(vec![ends("First.", usage(100, 5, 0, 4900))]);
|
||||
rig.run(&first, "one");
|
||||
let born = rig.session.load().unwrap().unwrap();
|
||||
assert_eq!((born.created_at, born.last_call_at), (noon(), noon()));
|
||||
rig.clock.set(noon() + Duration::minutes(10));
|
||||
let second = Script::new(vec![ends("Second.", usage(100, 5, 4900, 0))]);
|
||||
rig.wake(&second, "w2", "You act for her.", "two");
|
||||
let kept = rig.session.load().unwrap().unwrap();
|
||||
assert_eq!((kept.created_at, kept.last_call_at), (noon(), noon() + Duration::minutes(10)), "birth stays, the last call moves");
|
||||
assert_eq!(first.conversations.borrow()[0], second.conversations.borrow()[0], "one conversation while the session lives");
|
||||
// Discarded and begun again: it is born at the new time, and the conversation is a new one.
|
||||
rig.clock.set(noon() + Duration::hours(3));
|
||||
let third = Script::new(vec![ends("Third.", small())]);
|
||||
rig.wake(&third, "w3", "You act for her.", "three");
|
||||
let reborn = rig.session.load().unwrap().unwrap();
|
||||
assert_eq!((reborn.created_at, reborn.last_call_at), (noon() + Duration::hours(3), noon() + Duration::hours(3)));
|
||||
assert_ne!(first.conversations.borrow()[0], third.conversations.borrow()[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_store_that_cannot_be_forgotten_is_an_error_and_one_already_gone_is_not() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
// Nothing to forget: no store, and not even a directory to hold one.
|
||||
assert!(FileSession::new(dir.path().join("none").join("agent-session.cc")).discard().is_ok());
|
||||
assert!(FileSession::new(dir.path().join("agent-session.cc")).discard().is_ok());
|
||||
// A store that cannot be opened is removed whole; one that cannot be removed is a fault, not a quiet success.
|
||||
let blocked = dir.path().join("blocked.cc");
|
||||
std::fs::create_dir(&blocked).unwrap();
|
||||
assert!(FileSession::new(&blocked).discard().is_err());
|
||||
}
|
||||
|
|
|
|||
|
|
@ -732,7 +732,8 @@ retention = \"short\"
|
|||
input = 5.0
|
||||
output = 25.0
|
||||
cache_read = 0.5
|
||||
cache_write = 10.0
|
||||
cache_write_short = 6.25
|
||||
cache_write_long = 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));
|
||||
|
|
@ -775,6 +776,43 @@ fn a_value_out_of_range_refuses_the_tuning() {
|
|||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_value_out_of_range_refuses_the_agent_tuning() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join(TUNING_FILE);
|
||||
let price = "[agent.prices.claude-sonnet-5-5]\ninput = 2.0\noutput = 10.0\ncache_read = 0.1\ncache_write_short = 2.5\ncache_write_long = 4.0\n";
|
||||
for (body, names) in [
|
||||
("[agent]\nmodel = \" \"\n".to_owned(), "agent.model must name a model"),
|
||||
("[agent]\nmodel = \"claude-unpriced\"\n".to_owned(), "agent.prices has no entry"),
|
||||
(price.replace("input = 2.0", "input = -1.0"), "must be finite and not negative"),
|
||||
(price.replace("output = 10.0", "output = inf"), "must be finite and not negative"),
|
||||
(price.replace("cache_write_long = 4.0", "cache_write_long = nan"), "must be finite and not negative"),
|
||||
("[agent]\ntool_calls = 0\n".to_owned(), "agent.tool_calls and agent.model_calls"),
|
||||
("[agent]\ntool_calls = 33\n".to_owned(), "agent.tool_calls and agent.model_calls"),
|
||||
("[agent]\nmodel_calls = 0\n".to_owned(), "agent.tool_calls and agent.model_calls"),
|
||||
("[agent]\nmodel_calls = 33\n".to_owned(), "agent.tool_calls and agent.model_calls"),
|
||||
("[agent]\nwake_usd = 0.0\n".to_owned(), "agent.wake_usd must be above 0"),
|
||||
("[agent]\nwake_usd = -1.0\n".to_owned(), "agent.wake_usd must be above 0"),
|
||||
("[agent]\nwake_usd = inf\n".to_owned(), "agent.wake_usd must be above 0"),
|
||||
("[agent]\nwake_usd = 5.5\nday_usd = 20.0\n".to_owned(), "agent.wake_usd must be above 0"),
|
||||
("[agent]\nday_usd = 0.0\n".to_owned(), "agent.day_usd must be above 0"),
|
||||
("[agent]\nday_usd = -1.0\n".to_owned(), "agent.day_usd must be above 0"),
|
||||
("[agent]\nday_usd = 50.5\n".to_owned(), "agent.day_usd must be above 0"),
|
||||
("[agent]\nwake_usd = 2.0\nday_usd = 1.0\n".to_owned(), "agent.wake_usd must be at most agent.day_usd"),
|
||||
("[agent]\nmax_session_tokens = 0\n".to_owned(), "agent.max_session_tokens and agent.cache_min_tokens"),
|
||||
("[agent]\ncache_min_tokens = 0\n".to_owned(), "agent.max_session_tokens and agent.cache_min_tokens"),
|
||||
("[agent.ttl_s]\nshort = 60\n".to_owned(), "agent.ttl_s must be above 60"),
|
||||
("[agent.ttl_s]\nlong = 60\n".to_owned(), "agent.ttl_s must be above 60"),
|
||||
] {
|
||||
std::fs::write(&path, &body).unwrap();
|
||||
let fault = format!("{:#}", tuning::load(&path).unwrap_err());
|
||||
assert!(fault.contains(names), "{body:?}: {fault}");
|
||||
}
|
||||
// The edges that load: a day cap that is the wake cap, the least ttl, the most calls.
|
||||
std::fs::write(&path, "[agent]\nwake_usd = 1.0\nday_usd = 1.0\ntool_calls = 32\nmodel_calls = 1\n\n[agent.ttl_s]\nshort = 61\nlong = 61\n").unwrap();
|
||||
assert!(tuning::load(&path).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lower_temperature_concentrates_the_selection() {
|
||||
let room = chat_room();
|
||||
|
|
@ -1001,7 +1039,7 @@ fn a_given_state_is_projected_without_reading_the_stored_one() {
|
|||
// ---------------------------------------------------------------------------------------------
|
||||
// KitModel against a real kit server (ported with it from the stream organ).
|
||||
|
||||
use model_connector::{CallerAdmission, ProviderBackend, ProviderCall, ProviderRequest, ServeLimits, StopReason, TransportEvent, TransportEventPayload, TransportOutcome, TransportResult, Usage, serve as serve_kit};
|
||||
use model_connector::{CallerAdmission, InputItem, ProviderBackend, ProviderCall, ProviderRequest, ServeLimits, StopReason, TransportEvent, TransportEventPayload, TransportOutcome, TransportResult, Usage, serve as serve_kit};
|
||||
|
||||
const KIT_KEY: &str = "projector-test-key";
|
||||
const KIT_MODEL: &str = "claude-haiku-5-5";
|
||||
|
|
@ -1065,7 +1103,8 @@ fn a_kit_step_hands_back_tool_calls_and_the_items_to_replay() {
|
|||
let usage = Usage { input_tokens: 3, cache_read_tokens: 2, cache_write_tokens: 1, output_tokens: 4, reasoning_tokens: None };
|
||||
let events = vec![
|
||||
TransportEvent { sequence: 0, payload: TransportEventPayload::TextDelta { text: "Let me say it.".into() } },
|
||||
TransportEvent { sequence: 1, payload: TransportEventPayload::ToolCall { call_id: "toolu_1".into(), name: "say".into(), arguments: "{\"text\":\"hi\"}".into() } },
|
||||
TransportEvent { sequence: 1, payload: TransportEventPayload::ReasoningState { state: vec![7, 7, 7] } },
|
||||
TransportEvent { sequence: 2, payload: TransportEventPayload::ToolCall { call_id: "toolu_1".into(), name: "say".into(), arguments: "{\"text\":\"hi\"}".into() } },
|
||||
];
|
||||
call.transported(events, TransportOutcome::Completed { provider_response_id: Some("msg-1".into()), stop_reason: StopReason::ToolUse, usage })
|
||||
}
|
||||
|
|
@ -1086,7 +1125,7 @@ fn a_kit_step_hands_back_tool_calls_and_the_items_to_replay() {
|
|||
let stepped = model.step(StepRequest { request_id: "agent-1", conversation_id: "agent-c", model: KIT_MODEL, instructions: "You act for her.", tools: &tools, input: input.clone(), retention: Some(model_connector::CacheRetention::Long), schema: None }).unwrap();
|
||||
assert_eq!((stepped.stop, stepped.text.as_str()), (StopReason::ToolUse, "Let me say it."));
|
||||
assert_eq!(stepped.calls, [ToolCall { call_id: "toolu_1".into(), name: "say".into(), arguments: "{\"text\":\"hi\"}".into() }]);
|
||||
assert_eq!(stepped.items, [InputItem::AssistantText { text: "Let me say it.".into() }, InputItem::ToolCall { call_id: "toolu_1".into(), name: "say".into(), arguments: "{\"text\":\"hi\"}".into() }]);
|
||||
assert_eq!(stepped.items, [InputItem::AssistantText { text: "Let me say it.".into() }, InputItem::ReasoningState { provider: "anthropic-messages".into(), model: KIT_MODEL.into(), state: vec![7, 7, 7] }, InputItem::ToolCall { call_id: "toolu_1".into(), name: "say".into(), arguments: "{\"text\":\"hi\"}".into() }]);
|
||||
assert_eq!(stepped.usage, Spent { model: KIT_MODEL.into(), input_tokens: 3, output_tokens: 4, cache_read_tokens: 2, cache_write_tokens: 1, reasoning_tokens: None });
|
||||
{
|
||||
let seen = backend.seen.lock().unwrap();
|
||||
|
|
@ -1098,6 +1137,23 @@ fn a_kit_step_hands_back_tool_calls_and_the_items_to_replay() {
|
|||
assert!(failed.reason.contains("ended early") && failed.usage.is_some(), "{failed:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kit_ask_is_one_tool_less_turn_by_her_instance() {
|
||||
let backend = Scripted::ending(StopReason::EndTurn, &["I turn ", "it over."]);
|
||||
let (model, _root) = kit(Arc::clone(&backend), KIT_MODEL);
|
||||
let id = "mind-persona:eureka:project:a:1:1";
|
||||
let answer = model.ask(id, KIT_MODEL, "The projector prompt.", None).unwrap();
|
||||
assert_eq!(answer.text, "I turn it over.");
|
||||
assert_eq!(answer.usage, Some(Spent { model: KIT_MODEL.into(), input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_write_tokens: 0, reasoning_tokens: None }), "the receipt's usage, by the model that ran");
|
||||
let seen = backend.seen.lock().unwrap();
|
||||
let (caller, request) = &seen[0];
|
||||
assert_eq!(caller, INSTANCE);
|
||||
assert_eq!((request.request_id.as_str(), request.conversation_id.as_str(), request.model.as_str()), (id, id, KIT_MODEL));
|
||||
assert_eq!(request.input, [InputItem::UserText { text: "The projector prompt.".into() }]);
|
||||
assert_eq!((request.instructions.as_str(), request.reasoning_effort, request.max_output_tokens), (super::narrate::INSTRUCTIONS, Some(model_connector::ReasoningEffort::Low), super::narrate::MAX_OUTPUT_TOKENS));
|
||||
assert!(request.tools.is_empty() && request.output_schema_json.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kit_refusal_or_a_cut_short_turn_is_a_fault() {
|
||||
let backend = Scripted::ending(StopReason::EndTurn, &["Never said."]);
|
||||
|
|
|
|||
|
|
@ -153,7 +153,19 @@ pub struct Price {
|
|||
pub input: f64,
|
||||
pub output: f64,
|
||||
pub cache_read: f64,
|
||||
pub cache_write: f64,
|
||||
/// A write to the 5-minute cache, and to the 1-hour cache.
|
||||
pub cache_write_short: f64,
|
||||
pub cache_write_long: f64,
|
||||
}
|
||||
|
||||
impl Price {
|
||||
/// What a million tokens written to the cache of `retention` cost.
|
||||
pub(crate) fn cache_write(self, retention: CacheRetention) -> f64 {
|
||||
match retention {
|
||||
CacheRetention::Short => self.cache_write_short,
|
||||
CacheRetention::Long => self.cache_write_long,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for CacheTtl {
|
||||
|
|
@ -164,8 +176,8 @@ impl Default for CacheTtl {
|
|||
|
||||
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 };
|
||||
// Claude Sonnet 5.5 at the pricing page (platform.claude.com, 2026-11-29): $2 in, $10 out, $0.10 a cache hit, $2.50 a 5-minute write, $4 a 1-hour write.
|
||||
let sonnet = Price { input: 2.0, output: 10.0, cache_read: 0.10, cache_write_short: 2.50, cache_write_long: 4.0 };
|
||||
Self {
|
||||
model: "claude-sonnet-5-5".into(),
|
||||
tool_calls: 8,
|
||||
|
|
@ -185,7 +197,7 @@ 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) })
|
||||
self.prices.values().copied().fold(Price { input: 0.0, output: 0.0, cache_read: 0.0, cache_write_short: 0.0, cache_write_long: 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_short: a.cache_write_short.max(b.cache_write_short), cache_write_long: a.cache_write_long.max(b.cache_write_long) })
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -205,7 +217,7 @@ impl AgentTuning {
|
|||
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) {
|
||||
if ![price.input, price.output, price.cache_read, price.cache_write_short, price.cache_write_long].iter().all(|usd| usd.is_finite() && *usd >= 0.0) {
|
||||
bail!("agent.prices.{model} must be finite and not negative");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -393,6 +393,7 @@ mind_body::projection::tuning: impl Default for PoolCaps
|
|||
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 Price
|
||||
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]
|
||||
|
|
@ -401,10 +402,10 @@ mind_body::projection::tuning: struct LensWeights # [derive (Clone , Debug , Par
|
|||
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 Price # [derive (Clone , Copy , Debug , PartialEq , Serialize , Deserialize)] pub-fields[input: f64, output: f64, cache_read: f64, cache_write_short: f64, cache_write_long: 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 >]
|
||||
mind_body::projection::tuning: struct Tuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[projector: ProjectorTuning, persona: PersonaTuning, interpreter: InterpreterTuning, agent: AgentTuning, select: SelectTuning, lens: LensWeights, pronouns: BTreeMap < String , String >]
|
||||
mind_body::queue: fn on_hold (mind : & dyn MindPort) -> Result < Held >
|
||||
mind_body::queue: impl Held
|
||||
mind_body::queue: impl Held: fn contains (& self , item : & PipelineRef) -> bool
|
||||
|
|
|
|||
Loading…
Reference in a new issue