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.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Hand-off token limit off by default (#144)
Lin (kwant bot)df33c29f54d8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4f489727..1cfe7459 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -44,6 +44,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).server rejects is flagged next to the picker in plain words.### Changed+- **The hand-off token limit is now off by default.** A request no longer pauses after 200k fresh+ tokens of bots handing work to each other; the hand-off count caps (4 per bot, 16 per request, with+ Continue) still stop loops. Set a limit in Settings → Usage → Hand-offs per request (No limit, a quick+ pick or Custom) and it pauses and offers Continue as before. On upgrade, a stored limit still at the+ old 200k default is switched off once; any other number you set stays.- **Audits run on the fast model by default.** The Swarm Auditor's challenge and rebuttal turns now usethe engine's cheap, fast model (for Claude, Haiku at medium effort) instead of the bot's default. Thenew `auditor_model` setting picks `fast` (default), `balanced`, `deep`, or `bot` for the bot's usualdiff --git a/docs/mission-control.md b/docs/mission-control.mdindex 258008c8..9872e074 100644--- a/docs/mission-control.md+++ b/docs/mission-control.md@@ -608,7 +608,11 @@ Token budgets are opt-in. `budget_tokens` 0 means no limit, for tasks and missioand in the same transaction rows still at the old silent defaults lose them:`UPDATE tasks SET budget_tokens = 0 WHERE budget_tokens = 50000` and`UPDATE missions SET budget_tokens = 0 WHERE budget_tokens = 200000`. Task states are not changed.-- The hand-off loop guard (`chain_token_budget`) is separate and unchanged.+- The hand-off token limit per request (`chain_token_budget`, fresh tokens) is separate and is+ opt-in too: 0 (no limit) is the default. A person who sets a number gets the `budget_paused` notice+ and Continue as before. Migration (once, flag setting `chain_token_budget_opt_in_v1`): a stored+ `chain_token_budget` of exactly `200000`, the old default that Settings wrote back on every save,+ becomes `0`; any other stored number stays, and so does `200000` saved after the migration ran.## 16. Hand-off cards that go on@@ -652,8 +656,8 @@ from before this change (no result evidence) and cards whose lead was deleted ar### Capped hand-offs: the Continue noticeOne person message starts at most `routes::MAX_DELEGATIONS_PER_REQUEST` (16) hand-offs by mention,-at most `routes::MAX_MENTION_DELEGATIONS_PER_BOT` (4) to one teammate; `chain_token_budget` still-stops real loops. Mentions past a cap are not dropped: kwant saves one system message in the channel+at most `routes::MAX_MENTION_DELEGATIONS_PER_BOT` (4) to one teammate. These caps are what stop+loops by default; `chain_token_budget` adds a token limit only when the person sets one (§15). Mentions past a cap are not dropped: kwant saves one system message in the channelwith meta```jsondiff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsxindex e66e1c11..20c35a32 100644--- a/frontend/src/components/SettingsModal.tsx+++ b/frontend/src/components/SettingsModal.tsx@@ -3,7 +3,6 @@ import { AuditorSettings, DAILY_CAPS, SETTING_HINT as AUDITOR_HINT, isAuditorModimport { AuditorModelSetting } from './AuditorModelSetting';import { Key, Globe, X, Settings, Check, ChevronDown, ChevronRight, LogOut, Bell, AlertTriangle, Layers, Monitor, Volume2, VolumeX, Gauge, MapPin, Vibrate, VibrateOff, Sparkles, KanbanSquare } from 'lucide-react';import { TURN_LIMITS, TurnLimitKey, limitError } from '../threads';-import { budgetError, budgetValue } from '../chainBudget';import { DailyUsagePanel } from './DailyUsage';import {BROWSER_NOTIFY_KEY,@@ -47,6 +46,7 @@ import {parseDefaultLimits,parseLimit,parseMissionBoardSetting,+ requestLimitFrom,} from '../missions';import { FlightSchoolSettings, TIERS, TIER_HINTS, TIER_LABELS, Tier, parseFlightSchoolSettings } from '../flightSchool';@@ -286,9 +286,10 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, tconst webhookError = webhookUrlError(webhookUrl);// Kept as typed text so a half-typed value can be shown with its error; null until loaded.const [limits, setLimits] = useState<Record<TurnLimitKey, string> | null>(null);- // Fresh tokens one request's chain may use before hand-offs pause; null on a server without it.+ // Fresh tokens one request's hand-offs may use before they pause (0 = no limit), as typed; null on a server without it.const [chainBudget, setChainBudget] = useState<string | null>(null);- const chainBudgetError = chainBudget === null ? null : budgetError(chainBudget);+ const chainBudgetValue = chainBudget === null ? null : requestLimitFrom(chainBudget);+ const chainBudgetError = chainBudget !== null && chainBudgetValue === null;// Default token limits for new tasks and missions, as typed; null on a server without them.const [tokenLimits, setTokenLimits] = useState<{ task: string; mission: string } | null>(null);const tokenLimitsValue = tokenLimits ? defaultLimitsFrom(tokenLimits) : null;@@ -420,7 +421,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, tdelegation_follow_up_minutes: Number(limits.delegation_follow_up_minutes),}: {}),- ...(chainBudget !== null ? { chain_token_budget: budgetValue(chainBudget) } : {}),+ ...(chainBudgetValue !== null ? { chain_token_budget: chainBudgetValue } : {}),...(tokenLimitsValue ? defaultLimitsBody(tokenLimitsValue) : {}),...(agentTools !== null ? { agent_tools: agentTools } : {}),...(proactive ?? {}),@@ -761,26 +762,11 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t</div>)}{chainBudget !== null && (- <div className="space-y-1">- <label htmlFor="chain-token-budget" className="block text-[11px] font-medium text-zinc-300">- Token budget per request (fresh tokens)- </label>- <input- id="chain-token-budget"- type="text"- inputMode="numeric"- autoComplete="off"- value={chainBudget}- onChange={(e) => setChainBudget(e.target.value)}- aria-invalid={!!chainBudgetError}- aria-describedby="chain-token-budget-hint"- className={`w-full sm:w-48 bg-zinc-950 border rounded-lg px-3 py-2 text-xs font-mono text-zinc-100 focus:outline-none transition-colors ${- chainBudgetError ? 'border-rose-500/60 focus:border-rose-400' : 'border-zinc-800 focus:border-sky-500'- }`}- />- <p id="chain-token-budget-hint" className={`text-[11px] ${chainBudgetError ? 'text-rose-300' : 'text-zinc-500'}`}>- {chainBudgetError ??- 'When bots handing work to each other go over this for one of your messages, they pause and ask you before going on. 0 turns it off.'}+ <div className="space-y-1" data-chain-token-budget>+ <DefaultLimitField id="chain-token-budget" label="Hand-offs per request" scope="request" value={chainBudget} onChange={setChainBudget} />+ <p className="text-[11px] text-zinc-500">+ With no limit, bots hand work to each other until they're done. Set one and they pause and ask you before going over it for one of+ your messages.</p></div>)}diff --git a/frontend/src/missions.ts b/frontend/src/missions.tsindex 6156893e..36d3ee8a 100644--- a/frontend/src/missions.ts+++ b/frontend/src/missions.ts@@ -564,8 +564,8 @@ export function costText(spent: number, budget: number): string {export const NO_LIMIT = 0;/** Quick picks in the limit editor and Settings. */export const LIMIT_PICKS = [50_000, 200_000, 1_000_000] as const;-/** What the server takes: a task 1–5M, a mission 1000–5M (0 is no limit for both). */-export const LIMIT_RANGE = { task: [1, 5_000_000], mission: [1_000, 5_000_000] } as const;+/** What the server takes: a task 1–5M, a mission 1000–5M, one request's hand-offs 1–100M (0 is no limit for all). */+export const LIMIT_RANGE = { task: [1, 5_000_000], mission: [1_000, 5_000_000], request: [1, 100_000_000] } as const;export type LimitScope = keyof typeof LIMIT_RANGE;/** "50k", "1.5M", "200 000", "200,000" → tokens; null when it isn't a number. */@@ -602,6 +602,12 @@ export function parseDefaultLimits(d: { mission_default_task_budget_tokens?: unkif (task === null) return null;return { task, mission: n(d.mission_default_budget_tokens) ?? NO_LIMIT };}+/** Settings' hand-off token limit per request (`chain_token_budget`) as typed: 0 is no limit, the default; null while it can't be saved. */+export function requestLimitFrom(raw: string): number | null {+ const n = parseLimit(raw);+ if (n === null) return null;+ return n === NO_LIMIT || !limitError(raw, 'request') ? n : null;+}export const defaultLimitsBody = (l: DefaultLimits) => ({ mission_default_task_budget_tokens: l.task, mission_default_budget_tokens: l.mission });/** The task stopped because it used up its own token limit. */diff --git a/frontend/tests/tokenLimits.test.mjs b/frontend/tests/tokenLimits.test.mjsindex 39a7c66a..54a99ae8 100644--- a/frontend/tests/tokenLimits.test.mjs+++ b/frontend/tests/tokenLimits.test.mjs@@ -211,3 +211,14 @@ test('Out of budget: Remove limit and continue sends 0; Raise limit only offersv.done();}});++test('Settings hand-off limit per request: no limit is 0, a pick or "300k" is kept, out of range is refused', () => {+ assert.equal(m.requestLimitFrom('0'), 0);+ assert.equal(m.requestLimitFrom('200000'), 200_000);+ assert.equal(m.requestLimitFrom('300k'), 300_000);+ assert.equal(m.requestLimitFrom('100M'), 100_000_000);+ assert.equal(m.requestLimitFrom('101M'), null);+ assert.equal(m.requestLimitFrom(''), null, 'Custom with nothing typed yet');+ assert.equal(m.requestLimitFrom('lots'), null);+ assert.equal(m.limitLabel(0), 'No limit');+});diff --git a/src/db/mod.rs b/src/db/mod.rsindex c3e70875..88ed003e 100644--- a/src/db/mod.rs+++ b/src/db/mod.rs@@ -37,6 +37,8 @@ pub mod foundry;pub const GENERAL_DESCRIPTION: &str = "Everyone in this space. Laya picks who answers.";/// Default's #general description before the "kwant bots" wording; replaced only if unchanged.const OLD_GENERAL_DESCRIPTION: &str = "Main collaboration hub for all agents";+/// Set once [`Database::migrate_chain_budget_default`] has run.+const CHAIN_BUDGET_OPT_IN_DONE: &str = "chain_token_budget_opt_in_v1";use models::*;use spaces::SpaceId;@@ -186,6 +188,7 @@ impl Database {db.migrate_flight_school().await?;// Last: it rebuilds `tasks` and `missions` from their stored SQL, columns and triggers includeddb.migrate_opt_in_budgets().await?;+ db.migrate_chain_budget_default().await?;// After it: observes finished tasks once (their class comes from Flight School)db.migrate_performance().await?;// Phase D2: audits and their risks (add-only)@@ -524,6 +527,21 @@ impl Database {Ok(())}+ /// The chain token budget became opt-in. Settings saved before that wrote the old default+ /// back on every save, so a stored [`crate::server::budget::OLD_DEFAULT`] is cleared to 0+ /// (off), once; any other number the person set stays. Later saves of that number are kept.+ pub async fn migrate_chain_budget_default(&self) -> Result<(), DbError> {+ if self.get_setting(CHAIN_BUDGET_OPT_IN_DONE).await?.is_some() {+ return Ok(());+ }+ sqlx::query("UPDATE settings SET value = '0' WHERE key = ? AND trim(value) = ?")+ .bind(crate::server::budget::SETTING)+ .bind(crate::server::budget::OLD_DEFAULT.to_string())+ .execute(&self.pool)+ .await?;+ self.set_setting(CHAIN_BUDGET_OPT_IN_DONE, &chrono::Utc::now().to_rfc3339()).await+ }+// Settings CRUDpub async fn get_setting(&self, key: &str) -> Result<Option<String>, DbError> {let row: Option<(String,)> = sqlx::query_as("SELECT value FROM settings WHERE key = ?")diff --git a/src/server/budget.rs b/src/server/budget.rsindex ecc8e20a..a4926d7c 100644--- a/src/server/budget.rs+++ b/src/server/budget.rs@@ -17,7 +17,12 @@ use serde_json::json;/// Setting key: fresh tokens one chain may use before hand-offs pause; 0 turns the guard off.pub const SETTING: &str = "chain_token_budget";-pub const DEFAULT: u64 = 200_000;+/// Off unless the person sets a budget, like task and mission limits (docs/mission-control.md §15).+/// The hand-off count caps still stop a chain that loops.+pub const DEFAULT: u64 = 0;+/// The budget every install had before it became opt-in; a stored value equal to it is cleared+/// once ([`crate::db::Database::migrate_chain_budget_default`]).+pub const OLD_DEFAULT: u64 = 200_000;pub const MAX: u64 = 100_000_000;/// Message meta kind of the notice.pub const KIND: &str = "budget_paused";diff --git a/tests/chain_budget_test.rs b/tests/chain_budget_test.rsindex 3b97f8c2..98279ff6 100644--- a/tests/chain_budget_test.rs+++ b/tests/chain_budget_test.rs@@ -242,3 +242,56 @@ async fn a_budget_of_zero_never_pauses() {env.settle().await;assert!(env.notices().await.is_empty());}++#[tokio::test]+async fn a_fresh_install_has_no_token_limit_on_hand_offs() {+ let env = setup().await;+ assert_eq!(kwnt::server::budget::DEFAULT, 0);+ assert_eq!(ok(&env.app, "GET", "/api/settings", None).await["chain_token_budget"].as_u64(), Some(0));+ assert_eq!(kwnt::server::budget::limit(&env.state).await, 0);+ env.say("@Ann look at this MENTION:Bob").await;+ env.wait_for("Bob's turn", || async { env.replies_from("Bob").await == 1 }).await;+ env.settle().await;+ assert!(env.notices().await.is_empty(), "nothing pauses without a limit");+}++/// Runs a statement on the database file directly, as an older kwnt would have left it.+async fn raw(dir: &std::path::Path, sql: &str) {+ let pool = sqlx::sqlite::SqlitePoolOptions::new()+ .max_connections(1)+ .connect(&format!("sqlite://{}", dir.join("kwnt.db").display()))+ .await+ .unwrap();+ sqlx::query(sql).execute(&pool).await.unwrap();+ pool.close().await;+}++/// The value after an upgrade from before the limit was opt-in, when `stored` was saved.+async fn upgraded(stored: &str) -> Option<String> {+ let tmp = tempfile::tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ db.set_setting(kwnt::server::budget::SETTING, stored).await.unwrap();+ drop(db);+ // Before the upgrade the migration had never run+ raw(tmp.path(), "DELETE FROM settings WHERE key = 'chain_token_budget_opt_in_v1'").await;+ let db = Database::init(tmp.path()).await.unwrap();+ db.get_setting(kwnt::server::budget::SETTING).await.unwrap()+}++#[tokio::test]+async fn an_upgrade_turns_off_the_old_default_and_keeps_a_limit_the_person_chose() {+ assert_eq!(upgraded("200000").await.as_deref(), Some("0"), "the old default Settings saved back is switched off");+ assert_eq!(upgraded("50000").await.as_deref(), Some("50000"), "a chosen limit stays");+ assert_eq!(upgraded("0").await.as_deref(), Some("0"));+}++#[tokio::test]+async fn a_200k_limit_set_after_the_upgrade_is_kept() {+ let tmp = tempfile::tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ db.set_setting(kwnt::server::budget::SETTING, "200000").await.unwrap();+ drop(db);+ // The migration runs once: opening again doesn't clear a 200k the person picked since+ let db = Database::init(tmp.path()).await.unwrap();+ assert_eq!(db.get_setting(kwnt::server::budget::SETTING).await.unwrap().as_deref(), Some("200000"));+}