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
HTML agent-harnessagent-orchestrationagentsai-agentsautonomous-agentsclaude-codecodexcoding-agentsdesktop-appdeveloper-toolselectrongemini-cliharnessharness-engineeringlocal-firstmemorymulti-agentopencodeorchestrationtypescript
integrate: Lane A scheduling (#1/#2 heartbeat, #6 breaker/durability/ledger)
Chaitanya Giri939920580163
diff --cc src/main/hooks.tsindex 851306ef,120363d3..cc9e2743--- a/src/main/hooks.ts+++ b/src/main/hooks.ts@@@ -16,7 -16,7 +16,8 @@@ import { existsSync, rmSync } from 'nodimport { Notification, type WebContents } from 'electron';import type { HiveManager } from './hive';import type { HarnessConfig } from './config';+import type { ControlRegistry } from './control';+ import type { CircuitBreaker } from './breaker';interface HookPayload {hook_event_name?: string;@@@ -41,8 -41,9 +42,11 @@@ export class HookServerprivate hive: HiveManager,private getWebContents: () => WebContents | null,private getConfig: () => HarnessConfig,+ /** #7C — operator control state. Optional so tests can omit it. */- private control?: ControlRegistry++ private control?: ControlRegistry,+ /** Circuit breaker (Lane A #6.6b) — fed the hook-derived signals (session id,+ * repeated identical tool calls). Optional so the server still runs without it. */+ private breaker?: CircuitBreaker) {}start(): void {@@@ -80,14 -81,16 +84,24 @@@const agentId = p.agent_id ?? undefined;const event = p.hook_event_name ?? 'Unknown';+ // 7C.3 — a graceful operator HALT overrides everything (incl. the inbox+ // drain below): stop the agent CLEANLY at this hook boundary rather than+ // killing the PTY. session_id is in the payload for a later --resume.+ if (agentId && this.control?.shouldHalt(agentId)) {+ this.emit(agentId, event, p);+ return { continue: false, stopReason: 'Halted by the operator from the floor.' };+ }++ // Capture the Claude Code session id for idempotent --resume + cost dedup+ // (Lane A #6.6a). Cheap: recordSession writes only when it changes.+ if (agentId && p.session_id) this.hive.recordSession(agentId, p.session_id);++ // Feed the breaker its hook-derived loop signal: a tool that actually ran.+ // A repeated identical (name+input) PostToolUse is the runaway-loop tell.+ if (event === 'PostToolUse' && agentId) {+ this.breaker?.recordToolUse(agentId, p.tool_name, p.tool_input);+ }+if ((event === 'Stop' || event === 'SubagentStop') && agentId) {// Loop guard: a previous Stop hook already blocked this turn → let it stop.if (p.stop_hook_active) { this.emit(agentId, event, p); return {}; }diff --cc src/main/index.tsindex 9dabaf36,be558dd5..bc7405a4--- a/src/main/index.ts+++ b/src/main/index.ts@@@ -14,14 -14,13 +14,15 @@@ import} from './git';import { HiveManager, type AgentMeta, type HiveMessage, type HiveTask } from './hive';import { HookServer } from './hooks';+ import { CircuitBreaker, type BreakerInput } from './breaker';-import { StubUsageProvider, type UsageProvider } from './usage';++import type { UsageProvider } from './usage';import { MemoryManager } from './memory';import { enrichMessage } from './assistant';import { readAgentUsage } from './transcript';import { listIssues, listCIRuns } from './github';import { SlackWebhookServer } from './slack';+import { TelemetryCollector } from './telemetry';- import { CircuitBreaker } from './breaker';+import { ControlRegistry } from './control';const isDev = !!process.env.ELECTRON_RENDERER_URL;const ptyManager = new PtyManager();@@@ -32,26 -31,22 +33,35 @@@ const hive = new HiveManager() => readConfig().harnessHome,(channel, payload) => { try { liveWebContents()?.send(channel, payload); } catch { /* window tore down */ } });-// Circuit breaker (Lane A #6.6b) — POLICY only; the heartbeat beat feeds it-// signals + enforces its decisions. Config is read live so a settings change-// takes effect on the next beat.+// #7C — operator control state (pause/gate/steer/halt), read by the HookServer+// when deciding hook returns.+const control = new ControlRegistry();- const hookServer = new HookServer(hive, () => liveWebContents(), () => readConfig(), control);+// Stage 7A — the live observability tap. Receives Claude Code's first-party OTel+// over loopback OTLP/JSON and exposes the locked usage-provider seam. resolveCwd+// lets the transcript fallback find an agent's cwd from the hive registry.+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 */ } }- });++// Usage provider (Seam 1) — the INTEGRATION swap: Oscar's telemetry collector (#7)++// IS the provider, replacing Lane A's interim StubUsageProvider. Same++// getAgentUsage(agentId) pull seam, so the breaker + cost ledger consumers are++// untouched; telemetry has a transcript fallback built in, so it works before any++// live OTel arrives.++const usageProvider: UsageProvider = telemetry;++// Circuit breaker (Lane A #6.6b) — the REAL policy (replaces Lane C's interim++// glue). POLICY only; the heartbeat beat feeds it signals (via usageProvider) +++// enforces its decisions. Config read live so a settings change applies next beat.+ const breaker = new CircuitBreaker(() => {+ const c = readConfig();+ return { ...(c.circuitBreaker ?? {}), costCapUsd: c.costCapUsd };+ });-// Usage provider (Lane A #6.6 Seam 1) — interim transcript-backed stub; swap to-// Oscar's module (#7) at integration with no change to the breaker/ledger. The-// resolver turns an agentId into the transcript cwd + the session/cost key.-const usageProvider: UsageProvider = new StubUsageProvider((agentId) => {- const a = hive.registry().agents[agentId];- if (!a?.cwd) return null;- return { cwd: a.cwd, sessionId: hive.lastSession(agentId) ?? null, model: undefined };-});-const hookServer = new HookServer(hive, () => liveWebContents(), () => readConfig(), breaker);++// Feed the breaker's api_error-storm trip from Oscar's OTel api_error spans —++// Jim's one breaker input with no on-branch source (telemetry.onApiError seam).++telemetry.onApiError((agentId) => breaker.recordError(agentId));++// HookServer needs BOTH: Oscar's control registry (HITL pause/gate/steer/halt via++// hook returns) AND Jim's breaker (feed recordToolUse on each PostToolUse).++const hookServer = new HookServer(hive, () => liveWebContents(), () => readConfig(), control, breaker);const memory = new MemoryManager(() => readConfig().harnessHome,() => { const c = readConfig(); return { enabled: c.semanticMemory !== false, model: c.embeddingModel ?? 'minilm' }; }@@@ -521,8 -739,6 +754,7 @@@ ipcMain.handle('app:confirmClose', () =try { clearMissionTimers(); } catch (e) { console.error('[quit] clearMissionTimers:', e); }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); }@@@ -539,8 -755,6 +771,7 @@@ ipcMain.handle('app:resetAll', () =>try { clearMissionTimers(); } catch (e) { console.error('[reset] clearMissionTimers:', e); }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); }@@@ -713,14 -876,6 +944,16 @@@ app.whenReady().then(() =>ensureDefaultMissions(); // one-time: seed the built-in hourly ops standupsyncMissions(); // arm recurring auto-dispatch missions now the router is livehookServer.start();+ // Bind the telemetry collector BEFORE the renderer spawns any agent, then+ // point the hive at it so every subsequent spawn is instrumented. Best-effort+ // — a bind failure just leaves telemetry off (transcript reconciler stays).+ void telemetry.start().then((r) => {+ 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)++ // No breaker.start() — the breaker is POLICY-only, ticked by the heartbeat++ // beat (#1, ships disabled), so it's dormant until the user opts in. (Lane A++ // #6 replaced Lane C's interim self-polling breaker at integration.)memory.start(); // init shared palace + mine loop (no-op without mempalace)}createWindow();diff --cc src/renderer/src/components/SettingsModal.tsxindex e8cd6365,6665e841..8b2da489--- a/src/renderer/src/components/SettingsModal.tsx+++ b/src/renderer/src/components/SettingsModal.tsx@@@ -67,23 -67,6 +67,33 @@@ export function SettingsModal({ configcatch { 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) : '');++ // ─── circuit-breaker config (Lane A #6 canonical fields, widened view) ───────++ // Drives Jim's real breaker: floor-wide cost cap (costCapUsd) + output-token++ // velocity ceiling (circuitBreaker.tokenVelocityPerMin). The interim Lane C++ // knobs were dropped at integration.++ type BreakerCfgView = HarnessConfig & {++ costCapUsd?: number;++ circuitBreaker?: { tokenVelocityPerMin?: number; enabled?: boolean; hardStop?: boolean; repeatedToolLimit?: number; errorStormLimit?: number };++ };++ const breakerCfg = config as BreakerCfgView;++ const [agentBudget, setAgentBudget] = useState(breakerCfg.costCapUsd != null ? String(breakerCfg.costCapUsd) : '');++ const [velocityCeiling, setVelocityCeiling] = useState(breakerCfg.circuitBreaker?.tokenVelocityPerMin != null ? String(breakerCfg.circuitBreaker.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++ costCapUsd: Number.isFinite(usd as number) ? (usd as number) : undefined,++ circuitBreaker: {++ ...(breakerCfg.circuitBreaker ?? {}),++ tokenVelocityPerMin: Number.isFinite(vel as number) ? (vel as number) : undefined++ }+ } as Partial<HarnessConfig>);+ setBudgetNote('saved');+ setTimeout(() => setBudgetNote(''), 1500);+ };+// ─── Slack integration ─────────────────────────────────────────────────────const slackCfg = config as SlackConfig;const [slackEnabled, setSlackEnabled] = useState(slackCfg.slackEnabled ?? false);@@@ -201,44 -184,6 +211,44 @@@<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)++ floor cost cap (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 }}>