Skip to content

an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions

feat(7C.4): cost/runaway circuit breaker (interim glue) + budget config

Chaitanya Giri36d742e07bf0
diff --git a/src/main/breaker.ts b/src/main/breaker.ts
new file mode 100644
index 00000000..3726ad2d
--- /dev/null
+++ b/src/main/breaker.ts
@@ -0,0 +1,114 @@
+/**
+ * CircuitBreaker — the cost/runaway guardrail (#7C.4), INTERIM glue.
+ *
+ * ⚠ OWNERSHIP: this is the Lane C "glue" — it wires the telemetry SOURCE
+ * (telemetry.ts `getAgentUsage`, mine) to the BreakerState consumer (the avatar
+ * adapter + fleet meter, also mine). The breaker POLICY — the full trip-condition
+ * set (repeated-identical-tool-call loops, error storms, no-progress) and the
+ * steer→constrain→stop escalation ladder — is Lane A's #6 and will REPLACE this.
+ * Kept deliberately small and swap-trivial: it needs only `getAgentUsage` + an
+ * `emit`, exactly the locked seams. The two conditions implemented here (budget
+ * and token-velocity) are the ones computable purely from usage samples.
+ *
+ * Runs as an in-process poll (the syncMissions pattern, NOT launchd) in the
+ * Electron main process. No `electron` import so it stays unit-testable.
+ */
+import type { AgentUsageSample, BreakerState } from './telemetry';
+
+export type BreakerLevel = BreakerState['level'];
+
+export interface BreakerConfig {
+ /** Per-agent USD cap. Undefined = no budget tripping. */
+ agentBudgetUsd?: number;
+ /** Tokens/min ceiling. Undefined = no velocity tripping. */
+ tokenVelocityPerMin?: number;
+}
+
+export interface CircuitBreakerOptions {
+ /** Pull cumulative usage for an agent (the locked provider seam). */
+ getAgentUsage: (agentId: string) => AgentUsageSample | null;
+ /** The agent ids to evaluate each tick (live PTY agents). */
+ liveAgents: () => string[];
+ /** Current budget/velocity knobs (read fresh each tick so config edits apply). */
+ config: () => BreakerConfig;
+ /** Emit a state change — wired to the control:breakerState fan-out. */
+ emit: (state: BreakerState) => void;
+ /** Poll interval; default 5s (matches the metric export cadence). */
+ intervalMs?: number;
+ /** Clock injection for tests. Defaults to Date.now. */
+ now?: () => number;
+}
+
+interface Track {
+ level: BreakerLevel;
+ lastTotal: number;
+ lastTs: number;
+}
+
+function totalTokens(s: AgentUsageSample): number {
+ return s.input + s.output + s.cacheRead + s.cacheCreation;
+}
+
+export class CircuitBreaker {
+ private timer: NodeJS.Timeout | null = null;
+ private readonly tracks = new Map<string, Track>();
+ private readonly o: Required<Pick<CircuitBreakerOptions, 'intervalMs' | 'now'>> & CircuitBreakerOptions;
+
+ constructor(opts: CircuitBreakerOptions) {
+ this.o = { intervalMs: 5000, now: () => Date.now(), ...opts };
+ }
+
+ start(): void {
+ if (this.timer) return;
+ this.timer = setInterval(() => { try { this.tick(); } catch { /* never crash the poll */ } }, this.o.intervalMs);
+ }
+
+ stop(): void {
+ if (this.timer) { clearInterval(this.timer); this.timer = null; }
+ }
+
+ /** One evaluation pass. Public so a test can drive it deterministically. */
+ tick(): void {
+ const cfg = this.o.config();
+ const now = this.o.now();
+ for (const agentId of this.o.liveAgents()) {
+ const usage = this.o.getAgentUsage(agentId);
+ if (!usage) continue;
+ const total = totalTokens(usage);
+ const prev = this.tracks.get(agentId);
+ const velocity = prev && now > prev.lastTs
+ ? (total - prev.lastTotal) / ((now - prev.lastTs) / 60000)
+ : 0;
+
+ const { level, reason } = this.evaluate(usage.usd, velocity, cfg);
+
+ if (!prev) {
+ this.tracks.set(agentId, { level, lastTotal: total, lastTs: now });
+ if (level !== 'healthy') this.o.emit({ agentId, level, reason, ts: now });
+ continue;
+ }
+ prev.lastTotal = total;
+ prev.lastTs = now;
+ if (level !== prev.level) {
+ prev.level = level;
+ this.o.emit({ agentId, level, reason, ts: now });
+ }
+ }
+ }
+
+ /** Map (spend, velocity, config) → a breaker level. Budget dominates velocity. */
+ private evaluate(usd: number, velocity: number, cfg: BreakerConfig): { level: BreakerLevel; reason: string } {
+ const budget = cfg.agentBudgetUsd;
+ if (budget && budget > 0) {
+ if (usd >= budget) return { level: 'stopped', reason: `budget exceeded ($${usd.toFixed(2)} ≥ $${budget})` };
+ if (usd >= budget * 0.9) return { level: 'constrained', reason: `near budget ($${usd.toFixed(2)} of $${budget})` };
+ if (usd >= budget * 0.75) return { level: 'steering', reason: `approaching budget ($${usd.toFixed(2)} of $${budget})` };
+ }
+ const ceiling = cfg.tokenVelocityPerMin;
+ if (ceiling && ceiling > 0 && velocity > 0) {
+ if (velocity >= ceiling * 2) return { level: 'constrained', reason: `token velocity ${Math.round(velocity).toLocaleString()}/min (>2× ceiling)` };
+ if (velocity >= ceiling) return { level: 'steering', reason: `token velocity ${Math.round(velocity).toLocaleString()}/min (> ceiling)` };
+ }
+ return { level: 'healthy', reason: 'ok' };
+ }
+}
diff --git a/src/main/config.ts b/src/main/config.ts
index a83ce5bf..3865588a 100644
--- a/src/main/config.ts
+++ b/src/main/config.ts
@@ -69,6 +69,13 @@ export interface HarnessConfig {
slackChannelId?: string;
/** Local HTTP port the webhook server binds to (default 3847). */
slackPort?: number;
+ /** #7C.4 circuit breaker — per-agent USD budget; the breaker constrains an
+ * agent approaching it and stops it at the cap. Undefined = no cap (off). */
+ agentBudgetUsd?: number;
+ /** #7C.4 — token-velocity ceiling (tokens/min) above which the breaker arms.
+ * Undefined = velocity tripping off (budget-only). Lane A #6 owns the full
+ * policy; these are the interim, user-tunable knobs. */
+ tokenVelocityPerMin?: number;
}
const DEFAULTS: HarnessConfig = {
diff --git a/src/main/index.ts b/src/main/index.ts
index 9ee39cd6..abe59d23 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -20,6 +20,7 @@ import { readAgentUsage } from './transcript';
import { listIssues, listCIRuns } from './github';
import { SlackWebhookServer } from './slack';
import { TelemetryCollector } from './telemetry';
+import { CircuitBreaker } from './breaker';
const isDev = !!process.env.ELECTRON_RENDERER_URL;
const ptyManager = new PtyManager();
@@ -38,6 +39,15 @@ const telemetry = new TelemetryCollector({
emit: (channel, payload) => { try { liveWebContents()?.send(channel, payload); } catch { /* window tore down */ } },
resolveCwd: (agentId) => hive.registry().agents[agentId]?.cwd ?? null
});
+// #7C.4 — interim cost/runaway breaker (Lane A #6 owns the real policy; this is
+// the swap-trivial glue). Pulls the locked usage seam, emits BreakerState on the
+// same control:breakerState channel the renderer's avatar adapter consumes.
+const breaker = new CircuitBreaker({
+ getAgentUsage: (agentId) => telemetry.getAgentUsage(agentId),
+ liveAgents: () => Array.from(ptyToAgent.values()),
+ config: () => { const c = readConfig(); return { agentBudgetUsd: c.agentBudgetUsd, tokenVelocityPerMin: c.tokenVelocityPerMin }; },
+ emit: (state) => { try { liveWebContents()?.send('control:breakerState', state); } catch { /* window tore down */ } }
+});
const memory = new MemoryManager(
() => readConfig().harnessHome,
() => { const c = readConfig(); return { enabled: c.semanticMemory !== false, model: c.embeddingModel ?? 'minilm' }; }
@@ -508,6 +518,7 @@ ipcMain.handle('app:confirmClose', () => {
try { hive.stopRouter(); } catch (e) { console.error('[quit] stopRouter:', e); }
try { hookServer.stop(); } catch (e) { console.error('[quit] hookServer.stop:', e); }
try { telemetry.stop(); } catch (e) { console.error('[quit] telemetry.stop:', e); }
+ try { breaker.stop(); } catch (e) { console.error('[quit] breaker.stop:', e); }
try { stopSlackServer(); } catch (e) { console.error('[quit] slack.stop:', e); }
try { memory.stop(); } catch (e) { console.error('[quit] memory.stop:', e); }
try { ptyManager.killAll(); } catch (e) { console.error('[quit] killAll:', e); }
@@ -525,6 +536,7 @@ ipcMain.handle('app:resetAll', () => {
try { hive.stopRouter(); } catch (e) { console.error('[reset] stopRouter:', e); }
try { hookServer.stop(); } catch (e) { console.error('[reset] hookServer.stop:', e); }
try { telemetry.stop(); } catch (e) { console.error('[reset] telemetry.stop:', e); }
+ try { breaker.stop(); } catch (e) { console.error('[reset] breaker.stop:', e); }
try { stopSlackServer(); } catch (e) { console.error('[reset] slack.stop:', e); }
try { memory.stop(); } catch (e) { console.error('[reset] memory.stop:', e); }
try { ptyManager.killAll(); } catch (e) { console.error('[reset] killAll:', e); }
@@ -674,6 +686,7 @@ app.whenReady().then(() => {
if (r.ok && r.endpoint) { hive.setOtelEndpoint(r.endpoint); console.log('[telemetry] collector listening', r.endpoint); }
else console.error('[telemetry] collector failed to start:', r.error);
});
+ breaker.start(); // #7C.4 — in-process cost/runaway poll (dormant until budgets set)
memory.start(); // init shared palace + mine loop (no-op without mempalace)
}
createWindow();
diff --git a/src/preload/index.ts b/src/preload/index.ts
index b069da62..9b10d7ab 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -96,6 +96,9 @@ export interface HarnessConfig {
embeddingModel: 'minilm' | 'embeddinggemma';
missions?: ScheduledMission[];
notifications?: boolean;
+ /** #7C.4 circuit-breaker knobs (undefined = off). */
+ agentBudgetUsd?: number;
+ tokenVelocityPerMin?: number;
}
export interface MemoryStatus {
diff --git a/src/renderer/src/components/SettingsModal.tsx b/src/renderer/src/components/SettingsModal.tsx
index 6665e841..e8cd6365 100644
--- a/src/renderer/src/components/SettingsModal.tsx
+++ b/src/renderer/src/components/SettingsModal.tsx
@@ -67,6 +67,23 @@ export function SettingsModal({ config, onClose }: SettingsModalProps) {
catch { setNotifications(!next); /* revert on failure */ }
};
+ // ─── #7C.4 circuit-breaker budgets (optional config fields, widened view) ────
+ const breakerCfg = config as HarnessConfig & { agentBudgetUsd?: number; tokenVelocityPerMin?: number };
+ const [agentBudget, setAgentBudget] = useState(breakerCfg.agentBudgetUsd != null ? String(breakerCfg.agentBudgetUsd) : '');
+ const [velocityCeiling, setVelocityCeiling] = useState(breakerCfg.tokenVelocityPerMin != null ? String(breakerCfg.tokenVelocityPerMin) : '');
+ const [budgetNote, setBudgetNote] = useState('');
+ const saveBudget = async () => {
+ // Empty input clears the cap (undefined = off).
+ const usd = agentBudget.trim() === '' ? undefined : Number(agentBudget);
+ const vel = velocityCeiling.trim() === '' ? undefined : Number(velocityCeiling);
+ await window.cth.updateConfig({
+ agentBudgetUsd: Number.isFinite(usd as number) ? usd : undefined,
+ tokenVelocityPerMin: Number.isFinite(vel as number) ? vel : undefined
+ } as Partial<HarnessConfig>);
+ setBudgetNote('saved');
+ setTimeout(() => setBudgetNote(''), 1500);
+ };
+
// ─── Slack integration ─────────────────────────────────────────────────────
const slackCfg = config as SlackConfig;
const [slackEnabled, setSlackEnabled] = useState(slackCfg.slackEnabled ?? false);
@@ -184,6 +201,44 @@ export function SettingsModal({ config, onClose }: SettingsModalProps) {
<div style={{ height: 2, background: 'var(--cth-ink-300)' }} />
+ {/* #7C.4 — cost / runaway circuit breaker */}
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
+ <span style={{ fontSize: 14, lineHeight: '20px', color: 'var(--cth-ink-900)' }}>
+ Circuit breaker
+ </span>
+ <span style={{ fontSize: 12, lineHeight: '16px', color: 'var(--cth-ink-500)' }}>
+ Guard against runaway spend. Blank = off. The breaker steers, then constrains, then stops an agent that crosses these.
+ </span>
+ </div>
+ <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
+ <label style={{ display: 'flex', flexDirection: 'column', gap: 4, ...slackLabelStyle }}>
+ per-agent budget (USD)
+ <input
+ type="number" min="0" step="0.5" value={agentBudget}
+ onChange={(e) => setAgentBudget(e.target.value)}
+ placeholder="e.g. 5"
+ style={{ ...slackInputStyle, width: 140 }}
+ />
+ </label>
+ <label style={{ display: 'flex', flexDirection: 'column', gap: 4, ...slackLabelStyle }}>
+ token velocity (tok/min)
+ <input
+ type="number" min="0" step="1000" value={velocityCeiling}
+ onChange={(e) => setVelocityCeiling(e.target.value)}
+ placeholder="e.g. 200000"
+ style={{ ...slackInputStyle, width: 160 }}
+ />
+ </label>
+ </div>
+ <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
+ <PixelButton variant="secondary" size="sm" onClick={saveBudget}>save</PixelButton>
+ {budgetNote && <span style={{ fontSize: 12, color: 'var(--cth-mint)' }}>{budgetNote}</span>}
+ </div>
+ </div>
+
+ <div style={{ height: 2, background: 'var(--cth-ink-300)' }} />
+
{/* Slack integration */}
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>