Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat: budgets in Settings, and settings grouped with tabs
Salman Qureshi142e58cbe21d
diff --git a/apps/desktop/src/views/settings/Budgets.test.ts b/apps/desktop/src/views/settings/Budgets.test.tsnew file mode 100644index 00000000..e4ab2e6d--- /dev/null+++ b/apps/desktop/src/views/settings/Budgets.test.ts@@ -0,0 +1,19 @@+import { describe, expect, it } from "vitest";+import { parseTokens } from "./Budgets";++describe("parseTokens", () => {+ it("reads plain numbers, separators and k/m", () => {+ expect(parseTokens("1,500,000")).toBe(1_500_000);+ expect(parseTokens("2M")).toBe(2_000_000);+ expect(parseTokens("750k")).toBe(750_000);+ expect(parseTokens(" 1.5m ")).toBe(1_500_000);+ expect(parseTokens("0")).toBe(0);+ });++ it("refuses what isn't a token count", () => {+ expect(parseTokens("")).toBeNull();+ expect(parseTokens("lots")).toBeNull();+ expect(parseTokens("-5")).toBeNull();+ expect(parseTokens("2g")).toBeNull();+ });+});diff --git a/apps/desktop/src/views/settings/Budgets.tsx b/apps/desktop/src/views/settings/Budgets.tsxnew file mode 100644index 00000000..6cd913dc--- /dev/null+++ b/apps/desktop/src/views/settings/Budgets.tsx@@ -0,0 +1,178 @@+import { useEffect, useState } from "react";+import { ApiError, http } from "~/api/client";+import { Button } from "~/components/ui/Button";+import { Input } from "~/components/ui/Input";+import { Switch } from "~/components/ui/Switch";+import { Segmented, Spinner } from "~/components/ui/bits";+import { cx } from "~/lib/cx";+import { compact } from "~/views/bots/Usage";++/**+ * Budgets: how many tokens Mercury may use a day, when Token Saver steps+ * in, and the caps for bots. Saves apply at once, no restart.+ */++export interface BudgetState {+ daily: { budget: number; used: number; remaining: number; percentage: number };+ saver: { state: "off" | "on" | "auto"; autoEnabled: boolean; autoThreshold: number; savedToday: number; savedLifetime: number };+ bots: { enabled: boolean; perBot: number; fleet: number };+}++type BudgetPatch = { dailyBudget?: number; saver?: { manual?: boolean; autoEnabled?: boolean; autoThreshold?: number }; bots?: { perBot?: number; fleet?: number } };++const DAILY_PRESETS = [500_000, 1_000_000, 2_000_000, 5_000_000, 10_000_000];+const THRESHOLDS = ["50", "75", "90"] as const;++/** "2M", "750k", "1,500,000" → tokens; null when it isn't a number. */+export function parseTokens(text: string): number | null {+ const m = text.trim().toLowerCase().replace(/[,_\s]/g, "").match(/^(\d+(?:\.\d+)?)([km]?)$/);+ if (!m) return null;+ const n = Number(m[1]) * (m[2] === "m" ? 1_000_000 : m[2] === "k" ? 1_000 : 1);+ return Number.isFinite(n) ? Math.round(n) : null;+}++export function BudgetsSettings() {+ const [state, setState] = useState<BudgetState | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [saving, setSaving] = useState(false);++ useEffect(() => {+ http.get<BudgetState>("/api/budget")+ .then(setState)+ .catch((e) => setError(e instanceof ApiError && e.status === 404 ? "This runtime can't change budgets from here yet. Update Mercury, or send /budget set <tokens> in a chat." : e instanceof Error ? e.message : String(e)));+ }, []);++ async function save(patch: BudgetPatch): Promise<boolean> {+ setSaving(true);+ setError(null);+ try {+ setState(await http.put<BudgetState>("/api/budget", patch));+ return true;+ } catch (e) {+ setError(e instanceof Error ? e.message : String(e));+ return false;+ } finally {+ setSaving(false);+ }+ }++ if (!state) return error ? <p className="text-sm text-ink3">{error}</p> : <div className="py-10 text-ink3"><Spinner size={18} /></div>;+ const { daily, saver, bots } = state;+ const ratio = daily.budget > 0 ? Math.min(1, daily.used / daily.budget) : 0;++ return (+ <div className="flex flex-col gap-6">+ <p className="text-sm text-ink3">Tokens are what the models count. When Mercury reaches the daily budget it stops and tells you: raise the budget here, or send /budget override in a chat to let one more request through.</p>+ {error && <p className="text-sm text-red" role="alert">{error}</p>}++ <section className="flex flex-col gap-3">+ <h3 className="text-sm font-medium text-ink">Daily budget</h3>+ <div className="flex flex-col gap-3 rounded-lg border border-line bg-surface px-4 py-3">+ <div className="flex items-baseline justify-between text-sm">+ <span className="text-ink">{compact(daily.used)} <span className="text-ink3">of {compact(daily.budget)} used today</span></span>+ <span className="font-mono text-xs text-ink3">{daily.percentage}%</span>+ </div>+ <div className="h-1.5 overflow-hidden rounded-full bg-ink/[0.07]" role="meter" aria-valuemin={0} aria-valuemax={daily.budget} aria-valuenow={daily.used} aria-label="Tokens used today">+ <div className={cx("h-full rounded-full", ratio >= 0.9 ? "bg-red" : ratio >= 0.75 ? "bg-amber" : "bg-accent")} style={{ width: `${ratio * 100}%` }} />+ </div>+ <TokenField+ id="budget-daily"+ label="Tokens a day"+ value={daily.budget}+ min={1_000}+ presets={DAILY_PRESETS}+ saving={saving}+ onSave={(n) => save({ dailyBudget: n })}+ />+ </div>+ </section>++ <section className="flex flex-col gap-3">+ <h3 className="text-sm font-medium text-ink">Token Saver</h3>+ <div className="flex flex-col divide-y divide-line rounded-lg border border-line bg-surface">+ <Row title="On now" hint={saver.state === "auto" ? "On by itself: you're past the threshold today." : "Shorter answers, fewer steps, a smaller history. Turn on for a cheap day."}>+ <Switch id="saver-manual" checked={saver.state !== "off"} disabled={saving} onCheckedChange={(v) => void save({ saver: { manual: v } })} />+ </Row>+ <Row title="Turn on by itself" hint="When today's use passes a share of the daily budget.">+ <Switch id="saver-auto" checked={saver.autoEnabled} disabled={saving} onCheckedChange={(v) => void save({ saver: { autoEnabled: v } })} />+ </Row>+ {saver.autoEnabled && (+ <Row title="At" hint="of the daily budget.">+ <Segmented+ value={THRESHOLDS.find((t) => Number(t) === saver.autoThreshold) ?? ("" as (typeof THRESHOLDS)[number])}+ onChange={(v) => void save({ saver: { autoThreshold: Number(v) } })}+ options={THRESHOLDS.map((t) => ({ value: t, label: `${t}%` }))}+ />+ </Row>+ )}+ <div className="px-4 py-2.5 text-xs text-ink3">Saved about {compact(saver.savedToday)} tokens today, {compact(saver.savedLifetime)} in all.</div>+ </div>+ </section>++ <section className="flex flex-col gap-3">+ <h3 className="text-sm font-medium text-ink">Bots</h3>+ <div className="flex flex-col gap-4 rounded-lg border border-line bg-surface px-4 py-3">+ {!bots.enabled && <p className="text-xs text-ink3">Bots are off. These caps apply once you turn them on.</p>}+ <TokenField id="budget-bot" label="Each bot, a day" hint="For bots that don't set their own. 0 means no cap." value={bots.perBot} min={0} saving={saving} onSave={(n) => save({ bots: { perBot: n } })} />+ <TokenField id="budget-fleet" label="All bots together, a day" hint="Every bot pauses until tomorrow when it's reached. 0 means no cap." value={bots.fleet} min={0} saving={saving} onSave={(n) => save({ bots: { fleet: n } })} />+ </div>+ </section>+ </div>+ );+}++function Row({ title, hint, children }: { title: string; hint: string; children: React.ReactNode }) {+ return (+ <div className="flex items-center justify-between gap-4 px-4 py-3">+ <div>+ <div className="text-sm text-ink">{title}</div>+ <div className="text-xs text-ink3">{hint}</div>+ </div>+ {children}+ </div>+ );+}++/** A token amount: type "2M" or "750k", or pick a preset. Saves on Enter or Save. */+function TokenField({ id, label, hint, value, min, presets, saving, onSave }: {+ id: string; label: string; hint?: string; value: number; min: number; presets?: number[]; saving: boolean; onSave: (n: number) => Promise<boolean>;+}) {+ const [text, setText] = useState(value.toLocaleString());+ const [problem, setProblem] = useState<string | null>(null);+ const [saved, setSaved] = useState(false);+ useEffect(() => { setText(value.toLocaleString()); }, [value]);+ const parsed = parseTokens(text);+ const dirty = parsed !== value;++ async function commit(n: number | null = parsed) {+ setSaved(false);+ if (n === null) return setProblem("Type a number, like 2M or 750k.");+ if (n < min) return setProblem(`At least ${min.toLocaleString()} tokens.`);+ setProblem(null);+ if (await onSave(n)) setSaved(true);+ }++ return (+ <div className="flex flex-col gap-2">+ <label htmlFor={id} className="text-sm text-ink">{label}</label>+ {hint && <div className="-mt-1.5 text-xs text-ink3">{hint}</div>}+ <div className="flex items-center gap-2">+ <Input id={id} mono value={text} inputMode="numeric" className="max-w-[180px]" onChange={(e) => { setText(e.target.value); setSaved(false); setProblem(null); }} onKeyDown={(e) => { if (e.key === "Enter" && dirty) void commit(); }} aria-invalid={!!problem} />+ <span className="text-xs text-ink4">tokens</span>+ {dirty && <Button size="sm" variant="primary" disabled={saving} onClick={() => void commit()}>Save</Button>}+ {saved && !dirty && <span className="text-xs text-accent">Saved</span>}+ </div>+ {presets && (+ <div className="flex flex-wrap gap-1.5">+ {presets.map((p) => (+ <button key={p} type="button" disabled={saving} onClick={() => { setText(p.toLocaleString()); void commit(p); }}+ className={cx("rounded-full border px-2.5 py-0.5 font-mono text-2xs", p === value ? "border-accent/50 bg-accent/10 text-accent" : "border-line text-ink3 hover:border-line-strong hover:text-ink")}>+ {compact(p)}+ </button>+ ))}+ </div>+ )}+ {problem && <div className="text-xs text-red" role="alert">{problem}</div>}+ </div>+ );+}diff --git a/apps/desktop/src/views/settings/SettingsView.tsx b/apps/desktop/src/views/settings/SettingsView.tsxindex 9f55ebc7..4fe1a04b 100644--- a/apps/desktop/src/views/settings/SettingsView.tsx+++ b/apps/desktop/src/views/settings/SettingsView.tsx@@ -1,4 +1,4 @@-import { Activity, Boxes, Info, MessagesSquare, Mic, PanelBottom, Palette, Power, Server, Smartphone, UserRound, Bell } from "lucide-react";+import { Activity, Info, MessagesSquare, Palette, Server, Sparkles, UserRound } from "lucide-react";import { useEffect, useState } from "react";import { cx } from "~/lib/cx";import { useUi } from "~/app/store";@@ -17,71 +17,101 @@ import { Analytics } from "./Analytics";import { Profile } from "./Profile";import { ModelsSettings } from "./Models";import { VoiceSettings } from "./Voice";+import { BudgetsSettings } from "./Budgets";import { ChannelsSettings } from "./Channels";import { isVisible, orderedIds, useContributions, type ContributionArea } from "~/extensions/registry";import { NotificationsSettings } from "./Notifications";/**- * Settings: a section list on the left, one section on the right. Most-used- * first (Appearance), plain labels, every control explains itself in one line.+ * Settings: a short list of groups on the left; a group with more than one+ * page shows them as tabs across the top. Everything about the models+ * (which ones, voice, what they may spend) sits together under AI.*/-type Section = "profile" | "models" | "voice" | "notifications" | "channels" | "appearance" | "statusbar" | "analytics" | "connections" | "devices" | "startup" | "about";+type Section = "profile" | "models" | "voice" | "budgets" | "channels" | "notifications" | "appearance" | "statusbar" | "startup" | "connections" | "devices" | "analytics" | "about";-const SECTIONS: Array<{ id: Section; label: string; icon: typeof Palette }> = [- { id: "profile", label: "Profile", icon: UserRound },- { id: "models", label: "Models", icon: Boxes },- { id: "voice", label: "Voice", icon: Mic },- { id: "notifications", label: "Notifications", icon: Bell },- { id: "channels", label: "Channels", icon: MessagesSquare },- { id: "appearance", label: "Appearance", icon: Palette },- { id: "statusbar", label: "Status bar", icon: PanelBottom },- { id: "analytics", label: "Analytics", icon: Activity },- { id: "connections", label: "Connections", icon: Server },- { id: "devices", label: "Paired devices", icon: Smartphone },- { id: "startup", label: "Start-up", icon: Power },- { id: "about", label: "About", icon: Info },+type GroupId = "profile" | "ai" | "messaging" | "app" | "connections" | "analytics" | "about";++const GROUPS: Array<{ id: GroupId; label: string; icon: typeof Palette; tabs: Array<{ id: Section; label: string }> }> = [+ { id: "profile", label: "Profile", icon: UserRound, tabs: [{ id: "profile", label: "Profile" }] },+ { id: "ai", label: "AI", icon: Sparkles, tabs: [{ id: "models", label: "Models" }, { id: "voice", label: "Voice" }, { id: "budgets", label: "Budgets" }] },+ { id: "messaging", label: "Messaging", icon: MessagesSquare, tabs: [{ id: "channels", label: "Channels" }, { id: "notifications", label: "Notifications" }] },+ { id: "app", label: "App", icon: Palette, tabs: [{ id: "appearance", label: "Appearance" }, { id: "statusbar", label: "Status bar" }, { id: "startup", label: "Start-up" }] },+ { id: "connections", label: "Connections", icon: Server, tabs: [{ id: "connections", label: "Runtimes" }, { id: "devices", label: "Paired devices" }] },+ { id: "analytics", label: "Activity", icon: Activity, tabs: [{ id: "analytics", label: "Activity" }] },+ { id: "about", label: "About", icon: Info, tabs: [{ id: "about", label: "About" }] },];+/** The group a page lives in. */+function groupOf(section: string) {+ return GROUPS.find((g) => g.tabs.some((t) => t.id === section));+}+export function SettingsView({ connection, health, onSwitchConnection }: { connection: Connection; health: HealthInfo; onSwitchConnection: () => void }) {const [section, setSection] = useState<Section>("appearance");- // Another screen asked for a section (the Cloud banner opens Models).+ // The page last open in each group, so coming back lands where you were.+ const [lastTab, setLastTab] = useState<Partial<Record<GroupId, Section>>>({});+ const group = groupOf(section) ?? GROUPS[0];+ const wide = section === "analytics" ? "max-w-[960px]" : "max-w-[680px]";+ const go = (next: Section) => {+ const g = groupOf(next);+ if (g) setLastTab((m) => ({ ...m, [g.id]: next }));+ setSection(next);+ };+ // Another screen asked for a page (the Cloud banner opens Models).const wanted = useUi((s) => s.settingsSection);const clearWanted = useUi((s) => s.clearSettingsSection);useEffect(() => {- if (wanted && SECTIONS.some((x) => x.id === wanted)) setSection(wanted as Section);+ if (wanted && groupOf(wanted)) go(wanted as Section);if (wanted) clearWanted();}, [wanted, clearWanted]);return (<div className="flex h-full min-h-0">- <aside className="flex w-[240px] shrink-0 flex-col border-r border-line bg-soft">+ <aside className="flex w-[220px] shrink-0 flex-col border-r border-line bg-soft"><div className="flex h-[52px] shrink-0 items-center px-5" data-tauri-drag-region><span className="text-base font-semibold text-ink">Settings</span></div>- <nav className="flex flex-col gap-0.5 px-2" aria-label="Settings sections">- {SECTIONS.map(({ id, label, icon: Icon }) => (- <button key={id} onClick={() => setSection(id)} aria-current={section === id ? "page" : undefined}- className={cx("flex items-center gap-3 rounded-lg px-3 py-2.5 text-left text-base", section === id ? "bg-ink/[0.07] text-ink" : "text-ink2 hover:bg-ink/[0.05] hover:text-ink")}>+ <nav className="flex flex-col gap-0.5 px-2" aria-label="Settings">+ {GROUPS.map(({ id, label, icon: Icon, tabs }) => (+ <button key={id} onClick={() => go(lastTab[id] ?? tabs[0].id)} aria-current={group.id === id ? "page" : undefined}+ className={cx("flex items-center gap-3 rounded-lg px-3 py-2.5 text-left text-base", group.id === id ? "bg-ink/[0.07] text-ink" : "text-ink2 hover:bg-ink/[0.05] hover:text-ink")}><Icon size={17} strokeWidth={1.75} aria-hidden="true" />{label}</button>))}</nav></aside>- <div className="min-h-0 flex-1 overflow-y-auto">- <div className={cx("mx-auto flex flex-col gap-6 px-8 py-8", section === "analytics" ? "max-w-[960px]" : "max-w-[680px]")}>- <h1 className="text-xl font-semibold tracking-tight text-ink">{SECTIONS.find((s) => s.id === section)?.label}</h1>- {section === "profile" && <Profile />}- {section === "models" && <ModelsSettings />}- {section === "voice" && <VoiceSettings onOpenModels={() => setSection("models")} />}- {section === "notifications" && <NotificationsSettings />}- {section === "channels" && <ChannelsSettings />}- {section === "appearance" && <Appearance />}- {section === "statusbar" && <StatusBarSettings />}- {section === "analytics" && <Analytics />}- {section === "connections" && <Connections current={connection} health={health} onSwitchConnection={onSwitchConnection} />}- {section === "devices" && <Devices current={connection} />}- {section === "startup" && <Startup />}- {section === "about" && <About health={health} onAnalytics={() => setSection("analytics")} />}+ <div className="flex min-h-0 flex-1 flex-col">+ <div className="shrink-0 border-b border-line" data-tauri-drag-region>+ <div className={cx("mx-auto flex items-end gap-1 px-8 pt-5", wide)}>+ <h1 className={cx("mr-5 pb-3 text-xl font-semibold tracking-tight text-ink", group.tabs.length === 1 && "mr-0")}>{group.label}</h1>+ {group.tabs.length > 1 && (+ <div className="flex items-end gap-1" role="tablist" aria-label={group.label}>+ {group.tabs.map((t) => (+ <button key={t.id} role="tab" aria-selected={section === t.id} onClick={() => go(t.id)}+ className={cx("-mb-px border-b-2 px-3 pb-3 text-sm transition-colors", section === t.id ? "border-accent font-medium text-ink" : "border-transparent text-ink3 hover:text-ink")}>+ {t.label}+ </button>+ ))}+ </div>+ )}+ </div>+ </div>+ <div className="min-h-0 flex-1 overflow-y-auto">+ <div className={cx("mx-auto flex flex-col gap-6 px-8 py-8", wide)}>+ {section === "profile" && <Profile />}+ {section === "models" && <ModelsSettings />}+ {section === "voice" && <VoiceSettings onOpenModels={() => go("models")} />}+ {section === "budgets" && <BudgetsSettings />}+ {section === "notifications" && <NotificationsSettings />}+ {section === "channels" && <ChannelsSettings />}+ {section === "appearance" && <Appearance />}+ {section === "statusbar" && <StatusBarSettings />}+ {section === "analytics" && <Analytics />}+ {section === "connections" && <Connections current={connection} health={health} onSwitchConnection={onSwitchConnection} />}+ {section === "devices" && <Devices current={connection} />}+ {section === "startup" && <Startup />}+ {section === "about" && <About health={health} onAnalytics={() => go("analytics")} />}+ </div></div></div></div>diff --git a/src/index.ts b/src/index.tsindex 1979e535..0144b41c 100644--- a/src/index.ts+++ b/src/index.ts@@ -95,7 +95,7 @@ import { selectWithArrowKeys } from './utils/arrow-select.js';import { ProviderModelFetchError, fetchProviderModelCatalog } from './utils/provider-models.js';import { initCloudTokenStore } from './cloud/token-store.js';import { clearCloudRuntimeOnline, markCloudRuntimeOnline } from './cloud/runtime-status.js';-import { startWebServer, stopWebServer, updateStatus as updateWebStatus, setUserMemory as setWebUserMemory, setWebChannel as setWebWebChannel, setScheduler as setWebScheduler, setAgentSupervisor as setWebSupervisor, setBackgroundTaskManager as setWebBgTasks, setSpotifyClient as setWebSpotify, setProgrammingMode as setWebProgrammingMode, setModelSwitchCallback as setWebModelSwitch, setCurrentProviderCallback as setWebCurrentProvider, setStatusSnapshotCallback as setWebStatusSnapshot, setKanbanSupervisor as setWebKanban, setKanbanBoardManager as setWebBoardManager, setKanbanProviders as setWebKanbanProviders, setIDEProviders as setWebIDEProviders, setSessionRepository as setWebSessions, setSessionSyncEnabledCallback as setWebSessionSyncEnabled, setBotManager as setWebBotManager, setBotsWebhookSecret, setShutdownHandler, setMcpManager as setWebMcpManager, setStopCallback as setWebStop, setSessionBusyLookup as setWebSessionBusy } from './web/server.js';+import { startWebServer, stopWebServer, updateStatus as updateWebStatus, setUserMemory as setWebUserMemory, setWebChannel as setWebWebChannel, setScheduler as setWebScheduler, setAgentSupervisor as setWebSupervisor, setBackgroundTaskManager as setWebBgTasks, setSpotifyClient as setWebSpotify, setProgrammingMode as setWebProgrammingMode, setModelSwitchCallback as setWebModelSwitch, setCurrentProviderCallback as setWebCurrentProvider, setStatusSnapshotCallback as setWebStatusSnapshot, setKanbanSupervisor as setWebKanban, setKanbanBoardManager as setWebBoardManager, setKanbanProviders as setWebKanbanProviders, setIDEProviders as setWebIDEProviders, setSessionRepository as setWebSessions, setSessionSyncEnabledCallback as setWebSessionSyncEnabled, setBotManager as setWebBotManager, setBotsWebhookSecret, setShutdownHandler, setMcpManager as setWebMcpManager, setStopCallback as setWebStop, setSessionBusyLookup as setWebSessionBusy, setBudgetControls as setWebBudgetControls } from './web/server.js';import { validateApiKey, validateBaseUrl, validateModelName } from './providers/provider-meta.js';import { setFirstProviderHandler, setProvidersReload } from './web/api/providers.js';import { setCloudReload } from './web/api/cloud.js';@@ -3509,6 +3509,7 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {setCloudReload(() => agent.reloadProviders());setWebStop(() => agent.stopAllWork('stopped'));setWebSessionBusy((sessionId) => agent.isBusyWith(sessionId));+ setWebBudgetControls({ config: () => config, tokens: () => tokenBudget, saver: () => agent.saverMode });setWebCurrentProvider(() => agent.getCurrentProvider());// Live bottom bar for attached terminals and the dashboard: one snapshot,// pushed on every model switch and checked every 2 s for anything else.diff --git a/src/web/api-contract.ts b/src/web/api-contract.tsindex 9129a98b..bd31c3da 100644--- a/src/web/api-contract.ts+++ b/src/web/api-contract.ts@@ -46,6 +46,8 @@ export const API_FEATURES: readonly string[] = Object.freeze(['channels', // GET /api/channels, POST :type/check, PUT :type, POST :type/access, POST/GET signal/link'transcribe', // GET/POST /api/transcribe — dictation: raw audio in, text out'speak', // GET/POST /api/speak — read aloud: text in, MP3 out+ 'budget', // GET/PUT /api/budget — daily cap, Token Saver, bot caps; saves apply live+ 'threads.save', // POST /api/chat/threads/:id/save { saved } — thread.savedAt'cloud.signin', // GET /api/cloud/status, POST/GET/DELETE /api/cloud/signin (browser pairing from any client) // POST /api/voice/check { vendor, key?, endpoint? }'brain.map', // GET /api/brain/map[?archive=1] — themes, sub-themes, notes, related links]);diff --git a/src/web/api/budget-route.test.ts b/src/web/api/budget-route.test.tsnew file mode 100644index 00000000..a04d0918--- /dev/null+++ b/src/web/api/budget-route.test.ts@@ -0,0 +1,75 @@+import { describe, expect, it, vi, beforeEach } from 'vitest';++await vi.hoisted(async () => {+ const fs = await import('node:fs');+ const os = await import('node:os');+ const path = await import('node:path');+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mercury-budget-route-'));+ fs.writeFileSync(path.join(dir, 'mercury.yaml'), 'identity:\n owner: Test\n');+ process.env.MERCURY_HOME = dir;+});++import { loadConfig, type MercuryConfig } from '../../utils/config.js';+import { TokenBudget } from '../../utils/tokens.js';+import { SaverMode } from '../../core/saver-mode.js';+import budget, { setBudgetControls } from './budget.js';++let config: MercuryConfig;+let tokens: TokenBudget;+let saver: SaverMode;++beforeEach(() => {+ config = loadConfig();+ tokens = new TokenBudget(config);+ tokens.setBudget(1_000_000);+ saver = new SaverMode(config);+ saver.disable();+ setBudgetControls({ config: () => config, tokens: () => tokens, saver: () => saver });+});++// eslint-disable-next-line @typescript-eslint/no-explicit-any+const json = async (res: Response): Promise<any> => res.json();+const put = (body: unknown) => budget.request('http://127.0.0.1/api/budget', {+ method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),+});++/** Budgets from any client: what they are, and setting them, live. */+describe('/api/budget', () => {+ it('reports the daily cap, Token Saver and the bot caps', async () => {+ const res = await budget.request('http://127.0.0.1/api/budget');+ expect(res.status).toBe(200);+ expect(await res.json()).toMatchObject({+ daily: { budget: 1_000_000, used: expect.any(Number) },+ saver: { state: 'off', autoEnabled: expect.any(Boolean), autoThreshold: expect.any(Number) },+ bots: { perBot: expect.any(Number), fleet: expect.any(Number) },+ });+ });++ it('sets the daily cap live and saves it', async () => {+ const res = await put({ dailyBudget: 2_500_000 });+ expect(res.status).toBe(200);+ expect((await json(res)).daily.budget).toBe(2_500_000);+ expect(tokens.getBudget()).toBe(2_500_000);+ expect(loadConfig().tokens.dailyBudget).toBe(2_500_000);+ });++ it('turns Token Saver on and sets when it comes on by itself', async () => {+ const body = await json(await put({ saver: { manual: true, autoEnabled: true, autoThreshold: 60 } }));+ expect(body.saver).toMatchObject({ state: 'on', autoEnabled: true, autoThreshold: 60 });+ expect((await json(await put({ saver: { manual: false } }))).saver.state).toBe('off');+ });++ it('sets the bot caps', async () => {+ const body = await json(await put({ bots: { perBot: 300_000, fleet: 0 } }));+ expect(body.bots).toMatchObject({ perBot: 300_000, fleet: 0 });+ expect(loadConfig().bots.suggestedDailyTokenBudget).toBe(300_000);+ });++ it('changes nothing when one field is wrong', async () => {+ const res = await put({ dailyBudget: 3_000_000, saver: { autoThreshold: 400 } });+ expect(res.status).toBe(400);+ expect(tokens.getBudget()).toBe(1_000_000);+ expect((await put({ dailyBudget: 10 })).status).toBe(400);+ expect((await put({ dailyBudget: 'lots' })).status).toBe(400);+ });+});diff --git a/src/web/api/budget.ts b/src/web/api/budget.tsnew file mode 100644index 00000000..6c8ccd31--- /dev/null+++ b/src/web/api/budget.ts@@ -0,0 +1,110 @@+import { Hono } from 'hono';+import { saveConfig, type MercuryConfig } from '../../utils/config.js';+import type { TokenBudget } from '../../utils/tokens.js';+import type { SaverMode } from '../../core/saver-mode.js';++/**+ * Token budgets, readable and settable from any client. Saves apply live+ * and persist to mercury.yaml.+ *+ * GET /api/budget → { daily, saver, bots }+ * PUT /api/budget { dailyBudget?, saver?: { manual?, autoEnabled?, autoThreshold? },+ * bots?: { perBot?, fleet? } } → the same shape as GET+ *+ * daily: today's tokens against the daily cap (Mercury pauses at the cap).+ * saver: Token Saver: on by hand, or on by itself at a share of the cap.+ * bots: the cap a bot gets when it sets none, and the cap for all bots+ * together (0 = no cap).+ */++export interface BudgetControls {+ config: () => MercuryConfig;+ tokens: () => TokenBudget;+ saver: () => SaverMode;+}++let controls: BudgetControls | undefined;+export function setBudgetControls(c: BudgetControls | undefined): void { controls = c; }++const MAX = 1_000_000_000_000;++function snapshot(c: BudgetControls) {+ const tokens = c.tokens();+ const saver = c.saver();+ const cfg = c.config();+ return {+ daily: {+ budget: tokens.getBudget(),+ used: tokens.getDailyUsed(),+ remaining: tokens.getRemaining(),+ percentage: Math.round(tokens.getUsagePercentage()),+ },+ saver: {+ state: saver.getState(),+ autoEnabled: saver.isAutoEnabled(),+ autoThreshold: saver.getAutoThreshold(),+ savedToday: tokens.getSavedToday(),+ savedLifetime: tokens.getSavedLifetime(),+ },+ bots: {+ enabled: !!cfg.bots?.enabled,+ perBot: cfg.bots?.suggestedDailyTokenBudget ?? 5_000_000,+ fleet: cfg.bots?.fleetDailyTokenBudget ?? 0,+ },+ };+}++/** A whole number of tokens in range, or an error message. */+function tokensFrom(value: unknown, what: string, min: number): number | string {+ if (typeof value !== 'number' || !Number.isFinite(value)) return `${what} must be a number of tokens.`;+ const n = Math.round(value);+ if (n < min) return `${what} must be at least ${min.toLocaleString()} tokens.`;+ if (n > MAX) return `${what} is too large.`;+ return n;+}++const budget = new Hono();++budget.get('/api/budget', (c) => {+ if (!controls) return c.json({ error: 'Budgets are not available yet.' }, 503);+ return c.json(snapshot(controls));+});++budget.put('/api/budget', async (c) => {+ if (!controls) return c.json({ error: 'Budgets are not available yet.' }, 503);+ const body = (await c.req.json().catch(() => ({}))) as {+ dailyBudget?: unknown;+ saver?: { manual?: unknown; autoEnabled?: unknown; autoThreshold?: unknown };+ bots?: { perBot?: unknown; fleet?: unknown };+ };++ // Check everything first, so a bad field changes nothing.+ const daily = body.dailyBudget === undefined ? undefined : tokensFrom(body.dailyBudget, 'The daily budget', 1_000);+ const perBot = body.bots?.perBot === undefined ? undefined : tokensFrom(body.bots.perBot, 'The per-bot budget', 0);+ const fleet = body.bots?.fleet === undefined ? undefined : tokensFrom(body.bots.fleet, 'The all-bots budget', 0);+ for (const v of [daily, perBot, fleet]) if (typeof v === 'string') return c.json({ error: v }, 400);+ const s = body.saver ?? {};+ if (s.manual !== undefined && typeof s.manual !== 'boolean') return c.json({ error: 'saver.manual must be true or false.' }, 400);+ if (s.autoEnabled !== undefined && typeof s.autoEnabled !== 'boolean') return c.json({ error: 'saver.autoEnabled must be true or false.' }, 400);+ if (s.autoThreshold !== undefined && (typeof s.autoThreshold !== 'number' || !Number.isFinite(s.autoThreshold) || s.autoThreshold < 1 || s.autoThreshold > 100)) {+ return c.json({ error: 'saver.autoThreshold must be a percentage from 1 to 100.' }, 400);+ }++ const tokens = controls.tokens();+ const saver = controls.saver();+ if (typeof daily === 'number') tokens.setBudget(daily);+ if (typeof s.autoThreshold === 'number') saver.setAutoThreshold(s.autoThreshold);+ if (typeof s.autoEnabled === 'boolean') saver.setAutoEnabled(s.autoEnabled);+ if (s.manual === true && !saver.isManual()) saver.enable();+ if (s.manual === false && saver.isManual()) saver.disable();+ if (typeof perBot === 'number' || typeof fleet === 'number') {+ const cfg = controls.config();+ cfg.bots = cfg.bots ?? ({} as MercuryConfig['bots']);+ if (typeof perBot === 'number') cfg.bots.suggestedDailyTokenBudget = perBot;+ if (typeof fleet === 'number') cfg.bots.fleetDailyTokenBudget = fleet;+ saveConfig(cfg);+ }+ return c.json(snapshot(controls));+});++export default budget;diff --git a/src/web/server.ts b/src/web/server.tsindex 281a7fd6..38ced3b1 100644--- a/src/web/server.ts+++ b/src/web/server.ts@@ -15,6 +15,7 @@ import providerRoutes from './api/providers.js';import cloudRoutes from './api/cloud.js';import transcribeRoutes from './api/transcribe.js';import speakRoutes from './api/speak.js';+import budgetRoutes, { setBudgetControls } from './api/budget.js';import channelRoutes from './api/channels.js';import artifactRoutes from './api/artifacts.js';import configRoutes from './api/config.js';@@ -34,6 +35,7 @@ import { BoardManager } from '../core/board-manager.js';import { isBetterSqlite3Available } from '../memory/second-brain-db.js';export { setSessionRepository };+export { setBudgetControls };export { setSessionSyncEnabledCallback };const app = new Hono();@@ -99,6 +101,7 @@ app.route('/', providerRoutes);app.route('/', cloudRoutes);app.route('/', transcribeRoutes);app.route('/', speakRoutes);+app.route('/', budgetRoutes);app.route('/', channelRoutes);app.route('/', artifactRoutes);app.route('/', configRoutes);