Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

0.9.0 G2: a monthly budget per bot (backend) (#495)

Oleksandr Ivanchenko0cc46b28354d
diff --git a/src/db/bot_budget.rs b/src/db/bot_budget.rs
new file mode 100644
index 00000000..377b421f
--- /dev/null
+++ b/src/db/bot_budget.rs
@@ -0,0 +1,354 @@
+//! G2's books (see `crate::server::bot_budget`): each bot's fresh tokens and dollars per local
+//! day, booked from the same call and the same numbers as the daily spending stop
+//! (`spend_stop::book_turn`), each bot's monthly budget (person-only, never in `settings`), the
+//! notices already sent, and the routines held while a bot was paused.
+
+use super::{Database, DbError};
+use chrono::{DateTime, Utc};
+use serde::Serialize;
+use sqlx::FromRow;
+
+/// A bot's use over some days (a month, or one day).
+#[derive(Debug, Clone, Default, PartialEq, FromRow, Serialize)]
+pub struct BotUse {
+ pub tokens: i64,
+ pub usd: f64,
+ pub reported_turns: i64,
+ pub unreported_turns: i64,
+ pub cost_turns: i64,
+}
+
+/// A bot's budget row; all zero / null when the person never set one.
+#[derive(Debug, Clone, Default, PartialEq, FromRow)]
+pub struct BotBudgetRow {
+ pub kwant_id: String,
+ pub budget_tokens: i64,
+ pub budget_usd: f64,
+ /// `YYYY-MM` the person pressed Continue for.
+ pub continued_month: Option<String>,
+ /// `YYYY-MM` of the current pause episode (set once per episode).
+ pub paused_month: Option<String>,
+ pub paused_at: Option<DateTime<Utc>>,
+ /// The budget key (`month|tokens|usd`) the 80% note was sent (or skipped) for.
+ pub warned_key: Option<String>,
+}
+
+/// Day rows older than this are pruned.
+const KEEP_DAYS: i64 = 400;
+/// Notices older than this are pruned (they dedupe within one month).
+const KEEP_NOTICE_DAYS: i64 = 62;
+
+impl Database {
+ pub(super) async fn migrate_bot_budget(&self) -> Result<(), DbError> {
+ let existed: Option<(String,)> =
+ sqlx::query_as("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'bot_spend_days'")
+ .fetch_optional(&self.pool)
+ .await?;
+ for stmt in [
+ "CREATE TABLE IF NOT EXISTS bot_spend_days (
+ day TEXT NOT NULL,
+ kwant_id TEXT NOT NULL,
+ tokens INTEGER NOT NULL DEFAULT 0,
+ usd REAL NOT NULL DEFAULT 0,
+ reported_turns INTEGER NOT NULL DEFAULT 0,
+ unreported_turns INTEGER NOT NULL DEFAULT 0,
+ cost_turns INTEGER NOT NULL DEFAULT 0,
+ updated_at TIMESTAMP NOT NULL,
+ PRIMARY KEY (day, kwant_id)
+ )",
+ "CREATE INDEX IF NOT EXISTS bot_spend_days_kwant ON bot_spend_days (kwant_id, day)",
+ "CREATE TABLE IF NOT EXISTS bot_budgets (
+ kwant_id TEXT PRIMARY KEY,
+ budget_tokens INTEGER NOT NULL DEFAULT 0,
+ budget_usd REAL NOT NULL DEFAULT 0,
+ continued_month TEXT,
+ paused_month TEXT,
+ paused_at TIMESTAMP,
+ warned_key TEXT,
+ updated_at TIMESTAMP NOT NULL
+ )",
+ "CREATE TABLE IF NOT EXISTS bot_budget_notices (
+ month TEXT NOT NULL,
+ key TEXT NOT NULL,
+ created_at TIMESTAMP NOT NULL,
+ PRIMARY KEY (month, key)
+ )",
+ "CREATE TABLE IF NOT EXISTS budget_held_routines (
+ routine_id TEXT PRIMARY KEY,
+ kwant_id TEXT NOT NULL,
+ first_due_at TIMESTAMP NOT NULL
+ )",
+ ] {
+ sqlx::query(stmt).execute(&self.pool).await?;
+ }
+ // Added with G2; fail harmlessly when already there
+ let _ = sqlx::query("ALTER TABLE parked_turns ADD COLUMN reason TEXT NOT NULL DEFAULT 'usage_limit'").execute(&self.pool).await;
+ let _ = sqlx::query("ALTER TABLE routine_runs ADD COLUMN note TEXT").execute(&self.pool).await;
+ if existed.is_none() {
+ // Once, on upgrade: the last 31 days of engine-reported calls, by UTC date, so the
+ // first month isn't 0 (approximate: model_usage misses Codex and cancelled turns)
+ let since = Utc::now() - chrono::Duration::days(31);
+ let _ = sqlx::query(
+ "INSERT OR IGNORE INTO bot_spend_days (day, kwant_id, tokens, usd, reported_turns, unreported_turns, cost_turns, updated_at) \
+ SELECT strftime('%Y-%m-%d', created_at), kwant_id, \
+ SUM(fresh_input + cache_write + output), SUM(COALESCE(cost_usd, 0)), \
+ SUM(CASE WHEN reported != 0 THEN 1 ELSE 0 END), SUM(CASE WHEN reported = 0 THEN 1 ELSE 0 END), \
+ SUM(CASE WHEN COALESCE(cost_usd, 0) > 0 THEN 1 ELSE 0 END), ? \
+ FROM model_usage WHERE created_at >= ? GROUP BY 1, 2",
+ )
+ .bind(Utc::now())
+ .bind(since)
+ .execute(&self.pool)
+ .await;
+ }
+ Ok(())
+ }
+
+ /// Adds one booked turn to the bot's day.
+ pub async fn add_bot_spend(&self, day: &str, kwant_id: &str, tokens: u64, usd: f64, reported: bool) -> Result<(), DbError> {
+ let tokens = i64::try_from(tokens).unwrap_or(i64::MAX);
+ let usd = if usd.is_finite() && usd > 0.0 { usd } else { 0.0 };
+ sqlx::query(
+ "INSERT INTO bot_spend_days (day, kwant_id, tokens, usd, reported_turns, unreported_turns, cost_turns, updated_at) \
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?) \
+ ON CONFLICT(day, kwant_id) DO UPDATE SET tokens = MIN(tokens + excluded.tokens, 9223372036854775807), \
+ usd = usd + excluded.usd, reported_turns = reported_turns + excluded.reported_turns, \
+ unreported_turns = unreported_turns + excluded.unreported_turns, cost_turns = cost_turns + excluded.cost_turns, \
+ updated_at = excluded.updated_at",
+ )
+ .bind(day)
+ .bind(kwant_id)
+ .bind(tokens)
+ .bind(usd)
+ .bind(i64::from(reported))
+ .bind(i64::from(!reported))
+ .bind(i64::from(usd > 0.0))
+ .bind(Utc::now())
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+
+ /// Drops day rows older than [`KEEP_DAYS`].
+ pub async fn prune_bot_spend(&self, today: chrono::NaiveDate) -> Result<(), DbError> {
+ let cutoff = (today - chrono::Duration::days(KEEP_DAYS)).format("%Y-%m-%d").to_string();
+ sqlx::query("DELETE FROM bot_spend_days WHERE day < ?").bind(cutoff).execute(&self.pool).await?;
+ Ok(())
+ }
+
+ /// The bot's use on the days starting with `prefix` (`YYYY-MM-` for a month, a full date for a day).
+ pub async fn bot_use(&self, kwant_id: &str, prefix: &str) -> Result<BotUse, DbError> {
+ let row: BotUse = sqlx::query_as(
+ "SELECT COALESCE(SUM(tokens), 0) AS tokens, COALESCE(SUM(usd), 0.0) AS usd, \
+ COALESCE(SUM(reported_turns), 0) AS reported_turns, COALESCE(SUM(unreported_turns), 0) AS unreported_turns, \
+ COALESCE(SUM(cost_turns), 0) AS cost_turns FROM bot_spend_days WHERE kwant_id = ? AND day LIKE ? || '%'",
+ )
+ .bind(kwant_id)
+ .bind(prefix)
+ .fetch_one(&self.pool)
+ .await?;
+ Ok(row)
+ }
+
+ /// Sum of every bot's tokens on `day` (the invariant with `daily_spend`).
+ pub async fn bot_spend_day_total(&self, day: &str) -> Result<i64, DbError> {
+ let (n,): (i64,) = sqlx::query_as("SELECT COALESCE(SUM(tokens), 0) FROM bot_spend_days WHERE day = ?")
+ .bind(day)
+ .fetch_one(&self.pool)
+ .await?;
+ Ok(n)
+ }
+
+ pub async fn bot_budget(&self, kwant_id: &str) -> Result<BotBudgetRow, DbError> {
+ let row: Option<BotBudgetRow> = sqlx::query_as(
+ "SELECT kwant_id, budget_tokens, budget_usd, continued_month, paused_month, paused_at, warned_key FROM bot_budgets WHERE kwant_id = ?",
+ )
+ .bind(kwant_id)
+ .fetch_optional(&self.pool)
+ .await?;
+ Ok(row.unwrap_or_else(|| BotBudgetRow { kwant_id: kwant_id.into(), ..Default::default() }))
+ }
+
+ /// The bots with a budget set (either limit).
+ pub async fn bots_with_budget(&self) -> Result<Vec<BotBudgetRow>, DbError> {
+ Ok(sqlx::query_as(
+ "SELECT kwant_id, budget_tokens, budget_usd, continued_month, paused_month, paused_at, warned_key FROM bot_budgets \
+ WHERE budget_tokens > 0 OR budget_usd > 0",
+ )
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ /// Sets the limits; a change of either clears Continue (the new budget applies at once).
+ pub async fn set_bot_budget(&self, kwant_id: &str, tokens: i64, usd: f64) -> Result<(), DbError> {
+ sqlx::query(
+ "INSERT INTO bot_budgets (kwant_id, budget_tokens, budget_usd, updated_at) VALUES (?, ?, ?, ?) \
+ ON CONFLICT(kwant_id) DO UPDATE SET \
+ continued_month = CASE WHEN budget_tokens = excluded.budget_tokens AND budget_usd = excluded.budget_usd THEN continued_month ELSE NULL END, \
+ budget_tokens = excluded.budget_tokens, budget_usd = excluded.budget_usd, updated_at = excluded.updated_at",
+ )
+ .bind(kwant_id)
+ .bind(tokens)
+ .bind(usd)
+ .bind(Utc::now())
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+
+ pub async fn set_bot_budget_continued(&self, kwant_id: &str, month: Option<&str>) -> Result<(), DbError> {
+ sqlx::query(
+ "INSERT INTO bot_budgets (kwant_id, continued_month, updated_at) VALUES (?, ?, ?) \
+ ON CONFLICT(kwant_id) DO UPDATE SET continued_month = excluded.continued_month, updated_at = excluded.updated_at",
+ )
+ .bind(kwant_id)
+ .bind(month)
+ .bind(Utc::now())
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+
+ /// Starts a pause episode for `month`; true only for the call that started it.
+ pub async fn start_bot_pause(&self, kwant_id: &str, month: &str, at: DateTime<Utc>) -> Result<bool, DbError> {
+ let res = sqlx::query(
+ "UPDATE bot_budgets SET paused_month = ?, paused_at = ? WHERE kwant_id = ? AND paused_month IS NOT ?",
+ )
+ .bind(month)
+ .bind(at)
+ .bind(kwant_id)
+ .bind(month)
+ .execute(&self.pool)
+ .await?;
+ Ok(res.rows_affected() == 1)
+ }
+
+ /// Ends the pause episode; true when there was one.
+ pub async fn end_bot_pause(&self, kwant_id: &str) -> Result<bool, DbError> {
+ let res = sqlx::query("UPDATE bot_budgets SET paused_month = NULL, paused_at = NULL WHERE kwant_id = ? AND paused_month IS NOT NULL")
+ .bind(kwant_id)
+ .execute(&self.pool)
+ .await?;
+ Ok(res.rows_affected() == 1)
+ }
+
+ /// Marks the 80% note for `key` as done; true only the first time.
+ pub async fn mark_bot_warned(&self, kwant_id: &str, key: &str) -> Result<bool, DbError> {
+ let res = sqlx::query("UPDATE bot_budgets SET warned_key = ? WHERE kwant_id = ? AND warned_key IS NOT ?")
+ .bind(key)
+ .bind(kwant_id)
+ .bind(key)
+ .execute(&self.pool)
+ .await?;
+ Ok(res.rows_affected() == 1)
+ }
+
+ /// Notes that the notice `key` went out in `month`; true only the first time.
+ pub async fn first_bot_budget_notice(&self, month: &str, key: &str) -> Result<bool, DbError> {
+ let now = Utc::now();
+ let done = sqlx::query("INSERT OR IGNORE INTO bot_budget_notices (month, key, created_at) VALUES (?, ?, ?)")
+ .bind(month)
+ .bind(key)
+ .bind(now)
+ .execute(&self.pool)
+ .await?;
+ let _ = sqlx::query("DELETE FROM bot_budget_notices WHERE created_at < ?")
+ .bind(now - chrono::Duration::days(KEEP_NOTICE_DAYS))
+ .execute(&self.pool)
+ .await;
+ Ok(done.rows_affected() == 1)
+ }
+
+ /// Holds a routine whose run came due while its bot was paused; true the first time.
+ pub async fn hold_budget_routine(&self, routine_id: &str, kwant_id: &str) -> Result<bool, DbError> {
+ let res = sqlx::query("INSERT OR IGNORE INTO budget_held_routines (routine_id, kwant_id, first_due_at) VALUES (?, ?, ?)")
+ .bind(routine_id)
+ .bind(kwant_id)
+ .bind(Utc::now())
+ .execute(&self.pool)
+ .await?;
+ Ok(res.rows_affected() == 1)
+ }
+
+ /// Takes (and forgets) the routines held for `kwant_id`, oldest first.
+ pub async fn take_budget_routines(&self, kwant_id: &str) -> Result<Vec<String>, DbError> {
+ let mut rows: Vec<(String, DateTime<Utc>)> =
+ sqlx::query_as("DELETE FROM budget_held_routines WHERE kwant_id = ? RETURNING routine_id, first_due_at")
+ .bind(kwant_id)
+ .fetch_all(&self.pool)
+ .await?;
+ rows.sort_by_key(|(_, at)| *at);
+ Ok(rows.into_iter().map(|(id, _)| id).collect())
+ }
+
+ /// Makes the bot's budget-held parked turns due now; returns how many.
+ pub async fn release_budget_parks(&self, kwant_id: &str, now: DateTime<Utc>) -> Result<u64, DbError> {
+ let res = sqlx::query("UPDATE parked_turns SET retry_at = ? WHERE kwant_id = ? AND status = 'pending' AND reason = 'bot_budget'")
+ .bind(now)
+ .bind(kwant_id)
+ .execute(&self.pool)
+ .await?;
+ Ok(res.rows_affected())
+ }
+
+ /// Bots that may have something to release: a pause episode, held routines or held turns.
+ pub async fn paused_or_holding_bots(&self) -> Result<Vec<String>, DbError> {
+ let rows: Vec<(String,)> = sqlx::query_as(
+ "SELECT kwant_id FROM bot_budgets WHERE paused_month IS NOT NULL \
+ UNION SELECT kwant_id FROM budget_held_routines \
+ UNION SELECT kwant_id FROM parked_turns WHERE status = 'pending' AND reason = 'bot_budget'",
+ )
+ .fetch_all(&self.pool)
+ .await?;
+ Ok(rows.into_iter().map(|(id,)| id).collect())
+ }
+
+ /// Writes a routine run's note ("Ran late: …").
+ pub async fn set_routine_run_note(&self, run_id: &str, note: &str) -> Result<(), DbError> {
+ sqlx::query("UPDATE routine_runs SET note = ? WHERE id = ?").bind(note).bind(run_id).execute(&self.pool).await?;
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[tokio::test]
+ async fn books_by_bot_and_month() {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ db.add_bot_spend("2026-11-06", "a", 100, 0.5, true).await.unwrap();
+ db.add_bot_spend("2026-11-07", "a", 50, 0.0, false).await.unwrap();
+ db.add_bot_spend("2026-10-31", "a", 7, 0.0, true).await.unwrap();
+ db.add_bot_spend("2026-11-06", "b", 9, f64::NAN, true).await.unwrap();
+ let m = db.bot_use("a", "2026-11-").await.unwrap();
+ assert_eq!(m, BotUse { tokens: 150, usd: 0.5, reported_turns: 1, unreported_turns: 1, cost_turns: 1 });
+ assert_eq!(db.bot_use("a", "2026-11-07").await.unwrap().tokens, 50);
+ assert_eq!(db.bot_spend_day_total("2026-11-06").await.unwrap(), 109);
+ assert_eq!(db.bot_use("nobody", "2026-11-").await.unwrap(), BotUse::default());
+ }
+
+ #[tokio::test]
+ async fn pause_episode_and_warn_once() {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ db.set_bot_budget("a", 100, 0.0).await.unwrap();
+ assert!(db.start_bot_pause("a", "2026-11", Utc::now()).await.unwrap());
+ assert!(!db.start_bot_pause("a", "2026-11", Utc::now()).await.unwrap());
+ assert!(db.end_bot_pause("a").await.unwrap());
+ assert!(!db.end_bot_pause("a").await.unwrap());
+ assert!(db.mark_bot_warned("a", "2026-11|100|0").await.unwrap());
+ assert!(!db.mark_bot_warned("a", "2026-11|100|0").await.unwrap());
+ assert!(db.mark_bot_warned("a", "2026-11|200|0").await.unwrap());
+ db.set_bot_budget_continued("a", Some("2026-11")).await.unwrap();
+ db.set_bot_budget("a", 100, 0.0).await.unwrap();
+ assert_eq!(db.bot_budget("a").await.unwrap().continued_month.as_deref(), Some("2026-11"));
+ db.set_bot_budget("a", 300, 0.0).await.unwrap();
+ assert_eq!(db.bot_budget("a").await.unwrap().continued_month, None);
+ assert!(db.hold_budget_routine("r1", "a").await.unwrap());
+ assert!(!db.hold_budget_routine("r1", "a").await.unwrap());
+ assert_eq!(db.take_budget_routines("a").await.unwrap(), vec!["r1".to_string()]);
+ assert!(db.take_budget_routines("a").await.unwrap().is_empty());
+ }
+}
diff --git a/src/db/continuity.rs b/src/db/continuity.rs
index 8d128a68..f2da5185 100644
--- a/src/db/continuity.rs
+++ b/src/db/continuity.rs
@@ -228,6 +228,9 @@ pub struct RoutineRun {
pub status: String,
pub error: Option<String>,
pub message_id: Option<String>,
+ /// A line for the run's history, e.g. "Ran late: Pixel was paused at its monthly budget." (G2)
+ #[sqlx(default)]
+ pub note: Option<String>,
}
#[derive(Debug, Clone, Default)]
@@ -973,6 +976,7 @@ impl Database {
status: status.into(),
error: error.map(Into::into),
message_id: None,
+ note: None,
})
}
@@ -1043,7 +1047,7 @@ impl Database {
limit: i64,
) -> Result<Vec<RoutineRun>, DbError> {
Ok(sqlx::query_as::<_, RoutineRun>(
- "SELECT id, routine_id, trigger, started_at, ended_at, status, error, message_id FROM routine_runs \
+ "SELECT id, routine_id, trigger, started_at, ended_at, status, error, message_id, note FROM routine_runs \
WHERE routine_id = ? ORDER BY started_at DESC, rowid DESC LIMIT ?",
)
.bind(routine_id)
diff --git a/src/db/mod.rs b/src/db/mod.rs
index aab34893..7ff638f6 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -51,6 +51,7 @@ pub mod dev_prepush;
pub mod dev_line_notes;
pub mod dev_worktrees;
pub mod spend;
+pub mod bot_budget;
pub mod agent_connections;
pub mod dev_jira;
pub mod telegram;
@@ -219,6 +220,8 @@ impl Database {
db.migrate_reactions().await?;
// 0.7.4: the daily spending stop's books (add-only)
db.migrate_spend().await?;
+ // 0.9.0 G2: per-bot monthly budgets (add-only; after usage, parked and routines)
+ db.migrate_bot_budget().await?;
if spaces {
let migration = db.migrate_spaces(data_dir, fresh).await?;
db.require_spaces_schema(&migration).await?;
diff --git a/src/db/parked.rs b/src/db/parked.rs
index a6039a28..9d113612 100644
--- a/src/db/parked.rs
+++ b/src/db/parked.rs
@@ -22,8 +22,15 @@ pub struct ParkedTurn {
/// "pending", "running", "done" or "dropped" (the chat moved on before the retry).
pub status: String,
pub created_at: DateTime<Utc>,
+ /// Why it waits: "usage_limit" (the engine's limit) or "bot_budget" (G2: the bot is paused
+ /// at its monthly budget; released early by Continue or a raise).
+ #[sqlx(default)]
+ pub reason: String,
}
+/// A held prompt never grows past this; the oldest part goes first.
+const MAX_HELD_PROMPT: usize = 64 * 1024;
+
pub struct NewParkedTurn {
pub kwant_id: String,
pub channel_id: Option<String>,
@@ -33,6 +40,21 @@ pub struct NewParkedTurn {
pub depth: i64,
pub prompt: String,
pub retry_at: DateTime<Utc>,
+ /// "usage_limit" or "bot_budget" (see [`ParkedTurn::reason`]).
+ pub reason: &'static str,
+}
+
+/// `held` with `more` after it, kept under [`MAX_HELD_PROMPT`] by dropping the oldest part.
+fn appended(held: &str, more: &str) -> String {
+ let mut s = format!("{held}\n\n[another message arrived while the bot was paused]\n\n{more}");
+ if s.len() > MAX_HELD_PROMPT {
+ let mut cut = s.len() - MAX_HELD_PROMPT;
+ while !s.is_char_boundary(cut) {
+ cut += 1;
+ }
+ s = s[cut..].to_string();
+ }
+ s
}
/// The chat a turn ran in, matched the way it was parked.
@@ -68,20 +90,34 @@ impl Database {
/// time, so a chat gets at most one retry however many messages hit the limit).
pub async fn park_turn(&self, t: &NewParkedTurn) -> Result<Option<ParkedTurn>, DbError> {
let mut tx = self.begin_write().await?;
- let waiting: Option<(String,)> = sqlx::query_as(&format!("SELECT id FROM parked_turns WHERE status = 'pending' AND {SAME_CHAT}"))
- .bind(&t.kwant_id)
- .bind(t.channel_id.as_deref().unwrap_or(""))
- .bind(t.direct_kwant_id.as_deref().unwrap_or(""))
- .bind(t.thread_id.as_deref().unwrap_or(""))
- .fetch_optional(&mut *tx)
- .await?;
- if waiting.is_some() {
- tx.rollback().await?;
+ let waiting: Option<(String, String, String, DateTime<Utc>)> = sqlx::query_as(&format!(
+ "SELECT id, prompt, reason, retry_at FROM parked_turns WHERE status = 'pending' AND {SAME_CHAT}"
+ ))
+ .bind(&t.kwant_id)
+ .bind(t.channel_id.as_deref().unwrap_or(""))
+ .bind(t.direct_kwant_id.as_deref().unwrap_or(""))
+ .bind(t.thread_id.as_deref().unwrap_or(""))
+ .fetch_optional(&mut *tx)
+ .await?;
+ if let Some((id, prompt, reason, retry_at)) = waiting {
+ // A budget hold keeps every message, oldest first (G2: held, not dropped); a usage-limit
+ // retry already waiting in that chat becomes a budget hold
+ if t.reason == "bot_budget" {
+ sqlx::query("UPDATE parked_turns SET prompt = ?, reason = 'bot_budget', retry_at = ? WHERE id = ?")
+ .bind(appended(&prompt, &t.prompt))
+ .bind(if reason == "bot_budget" { retry_at } else { retry_at.max(t.retry_at) })
+ .bind(&id)
+ .execute(&mut *tx)
+ .await?;
+ tx.commit().await?;
+ } else {
+ tx.rollback().await?;
+ }
return Ok(None);
}
let row = sqlx::query_as::<_, ParkedTurn>(
- "INSERT INTO parked_turns (id, kwant_id, channel_id, direct_kwant_id, thread_id, delegation_id, depth, prompt, retry_at, status, created_at) \
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?) RETURNING *",
+ "INSERT INTO parked_turns (id, kwant_id, channel_id, direct_kwant_id, thread_id, delegation_id, depth, prompt, retry_at, status, created_at, reason) \
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?) RETURNING *",
)
.bind(Uuid::new_v4().to_string())
.bind(&t.kwant_id)
@@ -93,6 +129,7 @@ impl Database {
.bind(&t.prompt)
.bind(t.retry_at)
.bind(Utc::now())
+ .bind(t.reason)
.fetch_one(&mut *tx)
.await?;
tx.commit().await?;
@@ -101,7 +138,7 @@ impl Database {
/// The parked turns due by `now`, each claimed (`running`) so it runs once.
pub async fn take_due_parked(&self, now: DateTime<Utc>) -> Result<Vec<ParkedTurn>, DbError> {
- let due = sqlx::query_as::<_, ParkedTurn>("SELECT * FROM parked_turns WHERE status = 'pending' AND retry_at <= ? ORDER BY retry_at")
+ let due = sqlx::query_as::<_, ParkedTurn>("SELECT * FROM parked_turns WHERE status = 'pending' AND retry_at <= ? ORDER BY retry_at, created_at")
.bind(now)
.fetch_all(&self.pool)
.await?;
diff --git a/src/server/auth.rs b/src/server/auth.rs
index 776ba9c7..3a79812b 100644
--- a/src/server/auth.rs
+++ b/src/server/auth.rs
@@ -387,6 +387,9 @@ pub fn person_only(method: &Method, path: &str) -> bool {
// Carrying on a chain that went over its token budget is the person's call
["", "api", "chains", _, "continue"] => *method == Method::POST,
// Lifting today's spending stop spends the person's money: only they press Continue
+ // A bot's monthly budget (G2): only the person sets, raises, continues or pauses it again;
+ // a bot (Chief included) never changes its own budget or another bot's
+ ["", "api", "kwants", _, "budget", ..] => *method != Method::GET && *method != Method::HEAD,
["", "api", "usage", "today", "continue"] => *method != Method::GET && *method != Method::HEAD,
// Changing a choice a bot made is the person's call
["", "api", "messages", _, "decisions", ..] => *method != Method::GET && *method != Method::HEAD,
@@ -963,6 +966,12 @@ mod tests {
assert!(person_only(&post, "/api/usage/today/continue"));
assert!(person_only(&put, "/api/usage/today/continue/"));
assert!(!person_only(&get, "/api/usage/today"));
+ // G2: a bot's monthly budget
+ assert!(person_only(&post, "/api/kwants/k1/budget"));
+ assert!(person_only(&post, "/api/kwants/k1/budget/continue"));
+ assert!(person_only(&Method::DELETE, "/api/kwants/k1/budget/continue"));
+ assert!(!person_only(&get, "/api/kwants/k1/budget"));
+ assert!(!person_only(&get, "/api/usage/budgets"));
// 0.7.4: connected coding agents are made and revoked by the person only; the agent
// endpoint itself checks its own token instead
assert!(person_only(&get, "/api/agent-connections"));
diff --git a/src/server/bot_budget.rs b/src/server/bot_budget.rs
new file mode 100644
index 00000000..1e5d1089
--- /dev/null
+++ b/src/server/bot_budget.rs
@@ -0,0 +1,667 @@
+//! G2 · Bot budget: a person-only monthly budget per bot, in fresh tokens and/or dollars (see
+//! `release-090/g2-contract.md`).
+//!
+//! - **Counting** reuses the daily spending stop's booking: [`super::spend_stop::book_turn`]
+//! books one turn's numbers into the space's day and the bot's day ([`book`]), so there is one
+//! calculation of a turn's fresh tokens and cost, not two.
+//! - **The month** is the calendar month in the person's time zone (the daily stop's setting).
+//! - **The check** ([`gate`]) runs before a turn starts, right after the daily stop's, in
+//! `routes::turn_once`; the running turn always finishes. At 100% the bot is *paused*: new turns
+//! are held (parked with reason `bot_budget`, released by Continue, a raise or the new month),
+//! routines collapse to one late run, missions and AutoFix skip (see
+//! [`super::spend_stop::is_stop_error`]). Other bots are not affected.
+//! - **At 80%** one note in the bot's 1:1, once per budget.
+//! - Only the person sets, raises, continues or pauses again: the routes are in
+//! `auth::person_only`, and the budget lives in its own table, never in `settings`.
+
+use super::routes::TurnScope;
+use super::spaces::Scope;
+use super::AppState;
+use crate::db::models::{Kwant, MessageExtra, NewMessage};
+use axum::{
+ extract::{Path, State},
+ http::StatusCode,
+ response::{IntoResponse, Response},
+ Json,
+};
+use chrono::{DateTime, Datelike, NaiveDate, NaiveTime, Utc};
+use serde::{Deserialize, Serialize};
+use serde_json::{json, Value};
+
+/// The start of the error a held turn returns, the parked reason, and H3's `reason_code`.
+pub const REASON: &str = "bot_budget";
+/// The meta kind of the stop notice and of the Needs-you item.
+pub const STOPPED_KIND: &str = "bot_budget_stopped";
+const WARN_AT: f64 = 80.0;
+
+/// A bot's month against its budget: the body of `GET /api/kwants/:id/budget`.
+#[derive(Debug, Clone, Serialize, PartialEq)]
+pub struct Budget {
+ pub kwant_id: String,
+ pub kwant_name: String,
+ /// `YYYY-MM` in `timezone`.
+ pub month: String,
+ pub timezone: String,
+ pub used_tokens: u64,
+ pub used_usd: f64,
+ pub today_tokens: u64,
+ /// 0 when off.
+ pub budget_tokens: u64,
+ /// 0 when off.
+ pub budget_usd: f64,
+ /// The higher of the set limits' percentages; 0 when off.
+ pub percent: f64,
+ /// The limit at 100%: "tokens", "usd" or null.
+ pub over: Option<&'static str>,
+ /// "off", "under", "warn", "paused" or "continued".
+ pub state: &'static str,
+ pub paused_since: Option<DateTime<Utc>>,
+ pub continued_month: Option<String>,
+ /// Local 00:00 on the 1st of next month.
+ pub resets_at: DateTime<Utc>,
+ /// null before the bot's first booked turn this month; false when no turn reported usage.
+ pub usage_reported: Option<bool>,
+ pub some_unreported: bool,
+ /// null before the first booked turn this month; else whether any turn reported a cost.
+ pub cost_reported: Option<bool>,
+ /// Some turn booked this month didn't report usage (Codex, or a turn that ended without it):
+ /// `used_tokens` holds the daily stop's estimate for those turns, and `used_usd` has no
+ /// dollars for them. The budget and the spend are still returned and still park the bot; the
+ /// UI shows them as "about …" instead of hiding them.
+ pub estimated: bool,
+ pub engine: String,
+}
+
+/// The month `at` falls in (`YYYY-MM`), the local date, and when the month ends, in `tz`.
+pub fn month_at(tz: &str, at: DateTime<Utc>) -> (String, String, NaiveDate, DateTime<Utc>) {
+ let (zone, date, _) = super::spend_stop::day_at(tz, at);
+ let first_next = if date.month() == 12 {
+ NaiveDate::from_ymd_opt(date.year() + 1, 1, 1)
+ } else {
+ NaiveDate::from_ymd_opt(date.year(), date.month() + 1, 1)
+ }
+ .unwrap_or(date);
+ let utc = first_next.and_time(NaiveTime::MIN).and_utc();
+ let resets = if zone == "UTC" {
+ utc
+ } else {
+ crate::routines::local_instant(&zone, first_next, NaiveTime::MIN).ok().flatten().unwrap_or(utc)
+ };
+ let resets = if resets > at { resets } else { at + chrono::Duration::hours(24) };
+ (zone, date.format("%Y-%m").to_string(), date, resets)
+}
+
+/// (percent, the limit at 100%) for `used` against the set limits.
+fn percent_of(tokens: u64, usd: f64, budget_tokens: u64, budget_usd: f64) -> (f64, Option<&'static str>) {
+ let pt = if budget_tokens > 0 { tokens as f64 * 100.0 / budget_tokens as f64 } else { 0.0 };
+ let pu = if budget_usd > 0.0 { usd * 100.0 / budget_usd } else { 0.0 };
+ let over = if budget_tokens > 0 && pt >= 100.0 {
+ Some("tokens")
+ } else if budget_usd > 0.0 && pu >= 100.0 {
+ Some("usd")
+ } else {
+ None
+ };
+ (pt.max(pu), over)
+}
+
+fn budget_key(month: &str, tokens: u64, usd: f64) -> String {
+ format!("{month}|{tokens}|{usd}")
+}
+
+/// The bot's month, at the stop's clock.
+pub async fn status(state: &AppState, kwant: &Kwant) -> Budget {
+ let now = state.spend.now();
+ let (zone, month, date, resets_at) = month_at(&super::spend_stop::timezone(state).await, now);
+ let row = state.db.bot_budget(&kwant.id).await.unwrap_or_default();
+ let used = state.db.bot_use(&kwant.id, &format!("{month}-")).await.unwrap_or_default();
+ let today = state.db.bot_use(&kwant.id, &date.format("%Y-%m-%d").to_string()).await.unwrap_or_default();
+ let budget_tokens = u64::try_from(row.budget_tokens).unwrap_or(0);
+ let budget_usd = row.budget_usd.max(0.0);
+ let used_tokens = u64::try_from(used.tokens).unwrap_or(0);
+ let used_usd = used.usd.max(0.0);
+ let (percent, over) = percent_of(used_tokens, used_usd, budget_tokens, budget_usd);
+ let continued = row.continued_month.as_deref() == Some(month.as_str());
+ let state_name = if budget_tokens == 0 && budget_usd <= 0.0 {
+ "off"
+ } else if continued {
+ "continued"
+ } else if over.is_some() {
+ "paused"
+ } else if percent >= WARN_AT {
+ "warn"
+ } else {
+ "under"
+ };
+ let turns = used.reported_turns + used.unreported_turns;
+ Budget {
+ kwant_id: kwant.id.clone(),
+ kwant_name: kwant.name.clone(),
+ month: month.clone(),
+ timezone: zone,
+ used_tokens,
+ used_usd,
+ today_tokens: u64::try_from(today.tokens).unwrap_or(0),
+ budget_tokens,
+ budget_usd,
+ percent: (percent * 10.0).round() / 10.0,
+ over,
+ state: state_name,
+ paused_since: (state_name == "paused" && row.paused_month.as_deref() == Some(month.as_str())).then_some(row.paused_at).flatten(),
+ continued_month: row.continued_month,
+ resets_at,
+ usage_reported: (turns > 0).then_some(used.reported_turns > 0),
+ some_unreported: used.reported_turns > 0 && used.unreported_turns > 0,
+ cost_reported: (turns > 0).then_some(used.cost_turns > 0),
+ estimated: used.unreported_turns > 0,
+ engine: kwant.preferred_model.clone(),
+ }
+}
+
+/// Short token counts: 950, 61k, 2.04M.
+fn short(n: u64) -> String {
+ match n {
+ 0..=999 => n.to_string(),
+ 1_000..=999_999 => format!("{}k", n / 1_000),
+ _ => {
+ let m = format!("{:.2}", n as f64 / 1_000_000.0);
+ format!("{}M", m.trim_end_matches('0').trim_end_matches('.'))
+ }
+ }
+}
+
+fn month_name(month: &str) -> String {
+ NaiveDate::parse_from_str(&format!("{month}-01"), "%Y-%m-%d").map(|d| d.format("%B").to_string()).unwrap_or_else(|_| month.to_string())
+}
+
+/// "2.04M of 2M fresh tokens in November" / "$20.40 of $20.00 in November", for the limit hit
+/// (or the one with the higher percentage).
+pub fn used_of(b: &Budget) -> String {
+ let pt = if b.budget_tokens > 0 { b.used_tokens as f64 / b.budget_tokens as f64 } else { -1.0 };
+ let pu = if b.budget_usd > 0.0 { b.used_usd / b.budget_usd } else { -1.0 };
+ let usd = b.over == Some("usd") || (b.over.is_none() && pu > pt);
+ let about = if b.estimated { "about " } else { "" };
+ if usd {
+ format!("{about}${:.2} of ${:.2} in {}", b.used_usd, b.budget_usd, month_name(&b.month))
+ } else {
+ format!("{about}{} of {} fresh tokens in {}", short(b.used_tokens), short(b.budget_tokens), month_name(&b.month))
+ }
+}
+
+fn next_month_name(b: &Budget) -> String {
+ b.resets_at.format("%B").to_string()
+}
+
+pub fn stop_text(b: &Budget) -> String {
+ format!(
+ "{} stopped at its monthly budget. It finished what it was doing and won't start anything new until you raise the budget, continue, or {} starts.",
+ b.kwant_name,
+ next_month_name(b)
+ )
+}
+
+fn meta(kind: &str, b: &Budget) -> Value {
+ json!({
+ "kind": kind,
+ "kwant_id": b.kwant_id,
+ "kwant_name": b.kwant_name,
+ "month": b.month,
+ "over": b.over,
+ "percent": b.percent,
+ "used_tokens": b.used_tokens,
+ "budget_tokens": b.budget_tokens,
+ "used_usd": b.used_usd,
+ "budget_usd": b.budget_usd,
+ "resets_at": b.resets_at,
+ "paused_since": b.paused_since,
+ "estimated": b.estimated,
+ "detail": used_of(b),
+ })
+}
+
+/// The error a held turn returns; starts with [`REASON`].
+fn stop_error(b: &Budget) -> String {
+ format!(
+ "{REASON}: {} is paused at its monthly budget (used {}); it resumes at {} or when the person raises or continues it",
+ b.kwant_name,
+ used_of(b),
+ b.resets_at.to_rfc3339()
+ )
+}
+
+/// Whether a turn's error is the bot budget's hold.
+pub fn is_budget_error(err: &str) -> bool {
+ err.trim_start().starts_with(REASON)
+}
+
+/// Posts a system line in the bot's 1:1 (outside any turn).
+async fn post_direct(state: &AppState, kwant: &Kwant, text: String, meta: Value) {
+ let msg = NewMessage {
+ channel_id: None,
+ direct_kwant_id: Some(kwant.id.clone()),
+ sender_role: "system".into(),
+ sender_id: "kwnt".into(),
+ text,
+ reasoning_content: None,
+ tool_calls: None,
+ tokens_used: 0,
+ };
+ match state.db.insert_message_with(&msg, &MessageExtra { thread_id: None, meta: Some(meta) }).await {
+ Ok(saved) => {
+ let _ = state.event_sender.send(crate::drivers::events::RuntimeEvent::MessageAdded { message: serde_json::to_value(&saved).unwrap_or_default() });
+ }
+ Err(e) => tracing::warn!("could not post the budget note: {e}"),
+ }
+}
+
+/// Notice key for the stop notice in one chat during one pause episode.
+fn chat_key(context: &str, since: Option<DateTime<Utc>>) -> String {
+ format!("chat:{context}:{}", since.map(|t| t.timestamp()).unwrap_or_default())
+}
+
+/// The pause episode started: the stop notice in the bot's 1:1 and one notification.
+async fn announce_pause(state: &AppState, kwant: &Kwant, b: &Budget) {
+ tracing::info!(kwant = %kwant.id, month = %b.month, tokens = b.used_tokens, usd = b.used_usd, "bot paused at its monthly budget");
+ let _ = state.db.first_bot_budget_notice(&b.month, &chat_key(&kwant.id, b.paused_since)).await;
+ post_direct(state, kwant, stop_text(b), meta(STOPPED_KIND, b)).await;
+ let n = super::continuity::Notification {
+ kind: super::spend_stop::REASON,
+ kwant_id: kwant.id.clone(),
+ kwant_name: kwant.name.clone(),
+ channel_id: None,
+ // The stop notice is in the bot's direct chat, so a tap opens that (0.8.1 F6 fields)
+ thread_id: None,
+ card_id: None,
+ title: format!("{} stopped at its monthly budget", kwant.name),
+ body: format!("Used {}. Open to raise the budget or continue this month.", used_of(b)),
+ };
+ let space = state.db.space_of_kwant(&kwant.id).await.ok().flatten();
+ super::continuity::notify_held(state, n, space.as_ref(), false).await;
+}
+
+/// Starts the pause episode if it hasn't started (once); returns the status with `paused_since`.
+async fn ensure_paused(state: &AppState, kwant: &Kwant, mut b: Budget) -> Budget {
+ let now = state.spend.now();
+ if state.db.start_bot_pause(&kwant.id, &b.month, now).await.unwrap_or(false) {
+ b.paused_since = Some(now);
+ let _ = state.db.mark_bot_warned(&kwant.id, &budget_key(&b.month, b.budget_tokens, b.budget_usd)).await;
+ announce_pause(state, kwant, &b).await;
+ } else if b.paused_since.is_none() {
+ b.paused_since = state.db.bot_budget(&kwant.id).await.ok().and_then(|r| r.paused_at);
+ }
+ b
+}
+
+/// Books one finished turn for `kwant_id` (called by `spend_stop::book_turn` with the same
+/// numbers it books into the day) and moves the budget's state: the 80% note when this turn
+/// crossed 80%, the pause when it reached 100% (the turn itself already finished).
+pub async fn book(state: &AppState, kwant_id: &str, fresh_tokens: u64, usd: f64, reported: bool) {
+ if fresh_tokens == 0 && usd <= 0.0 {
+ return;
+ }
+ let now = state.spend.now();
+ let (_, month, date, _) = month_at(&super::spend_stop::timezone(state).await, now);
+ let day = date.format("%Y-%m-%d").to_string();
+ if let Err(e) = state.db.add_bot_spend(&day, kwant_id, fresh_tokens, usd, reported).await {
+ tracing::warn!("could not book the bot's spending: {e}");
+ return;
+ }
+ if state.db.first_bot_budget_notice(&month, &format!("prune:{day}")).await.unwrap_or(false) {
+ let _ = state.db.prune_bot_spend(date).await;
+ }
+ let Ok(Some(kwant)) = state.db.get_kwant(kwant_id).await else {
+ return;
+ };
+ let after = status(state, &kwant).await;
+ if after.state == "off" || after.state == "continued" {
+ return;
+ }
+ let before_tokens = after.used_tokens.saturating_sub(fresh_tokens);
+ let before_usd = (after.used_usd - usd).max(0.0);
+ let (before, _) = percent_of(before_tokens, before_usd, after.budget_tokens, after.budget_usd);
+ if after.state == "paused" {
+ ensure_paused(state, &kwant, after).await;
+ } else if after.state == "warn" && before < WARN_AT {
+ let key = budget_key(&after.month, after.budget_tokens, after.budget_usd);
+ if state.db.mark_bot_warned(&kwant.id, &key).await.unwrap_or(false) {
+ let text = format!(
+ "{} has used 80% of its {} budget. At 100% it stops starting new work.",
+ kwant.name,
+ month_name(&after.month)
+ );
+ post_direct(state, &kwant, text, meta("bot_budget_warn", &after)).await;
+ }
+ }
+}
+
+/// Before a turn starts (`routes::turn_once`, after the daily stop's gate): `Err` when the bot is
+/// paused at its budget. A turn that can wait (`parkable`: saved, not a retry, a check or a
+/// discussion round) is parked until the bot can start new work again; unless `quiet`, each chat
+/// gets the stop notice once per pause.
+pub(super) async fn gate(
+ scope: &TurnScope,
+ speaker: &Kwant,
+ prompt: &str,
+ quiet: bool,
+ parkable: bool,
+ delegation_id: Option<String>,
+) -> Result<(), String> {
+ let b = status(&scope.state, speaker).await;
+ if b.state != "paused" {
+ return Ok(());
+ }
+ let b = ensure_paused(&scope.state, speaker, b).await;
+ let context = scope.context_id(speaker);
+ tracing::info!(context = %context, kwant = %speaker.id, month = %b.month, "bot budget: turn held");
+ let held = if parkable && !quiet {
+ super::parked::park_for(scope, speaker, prompt, false, delegation_id, Some(b.resets_at), "bot_budget").await
+ } else {
+ None
+ };
+ if !quiet && scope.state.db.first_bot_budget_notice(&b.month, &chat_key(&context, b.paused_since)).await.unwrap_or(false) {
+ let mut m = meta(STOPPED_KIND, &b);
+ m["held"] = json!(held.is_some());
+ if let Some(saved) = scope.save(&scope.message("system", "kwnt", stop_text(&b)), Some(m)).await {
+ let _ = scope.state.event_sender.send(crate::drivers::events::RuntimeEvent::MessageAdded { message: serde_json::to_value(&saved).unwrap_or_default() });
+ }
+ }
+ Err(stop_error(&b))
+}
+
+/// For routines before they start: `Some(reason)` while `kwant_id` is paused at its budget.
+pub async fn held(state: &AppState, kwant_id: &str) -> Option<String> {
+ let kwant = state.db.get_kwant(kwant_id).await.ok().flatten()?;
+ let b = status(state, &kwant).await;
+ if b.state != "paused" {
+ return None;
+ }
+ let b = ensure_paused(state, &kwant, b).await;
+ Some(stop_error(&b))
+}
+
+/// H4: when the bot was paused at its budget (`None` when it isn't).
+pub async fn paused_since(state: &AppState, kwant_id: &str) -> Option<DateTime<Utc>> {
+ let kwant = state.db.get_kwant(kwant_id).await.ok().flatten()?;
+ let b = status(state, &kwant).await;
+ (b.state == "paused").then_some(b.paused_since).flatten()
+}
+
+/// H3: the reason code new work for the bot waits on (`Some("bot_budget")` while paused).
+pub async fn hold_reason(state: &AppState, kwant_id: &str) -> Option<&'static str> {
+ let kwant = state.db.get_kwant(kwant_id).await.ok().flatten()?;
+ (status(state, &kwant).await.state == "paused").then_some(REASON)
+}
+
+/// The bot can start new work again (raised, continued, budget off, or a new month): ends the
+/// pause, posts `card` in its 1:1, and starts what it held: parked turns oldest first, and each
+/// held routine once, marked as late.
+pub async fn release(state: &AppState, kwant: &Kwant, card: Option<(String, &str)>) {
+ let b = status(state, kwant).await;
+ if b.state == "paused" {
+ return;
+ }
+ let was_paused = state.db.end_bot_pause(&kwant.id).await.unwrap_or(false);
+ if let (true, Some((text, kind))) = (was_paused, card) {
+ post_direct(state, kwant, text, meta(kind, &b)).await;
+ }
+ let parks = state.db.release_budget_parks(&kwant.id, Utc::now()).await.unwrap_or(0);
+ if parks > 0 {
+ state.scheduler_wake.notify_one();
+ }
+ let routines = state.db.take_budget_routines(&kwant.id).await.unwrap_or_default();
+ let note = format!("Ran late: {} was paused at its monthly budget.", kwant.name);
+ for id in &routines {
+ if let Ok(Some(r)) = state.db.get_routine(id).await {
+ if r.enabled {
+ super::scheduler::start_run_noted(state, r, "schedule", Some(&note)).await;
+ }
+ }
+ }
+ if was_paused || parks > 0 || !routines.is_empty() {
+ tracing::info!(kwant = %kwant.id, parks, routines = routines.len(), "bot budget released");
+ }
+}
+
+/// Scheduler tick: releases bots whose pause ended on its own (the new month).
+pub async fn release_due(state: &AppState) {
+ let Ok(rows) = state.db.paused_or_holding_bots().await else {
+ return;
+ };
+ for id in rows {
+ if let Ok(Some(k)) = state.db.get_kwant(&id).await {
+ let card = format!("{} can start new work again.", k.name);
+ release(state, &k, Some((card, "bot_budget_resumed"))).await;
+ }
+ }
+}
+
+/// Needs you: one item per bot paused at its budget, in `space`.
+pub async fn needs_you_items(state: &AppState, kwants: &[Kwant]) -> Vec<Value> {
+ let mut out = Vec::new();
+ for k in kwants {
+ let b = status(state, k).await;
+ if b.state != "paused" {
+ continue;
+ }
+ let mut item = meta(STOPPED_KIND, &b);
+ item["id"] = json!(format!("{STOPPED_KIND}:{}:{}", k.id, b.month));
+ item["text"] = json!(stop_text(&b));
+ item["continue_url"] = json!(format!("/api/kwants/{}/budget/continue", k.id));
+ item["raise_url"] = json!(format!("/api/kwants/{}/budget", k.id));
+ out.push(item);
+ }
+ out
+}
+
+fn err(code: StatusCode, msg: impl Into<String>) -> Response {
+ (code, Json(json!({ "error": msg.into() }))).into_response()
+}
+
+#[allow(clippy::result_large_err)]
+async fn kwant_or_404(state: &AppState, id: &str) -> Result<Kwant, Response> {
+ match state.db.get_kwant(id).await {
+ Ok(Some(k)) => Ok(k),
+ Ok(None) => Err(err(StatusCode::NOT_FOUND, "no such bot")),
+ Err(_) => Err(err(StatusCode::INTERNAL_SERVER_ERROR, "could not load the bot")),
+ }
+}
+
+/// `GET /api/kwants/:id/budget`.
+pub async fn get_budget(State(state): State<AppState>, Path(id): Path<String>) -> Response {
+ match kwant_or_404(&state, &id).await {
+ Ok(k) => Json(status(&state, &k).await).into_response(),
+ Err(r) => r,
+ }
+}
+
+#[derive(Debug, Deserialize)]
+pub struct BudgetBody {
+ /// null or 0 = off; left out = unchanged.
+ #[serde(default, deserialize_with = "some_value")]
+ pub budget_tokens: Option<Option<f64>>,
+ #[serde(default, deserialize_with = "some_value")]
+ pub budget_usd: Option<Option<f64>>,
+}
+
+/// Tells a field set to null (`Some(None)`) from one left out (`None`).
+fn some_value<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<Option<f64>>, D::Error> {
+ Option::<f64>::deserialize(d).map(Some)
+}
+
+/// The limits a body asks for, validated: (tokens, usd).
+pub fn validate(body: &BudgetBody, current: (u64, f64)) -> Result<(u64, f64), String> {
+ let tokens = match body.budget_tokens {
+ None => current.0,
+ Some(None) => 0,
+ Some(Some(v)) if !v.is_finite() || v < 0.0 || v.fract() != 0.0 => return Err("budget_tokens must be a whole number of tokens, or null".into()),
+ Some(Some(v)) if v > super::spend_stop::MAX_TOKENS as f64 => return Err("At most 10 billion tokens a month.".into()),
+ Some(Some(v)) => v as u64,
+ };
+ let usd = match body.budget_usd {
+ None => current.1,
+ Some(None) => 0.0,
+ Some(Some(v)) if !v.is_finite() || v < 0.0 => return Err("budget_usd must be dollars, or null".into()),
+ Some(Some(v)) if v > super::spend_stop::MAX_USD => return Err("At most $100,000 a month.".into()),
+ Some(Some(v)) => (v * 100.0).round() / 100.0,
+ };
+ Ok((tokens, usd))
+}
+
+/// `POST /api/kwants/:id/budget` (person only): sets the limits.
+pub async fn set_budget(
+ State(state): State<AppState>,
+ Path(id): Path<String>,
+ body: Result<Json<BudgetBody>, axum::extract::rejection::JsonRejection>,
+) -> Response {
+ let Ok(Json(body)) = body else {
+ return err(StatusCode::BAD_REQUEST, "expected {budget_tokens, budget_usd}");
+ };
+ let kwant = match kwant_or_404(&state, &id).await {
+ Ok(k) => k,
+ Err(r) => return r,
+ };
+ let before = status(&state, &kwant).await;
+ let (tokens, usd) = match validate(&body, (before.budget_tokens, before.budget_usd)) {
+ Ok(v) => v,
+ Err(e) => return err(StatusCode::BAD_REQUEST, e),
+ };
+ if let Err(e) = state.db.set_bot_budget(&kwant.id, i64::try_from(tokens).unwrap_or(i64::MAX), usd).await {
+ tracing::warn!("could not save the bot budget: {e}");
+ return err(StatusCode::INTERNAL_SERVER_ERROR, "Couldn't save the budget. Try again.");
+ }
+ let after = status(&state, &kwant).await;
+ // A save that leaves use already at or past 80% doesn't send the 80% note for the new budget
+ if after.percent >= WARN_AT {
+ let _ = state.db.mark_bot_warned(&kwant.id, &budget_key(&after.month, after.budget_tokens, after.budget_usd)).await;
+ }
+ tracing::info!(kwant = %kwant.id, tokens, usd, state = after.state, "bot budget saved");
+ let after = if after.state == "paused" {
+ ensure_paused(&state, &kwant, after).await
+ } else {
+ release(&state, &kwant, Some((format!("{} can start new work again.", kwant.name), "bot_budget_resumed"))).await;
+ status(&state, &kwant).await
+ };
+ Json(after).into_response()
+}
+
+/// `POST /api/kwants/:id/budget/continue` (person only): ignores the budget until the month ends.
+pub async fn continue_month(State(state): State<AppState>, Path(id): Path<String>) -> Response {
+ let kwant = match kwant_or_404(&state, &id).await {
+ Ok(k) => k,
+ Err(r) => return r,
+ };
+ let b = status(&state, &kwant).await;
+ if b.state == "off" {
+ return err(StatusCode::CONFLICT, "this bot has no budget");
+ }
+ if let Err(e) = state.db.set_bot_budget_continued(&kwant.id, Some(&b.month)).await {
+ tracing::warn!("could not continue the bot budget: {e}");
+ return err(StatusCode::INTERNAL_SERVER_ERROR, "Couldn't continue. Try again.");
+ }
+ let text = format!(
+ "Continued for {}. {} can start new work again; the budget applies again on {}.",
+ month_name(&b.month),
+ kwant.name,
+ b.resets_at.format("%b %-d")
+ );
+ release(&state, &kwant, Some((text, "bot_budget_continued"))).await;
+ tracing::info!(kwant = %kwant.id, month = %b.month, "bot budget continued for the month");
+ Json(status(&state, &kwant).await).into_response()
+}
+
+/// `DELETE /api/kwants/:id/budget/continue` (person only): pause at the budget again.
+pub async fn pause_again(State(state): State<AppState>, Path(id): Path<String>) -> Response {
+ let kwant = match kwant_or_404(&state, &id).await {
+ Ok(k) => k,
+ Err(r) => return r,
+ };
+ if let Err(e) = state.db.set_bot_budget_continued(&kwant.id, None).await {
+ tracing::warn!("could not undo continue: {e}");
+ return err(StatusCode::INTERNAL_SERVER_ERROR, "could not save");
+ }
+ let b = status(&state, &kwant).await;
+ let b = if b.state == "paused" { ensure_paused(&state, &kwant, b).await } else { b };
+ Json(b).into_response()
+}
+
+/// `GET /api/usage/budgets`: every bot in the space, paused first, then by percent, then name.
+pub async fn list_budgets(State(state): State<AppState>, Scope(space): Scope) -> Response {
+ let Ok(kwants) = state.db.list_kwants(&space).await else {
+ return err(StatusCode::INTERNAL_SERVER_ERROR, "could not load the bots");
+ };
+ let mut bots = Vec::with_capacity(kwants.len());
+ for k in &kwants {
+ bots.push(status(&state, k).await);
+ }
+ sort_for_overview(&mut bots);
+ let now = state.spend.now();
+ let (zone, month, _, resets_at) = month_at(&super::spend_stop::timezone(&state).await, now);
+ Json(json!({ "month": month, "timezone": zone, "resets_at": resets_at, "bots": bots })).into_response()
+}
+
+/// H5 order: paused first, then percent high to low (bots with a budget), then the rest by name.
+pub fn sort_for_overview(bots: &mut [Budget]) {
+ bots.sort_by(|a, b| {
+ let rank = |x: &Budget| match x.state {
+ "paused" => 0,
+ "off" => 2,
+ _ => 1,
+ };
+ rank(a)
+ .cmp(&rank(b))
+ .then(b.percent.partial_cmp(&a.percent).unwrap_or(std::cmp::Ordering::Equal))
+ .then_with(|| a.kwant_name.to_lowercase().cmp(&b.kwant_name.to_lowercase()))
+ });
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn at(s: &str) -> DateTime<Utc> {
+ DateTime::parse_from_rfc3339(s).unwrap().with_timezone(&Utc)
+ }
+
+ #[test]
+ fn month_follows_the_zone() {
+ let (zone, month, _, resets) = month_at("Europe/Ljubljana", at("2026-11-30T23:30:00Z"));
+ assert_eq!((zone.as_str(), month.as_str()), ("Europe/Ljubljana", "2026-12"));
+ assert_eq!(resets, at("2026-12-31T23:00:00Z"));
+ let (zone, month, _, resets) = month_at("", at("2026-12-31T23:59:00Z"));
+ assert_eq!((zone.as_str(), month.as_str(), resets), ("UTC", "2026-12", at("2027-01-01T00:00:00Z")));
+ }
+
+ #[test]
+ fn percent_and_over() {
+ assert_eq!(percent_of(1_600, 0.0, 2_000, 0.0), (80.0, None));
+ assert_eq!(percent_of(2_040, 0.0, 2_000, 0.0).1, Some("tokens"));
+ assert_eq!(percent_of(10, 20.0, 2_000, 20.0), (100.0, Some("usd")));
+ assert_eq!(percent_of(99, 99.0, 0, 0.0), (0.0, None));
+ }
+
+ #[test]
+ fn validates_limits() {
+ let body = |t: Option<Option<f64>>, u: Option<Option<f64>>| BudgetBody { budget_tokens: t, budget_usd: u };
+ assert_eq!(validate(&body(Some(Some(2_000_000.0)), None), (0, 5.0)), Ok((2_000_000, 5.0)));
+ assert_eq!(validate(&body(Some(None), Some(Some(2.505))), (9, 5.0)), Ok((0, 2.51)));
+ assert!(validate(&body(Some(Some(-1.0)), None), (0, 0.0)).is_err());
+ assert!(validate(&body(Some(Some(1.5)), None), (0, 0.0)).is_err());
+ assert!(validate(&body(Some(Some(10_000_000_001.0)), None), (0, 0.0)).is_err());
+ assert!(validate(&body(None, Some(Some(100_000.01))), (0, 0.0)).is_err());
+ assert!(validate(&body(None, Some(Some(f64::NAN))), (0, 0.0)).is_err());
+ }
+
+ #[test]
+ fn short_counts() {
+ assert_eq!(short(2_040_000), "2.04M");
+ assert_eq!(short(2_000_000), "2M");
+ assert_eq!(short(61_000), "61k");
+ }
+
+ #[test]
+ fn budget_errors_are_stop_errors() {
+ assert!(is_budget_error("bot_budget: Pixel is paused"));
+ assert!(super::super::spend_stop::is_stop_error("bot_budget: Pixel is paused"));
+ assert!(!is_budget_error("spend_stopped: today's"));
+ }
+}
diff --git a/src/server/delegation.rs b/src/server/delegation.rs
index 948b3235..eb402441 100644
--- a/src/server/delegation.rs
+++ b/src/server/delegation.rs
@@ -567,17 +567,17 @@ async fn run(state: AppState, job: super::turns::JobGuard, d: Delegation, lead:
// limit resets
if outcome.is_err() {
if let Ok(Some(p)) = state.db.parked_for_delegation(&d.id).await {
+ let text = if p.reason == "bot_budget" {
+ format!("{} is paused at its monthly budget; the hand-off “{}” runs when it resumes.", specialist.name, d.title)
+ } else {
+ format!("{} hit a usage limit on “{}”. {}", specialist.name, d.title, super::parked::retry_line(p.retry_at, Utc::now()))
+ };
post_to_origin(
&state,
&d,
"system",
"kwnt",
- format!(
- "{} hit a usage limit on “{}”. {}",
- specialist.name,
- d.title,
- super::parked::retry_line(p.retry_at, Utc::now())
- ),
+ text,
meta("delegation_started", &d, &specialist.name),
)
.await;
@@ -1407,6 +1407,11 @@ pub async fn interrupt_open(state: &AppState) {
/// The retry of a delegation a usage limit stopped (see [`super::parked`]).
pub async fn retry_parked(state: &AppState, delegation_id: &str) -> bool {
+ retry_parked_for(state, delegation_id, false).await
+}
+
+/// [`retry_parked`]; `budget`: it was held at the specialist's monthly budget (G2), not a usage limit.
+pub async fn retry_parked_for(state: &AppState, delegation_id: &str, budget: bool) -> bool {
let Ok(Some(d)) = state.db.get_delegation(delegation_id).await else {
return false;
};
@@ -1419,7 +1424,11 @@ pub async fn retry_parked(state: &AppState, delegation_id: &str) -> bool {
&d,
"system",
"kwnt",
- format!("The usage limit has reset: {specialist} is retrying “{}” once.", d.title),
+ if budget {
+ format!("{specialist} can start new work again: running the hand-off “{}”.", d.title)
+ } else {
+ format!("The usage limit has reset: {specialist} is retrying “{}” once.", d.title)
+ },
meta("delegation_started", &d, &specialist),
)
.await;
diff --git a/src/server/mod.rs b/src/server/mod.rs
index f07cc1eb..b8ee7f7a 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -19,6 +19,7 @@ pub mod goals_remediation;
pub mod model_usage;
pub mod budget;
pub mod spend_stop;
+pub mod bot_budget;
pub mod scheduler;
pub mod turns;
pub mod delegation;
@@ -438,6 +439,10 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/usage/daily", get(model_usage::get_daily))
.route("/api/usage/today", get(spend_stop::get_today))
.route("/api/usage/today/continue", post(spend_stop::continue_today))
+ // 0.9.0 G2: per-bot monthly budgets (writes are person-only, see `auth::person_only`)
+ .route("/api/kwants/:id/budget", get(bot_budget::get_budget).post(bot_budget::set_budget))
+ .route("/api/kwants/:id/budget/continue", post(bot_budget::continue_month).delete(bot_budget::pause_again))
+ .route("/api/usage/budgets", get(bot_budget::list_budgets))
.route("/api/chains/:id/continue", post(budget::continue_chain))
.route(
"/api/kwants/:id/memories/:mid",
diff --git a/src/server/parked.rs b/src/server/parked.rs
index 1b163918..87251457 100644
--- a/src/server/parked.rs
+++ b/src/server/parked.rs
@@ -26,6 +26,20 @@ pub(super) async fn park(
no_park: bool,
delegation_id: Option<String>,
retry_at: Option<DateTime<Utc>>,
+) -> Option<String> {
+ park_for(scope, kwant, prompt, no_park, delegation_id, retry_at, "usage_limit").await
+}
+
+/// [`park`], with why it waits: "usage_limit" or "bot_budget" (G2, see
+/// [`super::bot_budget`]). Budget holds keep every message in the chat (appended, oldest first).
+pub(super) async fn park_for(
+ scope: &TurnScope,
+ kwant: &Kwant,
+ prompt: &str,
+ no_park: bool,
+ delegation_id: Option<String>,
+ retry_at: Option<DateTime<Utc>>,
+ reason: &'static str,
) -> Option<String> {
if no_park {
return None;
@@ -47,17 +61,35 @@ pub(super) async fn park(
depth: scope.delegation_depth,
prompt: prompt.to_string(),
retry_at: at,
+ reason,
})
.await
.ok()?;
+ let budget = reason == "bot_budget";
let Some(row) = row else {
- return Some("⏳ A retry for this chat is already set for when the limit resets.".into());
+ return Some(if budget {
+ "⏳ Held with the earlier message: it runs when the bot can start new work again.".into()
+ } else {
+ "⏳ A retry for this chat is already set for when the limit resets.".into()
+ });
};
+ if budget {
+ tracing::info!(kwant = %kwant.id, parked = %row.id, "turn held: the bot is paused at its monthly budget");
+ scope.state.scheduler_wake.notify_one();
+ return Some(format!("⏳ Held: it runs when {} can start new work again.", kwant.name));
+ }
tracing::info!(kwant = %kwant.id, parked = %row.id, retry_at = %at, "turn parked until the usage limit resets");
scope.state.scheduler_wake.notify_one();
Some(retry_line(at, Utc::now()))
}
+/// The prompt a held turn gets once its bot can start new work again (G2).
+pub fn budget_retry_prompt(original: &str) -> String {
+ format!(
+ "[kwnt held this while you were paused at your monthly budget; the person has raised or continued it, or a new month started. Answer it now]\n\n{original}"
+ )
+}
+
/// The prompt a retried turn gets: the original request, marked as a retry.
pub fn retry_prompt(original: &str) -> String {
format!(
@@ -94,7 +126,7 @@ pub async fn no_tools_turn_for_tests(state: &AppState, kwant_id: &str, prompt: &
async fn retry(state: &AppState, p: &ParkedTurn) -> bool {
if let Some(d) = &p.delegation_id {
- return super::delegation::retry_parked(state, d).await;
+ return super::delegation::retry_parked_for(state, d, p.reason == "bot_budget").await;
}
let Ok(Some(kwant)) = state.db.get_kwant(&p.kwant_id).await else {
return false;
@@ -104,9 +136,15 @@ async fn retry(state: &AppState, p: &ParkedTurn) -> bool {
let Ok(scope) = scope_for(state, &kwant, p.channel_id.clone(), p.thread_id.clone(), &job, p.depth).await else {
return false;
};
- let note = scope.message("system", "kwnt", format!("The usage limit has reset: retrying {}'s turn once.", kwant.name));
+ let budget = p.reason == "bot_budget";
+ let text = if budget {
+ format!("{} can start new work again: running the message it held.", kwant.name)
+ } else {
+ format!("The usage limit has reset: retrying {}'s turn once.", kwant.name)
+ };
+ let note = scope.message("system", "kwnt", text);
scope.save(&note, None).await;
- let prompt = retry_prompt(&p.prompt);
+ let prompt = if budget { budget_retry_prompt(&p.prompt) } else { retry_prompt(&p.prompt) };
tracing::info!(kwant = %kwant.id, parked = %p.id, "retrying a parked turn");
tokio::spawn(async move {
let _job = job;
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 05f55ac6..770d5dbc 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -2199,6 +2199,11 @@ pub(super) async fn turn_once(
// tasks never do), so this is how the stop knows it held the person's message
let person_turn = opts.nav_prompt.is_some();
super::spend_stop::gate(scope, target_kwant, quiet_stop, person_turn).await?;
+ // Then the bot's own monthly budget (G2): daily stop, mission budget (checked by the mission
+ // runner before it asks for a turn), bot budget; the first one hit holds the turn. A turn that
+ // can wait is parked until the bot can start new work again
+ let budget_parkable = !opts.unsaved && !opts.no_park() && opts.purpose.is_none();
+ super::bot_budget::gate(scope, target_kwant, &prompt, quiet_stop, budget_parkable, opts.delegation_id.clone()).await?;
let turns = &scope.state.turns;
turns.add_keys(&scope.job_id, std::slice::from_ref(&tag.turn_id));
// Sends turn_ended even if this future is dropped, queued or mid-turn
@@ -2226,6 +2231,7 @@ pub(super) async fn turn_once(
},
};
super::spend_stop::gate(scope, target_kwant, quiet_stop, person_turn).await?;
+ super::bot_budget::gate(scope, target_kwant, &prompt, quiet_stop, budget_parkable, opts.delegation_id.clone()).await?;
turns.set_turn(super::turns::ActiveTurn {
turn_id: tag.turn_id.clone(),
kwant_id: tag.kwant_id.clone(),
@@ -3398,7 +3404,8 @@ async fn run_kwant_turn_inner(
// CLI and the API engines stream it as they go): it counts toward today's spending stop.
// Engines that report usage only at the end add nothing here.
if cancelled || gave_up.is_some() || !matches!(driver_result, Some(Ok(Ok(_)))) {
- super::spend_stop::book(state, state.turns.usage_seen(&tag.turn_id), None).await;
+ // (and toward the bot's monthly budget, G2; usage the engine streamed is reported usage)
+ super::spend_stop::book_turn(state, &target_kwant.id, state.turns.usage_seen(&tag.turn_id), None, true).await;
}
let mcp_records = mcp_ctx.map(|c| c.take_records()).filter(|r| !r.is_empty());
// Ends what still runs; kept on the reply so the steps show after a reload
@@ -3441,7 +3448,9 @@ async fn run_kwant_turn_inner(
let fresh = output.usage.map_or(output.tokens_used as u64, |u| u.fresh());
state.turns.add_job_tokens(&scope.job_id, fresh);
// …and toward today's spending stop: every engine's fresh tokens, dollars where reported
- super::spend_stop::book(state, fresh, output.usage.and_then(|u| u.cost_usd)).await;
+ // and the bot's monthly budget (G2; one booking, the same numbers). An engine without
+ // usage (Codex) books its estimate, as an unreported turn
+ super::spend_stop::book_turn(state, &target_kwant.id, fresh, output.usage.and_then(|u| u.cost_usd), output.usage.is_some()).await;
// …and toward the task the bot holds, if any (see `super::missions`)
let turn_started_ms = chrono::Utc::now().timestamp_millis() - turn_start.elapsed().as_millis() as i64;
// (less what a task the bot handed in mid-turn already paid for)
diff --git a/src/server/scheduler.rs b/src/server/scheduler.rs
index 6af4cb67..4b899605 100644
--- a/src/server/scheduler.rs
+++ b/src/server/scheduler.rs
@@ -499,12 +499,30 @@ pub async fn run_now(State(state): State<AppState>, Path(id): Path<String>) -> R
/// Records a run and starts it in the background, or records it as skipped when the routine is
/// still running. `None` if the run couldn't be recorded.
pub async fn start_run(state: &AppState, routine: RoutineRow, trigger: &str) -> Option<RoutineRun> {
+ start_run_noted(state, routine, trigger, None).await
+}
+
+/// [`start_run`], with a note for the run's history (G2: "Ran late: … was paused at its monthly
+/// budget." on the one run a routine gets after its bot's pause ends).
+pub async fn start_run_noted(state: &AppState, routine: RoutineRow, trigger: &str, note: Option<&str>) -> Option<RoutineRun> {
// Today's spending stop holds new turns: the run is skipped, not failed (no AutoFix retry)
if let Some(why) = super::spend_stop::held(state, &routine.space_id).await {
let run = state.db.start_routine_run(&routine.id, trigger, "skipped", Some(&why)).await.ok()?;
send_run_event(state, &run);
return Some(run);
}
+ // Its bot is paused at its monthly budget (G2): held, and run once when the pause ends. Only
+ // the first held time goes in the history, so missed runs collapse into one late run
+ if let Some(why) = super::bot_budget::held(state, &routine.kwant_id).await {
+ // A scheduled time while it's already held adds nothing; Run now still gets its answer
+ let first = state.db.hold_budget_routine(&routine.id, &routine.kwant_id).await.unwrap_or(false);
+ if !first && trigger != "manual" {
+ return None;
+ }
+ let run = state.db.start_routine_run(&routine.id, trigger, "skipped", Some(&why)).await.ok()?;
+ send_run_event(state, &run);
+ return Some(run);
+ }
let claimed = state
.running_routines
.lock()
@@ -536,6 +554,9 @@ pub async fn start_run(state: &AppState, routine: RoutineRow, trigger: &str) ->
return None;
}
};
+ if let Some(note) = note {
+ let _ = state.db.set_routine_run_note(&run.id, note).await;
+ }
send_run_event(state, &run);
let state = state.clone();
let run_id = run.id.clone();
@@ -813,6 +834,8 @@ pub fn spawn(state: AppState, shutdown: CancellationToken) -> tokio::task::JoinH
loop {
tick(&state, Utc::now()).await;
super::delegation::follow_ups(&state, Utc::now()).await;
+ // G2: bots whose budget pause ended on its own (a new month) start what they held
+ super::bot_budget::release_due(&state).await;
super::parked::run_due(&state, Utc::now()).await;
super::waiting::run_due(&state, Utc::now()).await;
super::work_ahead::scan(&state, Utc::now(), false).await;
diff --git a/src/server/spend_stop.rs b/src/server/spend_stop.rs
index c2bc72e0..e3c7f814 100644
--- a/src/server/spend_stop.rs
+++ b/src/server/spend_stop.rs
@@ -108,7 +108,7 @@ pub fn day_at(tz: &str, at: DateTime<Utc>) -> (String, NaiveDate, DateTime<Utc>)
(zone.to_string(), date, ends)
}
-async fn timezone(state: &AppState) -> String {
+pub(super) async fn timezone(state: &AppState) -> String {
state.db.get_setting(super::bot_actions::TIMEZONE_SETTING).await.ok().flatten().unwrap_or_default()
}
@@ -146,9 +146,21 @@ pub async fn book(state: &AppState, fresh_tokens: u64, cost_usd: Option<f64>) {
}
}
-/// Whether a turn's error is the spending stop's (a skip, not a failure).
+/// Books one finished (or cancelled) turn of `kwant_id`: the same numbers go into today's
+/// spending (as [`book`]) and into the bot's month (G2, [`super::bot_budget::book`]), so a
+/// turn is counted once, the same way, for both. `reported`: the engine reported the usage (a
+/// Codex turn's estimate is not).
+pub async fn book_turn(state: &AppState, kwant_id: &str, fresh_tokens: u64, cost_usd: Option<f64>, reported: bool) {
+ book(state, fresh_tokens, cost_usd).await;
+ let usd = cost_usd.filter(|c| c.is_finite() && *c > 0.0).unwrap_or(0.0);
+ super::bot_budget::book(state, kwant_id, fresh_tokens, usd, reported).await;
+}
+
+/// Whether a turn's error is a spending hold, today's stop or a bot's monthly budget (G2): a
+/// skip, not a failure.
pub fn is_stop_error(err: &str) -> bool {
- err.trim_start().starts_with(REASON)
+ let e = err.trim_start();
+ e.starts_with(REASON) || super::bot_budget::is_budget_error(e)
}
/// Short token counts: 950, 12k, 1.2M.
diff --git a/src/server/waiting.rs b/src/server/waiting.rs
index 79d9f2f1..ee46c323 100644
--- a/src/server/waiting.rs
+++ b/src/server/waiting.rs
@@ -249,6 +249,9 @@ pub async fn list(State(state): State<AppState>, super::spaces::Scope(space): su
let mut items: Vec<Value> = items.into_iter().map(|(_, v)| v).collect();
// Today's spending stop holds routines, goals, missions and AutoFix: one item, first, while it
// does (its `id` names the day, so it is one item per day)
+ // Bots paused at their monthly budget (G2): one item each, after the daily stop's
+ let paused = super::bot_budget::needs_you_items(&state, &kwants).await;
+ items.splice(0..0, paused);
if let Some(stop) = super::spend_stop::needs_you_item(&state).await {
items.insert(0, stop);
}
diff --git a/tests/bot_budget_test.rs b/tests/bot_budget_test.rs
new file mode 100644
index 00000000..03a895cb
--- /dev/null
+++ b/tests/bot_budget_test.rs
@@ -0,0 +1,563 @@
+//! G2: a monthly budget per bot (release-090/g2-contract.md). The fake claude CLI from the daily
+//! spending stop's tests reports 8,710 fresh tokens and $0.42 a turn (no cost with NOCOST). The
+//! month moves on through the stop's clock seam, never by waiting. Its own test binary: it
+//! changes PATH.
+
+#[path = "common/exe.rs"]
+mod exe;
+
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use chrono::{DateTime, Utc};
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::{models::Message, Database},
+ router::LayaRouter,
+ server::{
+ bot_budget,
+ continuity::{SelfScope, TurnOrigin},
+ create_router, mcp_runtime, parked, AppState,
+ },
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use std::path::{Path, PathBuf};
+use std::sync::OnceLock;
+use std::time::Duration;
+use tower::ServiceExt;
+
+const FAKE_CLAUDE: &str = r#"#!/bin/sh
+case "$1" in
+ auth) echo '{"loggedIn":true}'; exit 0 ;;
+esac
+for a; do last="$a"; done
+# Only this turn's request counts: earlier NOCOST messages are in the history part of the prompt
+req="${last##*Current User Request:}"
+cost=',"total_cost_usd":0.42'
+case "$req" in *NOCOST*) cost="" ;; esac
+echo "{\"type\":\"result\",\"is_error\":false,\"num_turns\":1,\"result\":\"answer\"$cost,\"usage\":{\"input_tokens\":12,\"cache_creation_input_tokens\":8211,\"cache_read_input_tokens\":83544,\"output_tokens\":487},\"modelUsage\":{\"claude-opus-5-5\":{\"outputTokens\":487}}}"
+"#;
+
+const FRESH: u64 = 12 + 8_211 + 487;
+
+/// Codex reports no usage: kwant books the daily stop's estimate (reply length / 4) as an
+/// unreported turn. The reply is 400 characters, so each turn books 100 tokens.
+const FAKE_CODEX: &str = r#"#!/bin/sh
+case "$1 $2" in
+ "--version "*) echo "codex-cli 0.162.1"; exit 0 ;;
+ "login status") echo "Logged in using ChatGPT"; exit 0 ;;
+ "debug models") echo '{"models":[{"slug":"gpt-6.1-sol","display_name":"GPT-6.1 Sol","visibility":"list","priority":1}]}'; exit 0 ;;
+ "mcp list") echo '[]'; exit 0 ;;
+esac
+out=""
+prev=""
+for a in "$@"; do
+ if [ "$prev" = "-o" ]; then out="$a"; fi
+ prev="$a"
+done
+[ -n "$out" ] && printf '%0400d' 0 > "$out"
+exit 0
+"#;
+
+const CODEX_TURN: u64 = 100;
+
+fn fake_cli() {
+ static DONE: OnceLock<PathBuf> = OnceLock::new();
+ DONE.get_or_init(|| {
+ let bin = tempfile::tempdir().unwrap().keep().join("bin");
+ std::fs::create_dir_all(&bin).unwrap();
+ exe::write_executable(bin.join("claude"), FAKE_CLAUDE);
+ exe::write_executable(bin.join("codex"), FAKE_CODEX);
+ std::env::set_var("PATH", format!("{}:{}", bin.display(), std::env::var("PATH").unwrap_or_default()));
+ bin
+ });
+}
+
+async fn call_as(app: &Router, method: &str, uri: &str, body: Option<Value>, token: Option<&str>) -> (StatusCode, Value) {
+ let mut req = Request::builder().method(method).uri(uri).header("content-type", "application/json");
+ if let Some(t) = token {
+ req = req.header("authorization", format!("Bearer {t}"));
+ }
+ let body = body.map(|v| Body::from(v.to_string())).unwrap_or_else(Body::empty);
+ let resp = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();
+ let s = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (s, serde_json::from_slice(&bytes).unwrap_or_else(|_| Value::String(String::from_utf8_lossy(&bytes).into())))
+}
+
+async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
+ call_as(app, method, uri, body, None).await
+}
+
+async fn ok(app: &Router, method: &str, uri: &str, body: Option<Value>) -> Value {
+ let (s, v) = call(app, method, uri, body).await;
+ assert!(s.is_success(), "{method} {uri}: {s} {v}");
+ v
+}
+
+fn meta(m: &Message) -> Value {
+ m.meta.as_deref().and_then(|s| serde_json::from_str(s).ok()).unwrap_or(Value::Null)
+}
+
+fn at(s: &str) -> DateTime<Utc> {
+ DateTime::parse_from_rfc3339(s).unwrap().with_timezone(&Utc)
+}
+
+struct Env {
+ app: Router,
+ state: AppState,
+ channel: String,
+ ann: String,
+ bob: String,
+}
+
+/// Ann and Bob on the fake claude in channel "desk", Bob leading.
+async fn setup(dir: &Path) -> Env {
+ fake_cli();
+ let config = Config {
+ data_dir: dir.to_path_buf(),
+ laya_url: "http://127.0.0.1:9".into(),
+ browser_cdp_url: Some("http://127.0.0.1:9".into()),
+ ..Config::default()
+ };
+ let db = Database::init(dir).await.unwrap();
+ let state = AppState::new(config.clone(), db, ToolRunner::new(dir.join("workspace")), PermissionBroker::new(), LayaRouter::new(config.laya_url.clone()));
+ let app = create_router(state.clone());
+ let bot = |name: &str| {
+ json!({"name": name, "title": format!("{name} the tester"), "persona_prompt": "Test persona",
+ "avatar_sprite": "s", "driver_type": "cli", "preferred_model": "claude"})
+ };
+ let ann = ok(&app, "POST", "/api/kwants", Some(bot("Ann"))).await["id"].as_str().unwrap().to_string();
+ let bob = ok(&app, "POST", "/api/kwants", Some(bot("Bob"))).await["id"].as_str().unwrap().to_string();
+ let c = ok(&app, "POST", "/api/channels", Some(json!({"name": "desk", "lead_kwant_id": bob, "member_kwants": [ann]}))).await;
+ Env { app, state, channel: c["id"].as_str().unwrap().to_string(), ann, bob }
+}
+
+impl Env {
+ async fn say(&self, prompt: &str) {
+ ok(&self.app, "POST", "/api/chat/send", Some(json!({"channel_id": self.channel, "prompt": prompt, "sender_id": "user"}))).await;
+ }
+
+ async fn messages(&self) -> Vec<Message> {
+ self.state.db.list_messages(&self.channel, 200).await.unwrap()
+ }
+
+ async fn replies(&self, who: &str) -> usize {
+ self.messages().await.iter().filter(|m| m.sender_role == "kwant" && m.sender_id == who).count()
+ }
+
+ /// Notices of `kind` in the channel.
+ async fn notices(&self, kind: &str) -> Vec<Message> {
+ self.messages().await.into_iter().filter(|m| meta(m)["kind"] == kind).collect()
+ }
+
+ /// Notices of `kind` in Ann's 1:1.
+ async fn direct(&self, kind: &str) -> Vec<Message> {
+ self.state.db.list_messages(&self.ann, 200).await.unwrap().into_iter().filter(|m| meta(m)["kind"] == kind).collect()
+ }
+
+ async fn budget(&self, kwant: &str) -> Value {
+ ok(&self.app, "GET", &format!("/api/kwants/{kwant}/budget"), None).await
+ }
+
+ async fn set_budget(&self, kwant: &str, body: Value) -> Value {
+ ok(&self.app, "POST", &format!("/api/kwants/{kwant}/budget"), Some(body)).await
+ }
+
+ async fn wait_reply(&self, who: &str, before: usize, what: &str) {
+ for _ in 0..200 {
+ if self.replies(who).await > before {
+ // the turn is booked right after the reply is saved
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ return;
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ panic!("no reply from {who} to {what}: {:#?}", self.messages().await.iter().map(|m| (&m.sender_id, &m.text)).collect::<Vec<_>>());
+ }
+
+ /// Sends `prompt` to `who` and waits for the reply.
+ async fn turn_with(&self, who: &str, prompt: &str) {
+ let before = self.replies(who).await;
+ self.say(&format!("@{who} {prompt}")).await;
+ self.wait_reply(who, before, prompt).await;
+ }
+
+ async fn turn(&self, prompt: &str) {
+ self.turn_with("Ann", prompt).await;
+ }
+
+ /// Sends `prompt` to Ann while she's paused: saved, and no turn starts.
+ async fn held(&self, prompt: &str) {
+ let people = self.messages().await.iter().filter(|m| m.sender_role == "user").count();
+ let replies = self.replies("Ann").await;
+ self.say(&format!("@Ann {prompt}")).await;
+ tokio::time::sleep(Duration::from_millis(1500)).await;
+ assert_eq!(self.messages().await.iter().filter(|m| m.sender_role == "user").count(), people + 1, "the message is saved");
+ assert_eq!(self.replies("Ann").await, replies, "no turn while paused");
+ }
+
+ async fn budget_parks(&self) -> Vec<kwnt::db::parked::ParkedTurn> {
+ self.state.db.list_parked().await.unwrap().into_iter().filter(|p| p.reason == "bot_budget" && p.status == "pending").collect()
+ }
+
+ /// Runs the parked turns that are due now and waits for Ann's reply to the first one.
+ async fn run_parked(&self) {
+ let before = self.replies("Ann").await;
+ assert_eq!(parked::run_due(&self.state, Utc::now() + chrono::Duration::seconds(1)).await, 1, "one held turn runs");
+ self.wait_reply("Ann", before, "the held turn").await;
+ }
+
+ async fn waiting_items(&self) -> Vec<Value> {
+ let w = ok(&self.app, "GET", "/api/waiting", None).await;
+ w["items"].as_array().unwrap().iter().filter(|i| i["kind"] == "bot_budget_stopped").cloned().collect()
+ }
+}
+
+/// Counting: fresh tokens and reported dollars per bot, the same numbers the daily stop books.
+#[tokio::test]
+async fn counts_each_bots_fresh_tokens_like_the_daily_stop() {
+ let tmp = tempfile::tempdir().unwrap();
+ let env = setup(tmp.path()).await;
+ let b = env.budget(&env.ann).await;
+ assert_eq!((b["state"].as_str(), b["used_tokens"].as_u64(), b["usage_reported"].clone()), (Some("off"), Some(0), Value::Null), "{b}");
+
+ env.turn("one").await;
+ env.turn("two").await;
+ env.turn("NOCOST three").await;
+ env.turn_with("Bob", "hello").await;
+
+ let b = env.budget(&env.ann).await;
+ assert_eq!(b["used_tokens"].as_u64(), Some(3 * FRESH), "{b}");
+ assert_eq!(b["today_tokens"].as_u64(), Some(3 * FRESH));
+ assert!((b["used_usd"].as_f64().unwrap() - 0.84).abs() < 1e-9, "only reported cost counts: {b}");
+ assert_eq!((b["usage_reported"].as_bool(), b["cost_reported"].as_bool(), b["some_unreported"].as_bool()), (Some(true), Some(true), Some(false)));
+ assert_eq!(b["state"], "off", "no budget set: counted, never paused");
+ assert_eq!(b["engine"], "claude");
+ assert_eq!(env.budget(&env.bob).await["used_tokens"].as_u64(), Some(FRESH), "per bot");
+
+ // Every booked token lands in exactly one bot's day: the bots add up to the daily stop's total
+ let today = ok(&env.app, "GET", "/api/usage/today", None).await;
+ let day = today["day"].as_str().unwrap().to_string();
+ assert_eq!(today["today_tokens"].as_u64(), Some(4 * FRESH));
+ assert_eq!(env.state.db.bot_spend_day_total(&day).await.unwrap() as u64, 4 * FRESH);
+
+ let all = ok(&env.app, "GET", "/api/usage/budgets", None).await;
+ let names: Vec<&str> = all["bots"].as_array().unwrap().iter().map(|b| b["kwant_name"].as_str().unwrap()).collect();
+ assert!(names.contains(&"Ann") && names.contains(&"Bob"), "{all}");
+ assert_eq!(all["month"], b["month"]);
+}
+
+/// 80%: one note in the bot's 1:1 when a turn crosses it, never again for the same budget, and
+/// not when the person saves a budget the bot is already past 80% of.
+#[tokio::test]
+async fn warns_once_when_a_turn_crosses_80_percent() {
+ let tmp = tempfile::tempdir().unwrap();
+ let env = setup(tmp.path()).await;
+ env.state.spend.set(Some(at("2026-11-06T12:00:00Z")));
+ let budget = FRESH * 6 / 5; // one turn is 83%
+ let b = env.set_budget(&env.ann, json!({"budget_tokens": budget})).await;
+ assert_eq!((b["state"].as_str(), b["budget_tokens"].as_u64()), (Some("under"), Some(budget)), "{b}");
+
+ env.turn("first").await;
+ let b = env.budget(&env.ann).await;
+ assert_eq!(b["state"], "warn", "{b}");
+ assert_eq!(b["percent"].as_f64(), Some(83.3));
+ let warns = env.direct("bot_budget_warn").await;
+ assert_eq!(warns.len(), 1);
+ assert_eq!(warns[0].text, "Ann has used 80% of its November budget. At 100% it stops starting new work.");
+
+ // Raised, then set back and lowered: still past 80%, but no second note
+ env.set_budget(&env.ann, json!({"budget_tokens": 10 * FRESH})).await;
+ assert_eq!(env.budget(&env.ann).await["state"], "under");
+ env.set_budget(&env.ann, json!({"budget_tokens": budget})).await;
+ env.set_budget(&env.ann, json!({"budget_tokens": FRESH * 11 / 10})).await;
+ assert_eq!(env.budget(&env.ann).await["state"], "warn");
+ assert_eq!(env.direct("bot_budget_warn").await.len(), 1, "one 80% note");
+ assert!(env.direct(bot_budget::STOPPED_KIND).await.is_empty());
+}
+
+/// 100%: the turn that crosses finishes; one pause, one notice in the 1:1 and one per chat; the
+/// next message is saved and held (folded into one held turn) while other bots keep working;
+/// Continue releases it, undoing Continue pauses again, and raising the budget releases again.
+#[tokio::test]
+async fn crossing_turn_finishes_next_is_held_until_continue_or_raise() {
+ let tmp = tempfile::tempdir().unwrap();
+ let env = setup(tmp.path()).await;
+ env.state.spend.set(Some(at("2026-11-06T12:00:00Z")));
+ env.set_budget(&env.ann, json!({"budget_tokens": FRESH})).await;
+
+ env.turn("first").await; // starts under the budget, reaches it, and finishes
+ let b = env.budget(&env.ann).await;
+ assert_eq!((b["state"].as_str(), b["over"].as_str(), b["percent"].as_f64()), (Some("paused"), Some("tokens"), Some(100.0)), "{b}");
+ assert!(b["paused_since"].is_string(), "{b}");
+ assert_eq!(b["resets_at"], "2026-12-01T00:00:00Z");
+ let stops = env.direct(bot_budget::STOPPED_KIND).await;
+ assert_eq!(stops.len(), 1, "one notice when the pause starts");
+ assert_eq!(
+ stops[0].text,
+ "Ann stopped at its monthly budget. It finished what it was doing and won't start anything new until you raise the budget, continue, or December starts."
+ );
+ assert_eq!(meta(&stops[0])["detail"], "8k of 8k fresh tokens in November");
+
+ env.held("second").await;
+ env.held("third").await;
+ assert_eq!(env.notices(bot_budget::STOPPED_KIND).await.len(), 1, "one notice per chat per pause");
+ let parks = env.budget_parks().await;
+ assert_eq!(parks.len(), 1, "held messages fold into one turn: {parks:?}");
+ assert!(parks[0].prompt.contains("second") && parks[0].prompt.contains("third"), "{}", parks[0].prompt);
+ assert_eq!(parks[0].kwant_id, env.ann);
+ let items = env.waiting_items().await;
+ assert_eq!(items.len(), 1, "{items:?}");
+ assert_eq!(items[0]["continue_url"], format!("/api/kwants/{}/budget/continue", env.ann));
+ assert_eq!(env.direct(bot_budget::STOPPED_KIND).await.len(), 1, "still one pause");
+
+ // Only Ann is paused: Bob works, and the space-wide daily stop isn't involved
+ env.turn_with("Bob", "still here?").await;
+ assert_eq!(ok(&env.app, "GET", "/api/usage/today", None).await["stopped"], false);
+
+ // Continue this month
+ let b = ok(&env.app, "POST", &format!("/api/kwants/{}/budget/continue", env.ann), None).await;
+ assert_eq!((b["state"].as_str(), b["continued_month"].as_str()), (Some("continued"), Some("2026-11")), "{b}");
+ assert_eq!(env.direct("bot_budget_continued").await.len(), 1);
+ assert!(env.waiting_items().await.is_empty());
+ env.run_parked().await;
+ env.turn("fourth").await;
+
+ // Undo Continue a few minutes later: paused again, a new pause with its own notice
+ env.state.spend.set(Some(at("2026-11-06T12:05:00Z")));
+ let b = ok(&env.app, "DELETE", &format!("/api/kwants/{}/budget/continue", env.ann), None).await;
+ assert_eq!(b["state"], "paused", "{b}");
+ assert_eq!(env.direct(bot_budget::STOPPED_KIND).await.len(), 2);
+ env.held("fifth").await;
+ assert_eq!(env.notices(bot_budget::STOPPED_KIND).await.len(), 2, "the new pause notices the chat once");
+ assert_eq!(env.budget_parks().await.len(), 1);
+
+ // Raise the budget
+ let b = env.set_budget(&env.ann, json!({"budget_tokens": 10 * FRESH})).await;
+ assert_eq!(b["state"], "under", "{b}");
+ let resumed = env.direct("bot_budget_resumed").await;
+ assert_eq!(resumed.len(), 1);
+ assert_eq!(resumed[0].text, "Ann can start new work again.");
+ env.run_parked().await;
+ assert!(env.budget_parks().await.is_empty());
+}
+
+/// The USD budget counts only reported cost, and either limit pauses.
+#[tokio::test]
+async fn usd_budget_pauses_on_reported_cost() {
+ let tmp = tempfile::tempdir().unwrap();
+ let env = setup(tmp.path()).await;
+ env.set_budget(&env.ann, json!({"budget_usd": 0.5})).await;
+ env.turn("priced").await;
+ env.turn("NOCOST free").await;
+ assert_eq!(env.budget(&env.ann).await["state"], "warn");
+ env.turn("priced again").await;
+ let b = env.budget(&env.ann).await;
+ assert_eq!((b["state"].as_str(), b["over"].as_str()), (Some("paused"), Some("usd")), "{b}");
+ assert!(env.direct(bot_budget::STOPPED_KIND).await[0].text.contains("stopped at its monthly budget"));
+ env.held("NOCOST stopped").await;
+}
+
+/// A new month releases the bot on its own; a routine held during the pause runs once, late,
+/// with a note in its history.
+#[tokio::test]
+async fn new_month_releases_and_held_routine_runs_once_late() {
+ let tmp = tempfile::tempdir().unwrap();
+ let env = setup(tmp.path()).await;
+ env.state.spend.set(Some(at("2026-11-30T12:00:00Z")));
+ env.set_budget(&env.ann, json!({"budget_tokens": FRESH})).await;
+ env.turn("last of the month").await;
+ assert_eq!(env.budget(&env.ann).await["state"], "paused");
+
+ let (s, r) = call(
+ &env.app,
+ "POST",
+ "/api/routines",
+ Some(json!({"kwant_id": env.ann, "name": "Digest", "instructions": "Summarise yesterday.",
+ "schedule": {"type": "daily", "time": "09:00", "tz": "UTC"}})),
+ )
+ .await;
+ assert_eq!(s, StatusCode::CREATED, "{r}");
+ let rid = r["id"].as_str().unwrap().to_string();
+ for _ in 0..2 {
+ let (s, v) = call(&env.app, "POST", &format!("/api/routines/{rid}/run"), None).await;
+ assert_eq!(s, StatusCode::ACCEPTED, "{v}");
+ }
+ let runs = ok(&env.app, "GET", &format!("/api/routines/{rid}/runs"), None).await;
+ let runs = runs.as_array().unwrap().clone();
+ assert_eq!(runs.len(), 2, "{runs:?}");
+ for run in &runs {
+ assert_eq!(run["status"], "skipped", "{run}");
+ assert!(run["error"].as_str().unwrap().starts_with("bot_budget"), "{run}");
+ }
+
+ // Still November: nothing to release
+ bot_budget::release_due(&env.state).await;
+ assert_eq!(env.budget(&env.ann).await["state"], "paused");
+ assert_eq!(ok(&env.app, "GET", &format!("/api/routines/{rid}/runs"), None).await.as_array().unwrap().len(), 2);
+
+ // December
+ env.state.spend.set(Some(at("2026-12-01T00:30:00Z")));
+ let b = env.budget(&env.ann).await;
+ assert_eq!((b["month"].as_str(), b["used_tokens"].as_u64(), b["state"].as_str()), (Some("2026-12"), Some(0), Some("under")), "{b}");
+ bot_budget::release_due(&env.state).await;
+ assert_eq!(env.direct("bot_budget_resumed").await.len(), 1);
+ let mut late = Value::Null;
+ for _ in 0..200 {
+ let runs = ok(&env.app, "GET", &format!("/api/routines/{rid}/runs"), None).await;
+ if runs.as_array().unwrap().len() == 3 && runs[0]["status"] == "ok" {
+ late = runs[0].clone();
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ assert_eq!(late["note"], "Ran late: Ann was paused at its monthly budget.", "{late}");
+ assert_eq!(late["trigger"], "schedule");
+
+ // Released once: the next tick has nothing left
+ bot_budget::release_due(&env.state).await;
+ assert_eq!(ok(&env.app, "GET", &format!("/api/routines/{rid}/runs"), None).await.as_array().unwrap().len(), 3);
+ assert_eq!(env.direct("bot_budget_resumed").await.len(), 1);
+}
+
+/// Only the person sets, continues or re-pauses a budget: a bot's turn token gets 403 and changes
+/// nothing; reading stays open.
+#[tokio::test]
+async fn a_bot_token_cannot_change_a_budget() {
+ let tmp = tempfile::tempdir().unwrap();
+ let env = setup(tmp.path()).await;
+ env.set_budget(&env.ann, json!({"budget_tokens": FRESH})).await;
+ env.turn("spend it").await;
+ assert_eq!(env.budget(&env.ann).await["state"], "paused");
+
+ let ann = env.state.db.get_kwant(&env.ann).await.unwrap().unwrap();
+ let scope = SelfScope {
+ kwant_id: ann.id.clone(),
+ kwant_name: ann.name.clone(),
+ origin: Some(TurnOrigin { channel_id: Some(env.channel.clone()), ..Default::default() }),
+ turn_id: Some("t-budget".into()),
+ ..Default::default()
+ };
+ let token = mcp_runtime::prepare_turn_with_self(&env.state, &ann, Some("t-budget".into()), None, Some(scope)).await.unwrap().1;
+
+ for kwant in [&env.ann, &env.bob] {
+ for (method, uri, body) in [
+ ("POST", format!("/api/kwants/{kwant}/budget"), Some(json!({"budget_tokens": null}))),
+ ("POST", format!("/api/kwants/{kwant}/budget/continue"), None),
+ ("DELETE", format!("/api/kwants/{kwant}/budget/continue"), None),
+ ] {
+ let (s, v) = call_as(&env.app, method, &uri, body, Some(&token)).await;
+ assert_eq!(s, StatusCode::FORBIDDEN, "{method} {uri}: {v}");
+ }
+ }
+ let b = env.budget(&env.ann).await;
+ assert_eq!((b["state"].as_str(), b["budget_tokens"].as_u64()), (Some("paused"), Some(FRESH)), "unchanged: {b}");
+ assert!(env.direct("bot_budget_continued").await.is_empty());
+
+ let (s, v) = call_as(&env.app, "GET", &format!("/api/kwants/{}/budget", env.ann), None, Some(&token)).await;
+ assert_eq!((s, v["state"].as_str()), (StatusCode::OK, Some("paused")), "{v}");
+ let (s, _) = call_as(&env.app, "GET", "/api/usage/budgets", None, Some(&token)).await;
+ assert_eq!(s, StatusCode::OK);
+
+ // The person can
+ let (s, v) = call(&env.app, "POST", &format!("/api/kwants/{}/budget/continue", env.ann), None).await;
+ assert_eq!((s, v["state"].as_str()), (StatusCode::OK, Some("continued")), "{v}");
+}
+
+/// Bad limits are refused and change nothing; null turns a limit off.
+#[tokio::test]
+async fn validates_limits_and_turns_off() {
+ let tmp = tempfile::tempdir().unwrap();
+ let env = setup(tmp.path()).await;
+ env.set_budget(&env.ann, json!({"budget_tokens": 1000, "budget_usd": 2.345})).await;
+ for bad in [
+ json!({"budget_tokens": -1}),
+ json!({"budget_tokens": 1.5}),
+ json!({"budget_tokens": 10_000_000_001u64}),
+ json!({"budget_usd": -0.01}),
+ json!({"budget_usd": 100_001}),
+ json!({"budget_tokens": "lots"}),
+ ] {
+ let (s, v) = call(&env.app, "POST", &format!("/api/kwants/{}/budget", env.ann), Some(bad.clone())).await;
+ assert_eq!(s, StatusCode::BAD_REQUEST, "{bad}: {v}");
+ }
+ let b = env.budget(&env.ann).await;
+ assert_eq!((b["budget_tokens"].as_u64(), b["budget_usd"].as_f64()), (Some(1000), Some(2.35)), "{b}");
+
+ let b = env.set_budget(&env.ann, json!({"budget_usd": null})).await;
+ assert_eq!((b["budget_tokens"].as_u64(), b["budget_usd"].as_f64()), (Some(1000), Some(0.0)), "left out stays: {b}");
+ let b = env.set_budget(&env.ann, json!({"budget_tokens": 0})).await;
+ assert_eq!(b["state"], "off");
+ let (s, _) = call(&env.app, "POST", &format!("/api/kwants/{}/budget/continue", env.ann), None).await;
+ assert_eq!(s, StatusCode::CONFLICT, "nothing to continue");
+ let (s, _) = call(&env.app, "GET", "/api/kwants/nobody/budget", None).await;
+ assert_eq!(s, StatusCode::NOT_FOUND);
+}
+
+/// Replies in `chat` from the bot named `who` (messages carry the bot's name).
+async fn replies_in(env: &Env, chat: &str, who: &str) -> usize {
+ env.state.db.list_messages(chat, 200).await.unwrap().iter().filter(|m| m.sender_role == "kwant" && m.sender_id == who).count()
+}
+
+/// A Codex bot reports no usage, but its budget is never hidden while it can still park the bot:
+/// the budget and the month's spend come back with `estimated: true`, and the estimate pauses it.
+#[tokio::test]
+async fn a_codex_bots_budget_is_shown_as_estimated_and_still_holds_it() {
+ let tmp = tempfile::tempdir().unwrap();
+ let env = setup(tmp.path()).await;
+ let bot = json!({"name": "Cody", "title": "Cody the tester", "persona_prompt": "Test persona",
+ "avatar_sprite": "s", "driver_type": "cli", "preferred_model": "codex"});
+ let cody = ok(&env.app, "POST", "/api/kwants", Some(bot)).await["id"].as_str().unwrap().to_string();
+ // The engine list is probed at start-up; the fake codex was put on PATH after that
+ ok(&env.app, "POST", "/api/engines/recheck", None).await;
+ // Cody's direct chat, where its stop notice also goes
+ let desk = cody.clone();
+ let say = |text: &str| ok(&env.app, "POST", "/api/chat/send", Some(json!({"kwant_id": cody, "prompt": text, "sender_id": "user"})));
+
+ let b = env.set_budget(&cody, json!({"budget_tokens": 2 * CODEX_TURN, "budget_usd": 5.0})).await;
+ assert_eq!((b["engine"].as_str(), b["estimated"].as_bool(), b["usage_reported"].clone()), (Some("codex"), Some(false), Value::Null), "{b}");
+
+ for (n, text) in [(1, "one"), (2, "two")] {
+ say(text).await;
+ for _ in 0..200 {
+ if replies_in(&env, &desk, "Cody").await >= n {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ assert_eq!(replies_in(&env, &desk, "Cody").await, n, "Cody answered {text}");
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ }
+
+ // Not hidden: the set budget and the month's estimated spend, flagged as estimated
+ let b = env.budget(&cody).await;
+ assert_eq!((b["budget_tokens"].as_u64(), b["budget_usd"].as_f64()), (Some(2 * CODEX_TURN), Some(5.0)), "{b}");
+ assert_eq!(b["used_tokens"].as_u64(), Some(2 * CODEX_TURN), "the daily stop's estimate: {b}");
+ assert_eq!(b["used_usd"].as_f64(), Some(0.0), "no dollars are reported: {b}");
+ assert_eq!((b["usage_reported"].as_bool(), b["cost_reported"].as_bool(), b["estimated"].as_bool()), (Some(false), Some(false), Some(true)), "{b}");
+ assert_eq!((b["state"].as_str(), b["over"].as_str()), (Some("paused"), Some("tokens")), "the estimate parks the bot: {b}");
+ let all = ok(&env.app, "GET", "/api/usage/budgets", None).await;
+ let row = all["bots"].as_array().unwrap().iter().find(|r| r["kwant_id"] == cody.as_str()).cloned().unwrap();
+ assert_eq!((row["estimated"].as_bool(), row["budget_tokens"].as_u64()), (Some(true), Some(2 * CODEX_TURN)), "{row}");
+
+ // The stop notice says it is an estimate
+ let stop: Vec<Message> = env.state.db.list_messages(&cody, 200).await.unwrap().into_iter().filter(|m| meta(m)["kind"] == bot_budget::STOPPED_KIND).collect();
+ assert_eq!(stop.len(), 1, "one stop notice");
+ assert_eq!(meta(&stop[0])["estimated"], true);
+ assert!(meta(&stop[0])["detail"].as_str().unwrap().starts_with("about 200 of 200 fresh tokens"), "{}", meta(&stop[0]));
+
+ // Held: the next message is parked, not run
+ say("three").await;
+ tokio::time::sleep(Duration::from_millis(1500)).await;
+ assert_eq!(replies_in(&env, &desk, "Cody").await, 2, "no turn while paused");
+ let parks = env.state.db.list_parked().await.unwrap().into_iter().filter(|p| p.reason == "bot_budget" && p.status == "pending" && p.kwant_id == cody).count();
+ assert_eq!(parks, 1, "held for when Cody resumes");
+ // Ann, on Claude, reports usage: not estimated
+ env.turn("hi").await;
+ assert_eq!(env.budget(&env.ann).await["estimated"], false);
+}