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

merge: repurpose agent-card progress bar as a context-window gauge (#12)

Chaitanya Giri017d00f15cf6
diff --cc src/main/hooks.ts
index cc9e2743,d3587a71..ab47a497
--- a/src/main/hooks.ts
+++ b/src/main/hooks.ts
@@@ -83,25 -86,10 +93,28 @@@ export class HookServer
private handle(p: HookPayload): unknown {
const agentId = p.agent_id ?? undefined;
const event = p.hook_event_name ?? 'Unknown';
+ if (agentId && typeof p.transcript_path === 'string' && p.transcript_path) {
+ this.transcriptPaths.set(agentId, p.transcript_path);
+ }
+ // 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.ts
index 75af3d56,d515cbc4..fe623369
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@@ -14,17 -14,11 +14,17 @@@ import
} from './git';
import { HiveManager, type AgentMeta, type HiveMessage, type HiveTask } from './hive';
import { HookServer } from './hooks';
+import { CircuitBreaker, type BreakerInput } from './breaker';
+import type { UsageProvider } from './usage';
import { MemoryManager } from './memory';
+import { MemoryReflector, type ReflectSettings } from './reflect';
+import { PersistStore } from './db';
import { enrichMessage } from './assistant';
- import { readAgentUsage } from './transcript';
+ import { readAgentUsage, readContextTokens } from './transcript';
import { listIssues, listCIRuns } from './github';
import { SlackWebhookServer } from './slack';
+import { TelemetryCollector } from './telemetry';
+import { ControlRegistry } from './control';
const isDev = !!process.env.ELECTRON_RENDERER_URL;
const ptyManager = new PtyManager();
@@@ -957,60 -503,17 +957,68 @@@ ipcMain.handle('app:resetAll', () =>
});
// ─── IPC: token telemetry (real usage + est. cost from CC transcripts) ───────
+// Reconciler/fallback path: per-cwd transcript sum, now priced PER MODEL (cost
+// bug #1 fixed in pricing.ts). Kept for back-compat with the existing UsageRow.
ipcMain.handle('hive:agentUsage', (_evt, cwd: unknown) =>
typeof cwd === 'string' ? readAgentUsage(cwd) : null);
+ // Current context size (tokens) of an agent's LIVE session — the transcript
+ // path is learned from the agent's hook payloads, so this works even when
+ // several agents share one cwd. Null until the first hook fires.
+ ipcMain.handle('hive:agentContext', (_evt, agentId: unknown) => {
+ if (typeof agentId !== 'string') return null;
+ const tp = hookServer.transcriptPath(agentId);
+ return tp ? readContextTokens(tp) : null;
+ });
+// ─── IPC: live telemetry (the OTel collector — the locked usage-provider seam) ─
+// The fleet grid + span waterfall (#7B) read these; Lane A's breaker (#6)
+// consumes getAgentUsage in-process via the provider, not over IPC.
+ipcMain.handle('telemetry:usage', (_evt, agentId: unknown) =>
+ typeof agentId === 'string' ? telemetry.getAgentUsage(agentId) : null);
+ipcMain.handle('telemetry:spans', (_evt, agentId: unknown) =>
+ typeof agentId === 'string' ? telemetry.getSpans(agentId) : []);
+ipcMain.handle('telemetry:snapshot', () => telemetry.snapshot());
+
+// ─── IPC: circuit-breaker state (Lane A #6 policy → this lane's avatars/meter) ─
+// Lane A's breaker calls this with a BreakerState; we fan it out to the renderer
+// on `control:breakerState`, where the avatar adapter gives it precedence over
+// hook-derived status (#5C looping/zombie). Defined here so the channel exists
+// before Jim's policy lands; he produces, this lane consumes.
+ipcMain.handle('control:setBreakerState', (_evt, state: unknown) => {
+ try { liveWebContents()?.send('control:breakerState', state); } catch { /* window tore down */ }
+ return { ok: true };
+});
+
+// ─── IPC: operator control over agents (#7C.1–7C.3) ─────────────────────────
+// All return the agent's fresh control snapshot so the UI can reflect state.
+ipcMain.handle('control:pause', (_evt, agentId: unknown, on: unknown) => {
+ if (typeof agentId !== 'string') return null;
+ control.pause(agentId, on === true);
+ return control.snapshot(agentId);
+});
+ipcMain.handle('control:resume', (_evt, agentId: unknown) => {
+ if (typeof agentId !== 'string') return null;
+ control.resume(agentId);
+ return control.snapshot(agentId);
+});
+ipcMain.handle('control:gateTool', (_evt, agentId: unknown, tool: unknown, on: unknown) => {
+ if (typeof agentId !== 'string' || typeof tool !== 'string') return null;
+ control.gateTool(agentId, tool, on === true);
+ return control.snapshot(agentId);
+});
+ipcMain.handle('control:steer', (_evt, agentId: unknown, text: unknown) => {
+ if (typeof agentId !== 'string' || typeof text !== 'string') return null;
+ control.steer(agentId, text);
+ return control.snapshot(agentId);
+});
+ipcMain.handle('control:halt', (_evt, agentId: unknown) => {
+ if (typeof agentId !== 'string') return null;
+ control.halt(agentId);
+ return control.snapshot(agentId);
+});
+ipcMain.handle('control:snapshot', (_evt, agentId: unknown) =>
+ typeof agentId === 'string' ? control.snapshot(agentId) : null);
+
// ─── IPC: scheduled missions (recurring auto-dispatch) ──────────────────────
ipcMain.handle('missions:list', () => readConfig().missions ?? []);
ipcMain.handle('missions:save', (_evt, missions) => {
diff --cc src/main/transcript.ts
index ee76119b,0c729ba6..3d1793bf
--- a/src/main/transcript.ts
+++ b/src/main/transcript.ts
@@@ -1,7 -1,6 +1,7 @@@
- import { existsSync, readdirSync, readFileSync } from 'node:fs';
+ import { closeSync, existsSync, fstatSync, openSync, readSync, readdirSync, readFileSync } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
+import { estimateCostUsd, normalizeModel } from './pricing';
/** Resolve the Claude Code transcript directory for a given working directory.
* Claude Code stores per-project transcripts under ~/.claude/projects, keying
diff --cc src/preload/index.ts
index e9983417,2ed73d55..d02b7252
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@@ -390,64 -278,15 +390,69 @@@ const api =
// ─── Token telemetry (real usage + est. cost from CC transcripts) ──────────
/** Sum input/output/cache tokens + estimated USD cost for an agent from its
- * Claude Code transcripts. Returns null for an invalid cwd. */
+ * Claude Code transcripts (reconciler/fallback). Returns null for an invalid cwd. */
agentUsage: (cwd: string): Promise<AgentUsage | null> =>
ipcRenderer.invoke('hive:agentUsage', cwd),
+ /** Current context size (tokens) of an agent's live session, read from the
+ * last assistant message of its transcript. Null until the agent's hooks
+ * have fired at least once (the transcript path is learned from them). */
+ agentContext: (agentId: string): Promise<number | null> =>
+ ipcRenderer.invoke('hive:agentContext', agentId),
+ // ─── Live telemetry (OTel collector — the usage-provider seam + spans) ──────
+ /** Live cumulative usage for an agent (OTel-preferred, transcript fallback). */
+ telemetryUsage: (agentId: string): Promise<AgentUsageSample | null> =>
+ ipcRenderer.invoke('telemetry:usage', agentId),
+ /** Recent tool spans for an agent's waterfall (#7B.2). */
+ telemetrySpans: (agentId: string): Promise<ToolSpan[]> =>
+ ipcRenderer.invoke('telemetry:spans', agentId),
+ /** Cold-start backfill of all agents' usage + recent spans. */
+ telemetrySnapshot: (): Promise<TelemetrySnapshot> =>
+ ipcRenderer.invoke('telemetry:snapshot'),
+ /** Subscribe to live telemetry pushes; returns an unsubscribe fn. */
+ onTelemetryEvent: (cb: (e: TelemetryEvent) => void): (() => void) => {
+ const listener = (_e: IpcRendererEvent, payload: TelemetryEvent) => cb(payload);
+ ipcRenderer.on('telemetry:event', listener);
+ return () => ipcRenderer.removeListener('telemetry:event', listener);
+ },
+
+ // ─── Circuit breaker (Lane A #6 state → avatars/meter) ──────────────────────
+ /** Subscribe to breaker-state changes; returns an unsubscribe fn. */
+ onBreakerState: (cb: (s: BreakerState) => void): (() => void) => {
+ const listener = (_e: IpcRendererEvent, payload: BreakerState) => cb(payload);
+ ipcRenderer.on('control:breakerState', listener);
+ return () => ipcRenderer.removeListener('control:breakerState', listener);
+ },
+ /** Push a breaker state to the renderer (Lane A's policy / interim glue calls this). */
+ setBreakerState: (state: BreakerState): Promise<{ ok: boolean }> =>
+ ipcRenderer.invoke('control:setBreakerState', state),
+
+ // ─── Operator control over agents (#7C.1–7C.3) ──────────────────────────────
+ /** Pause/unpause an agent — paused → its tool calls are denied at PreToolUse. */
+ controlPause: (agentId: string, on: boolean): Promise<AgentControlSnapshot | null> =>
+ ipcRenderer.invoke('control:pause', agentId, on),
+ /** Clear pause + halt so the agent can run again. */
+ controlResume: (agentId: string): Promise<AgentControlSnapshot | null> =>
+ ipcRenderer.invoke('control:resume', agentId),
+ /** Gate/ungate a specific tool for an agent (denied at PreToolUse). */
+ controlGateTool: (agentId: string, tool: string, on: boolean): Promise<AgentControlSnapshot | null> =>
+ ipcRenderer.invoke('control:gateTool', agentId, tool, on),
+ /** Queue a steer note — injected as context on the agent's next hook (#7C.2). */
+ controlSteer: (agentId: string, text: string): Promise<AgentControlSnapshot | null> =>
+ ipcRenderer.invoke('control:steer', agentId, text),
+ /** Request a graceful stop at the next hook boundary (#7C.3). */
+ controlHalt: (agentId: string): Promise<AgentControlSnapshot | null> =>
+ ipcRenderer.invoke('control:halt', agentId),
+ /** Read an agent's current control snapshot. */
+ controlSnapshot: (agentId: string): Promise<AgentControlSnapshot | null> =>
+ ipcRenderer.invoke('control:snapshot', agentId),
+ /** Subscribe to gate/deny events (a tool was blocked); returns unsubscribe fn. */
+ onApprovalRequest: (cb: (e: { agentId: string; tool?: string; reason?: string }) => void): (() => void) => {
+ const listener = (_e: IpcRendererEvent, payload: { agentId: string; tool?: string; reason?: string }) => cb(payload);
+ ipcRenderer.on('control:approvalRequest', listener);
+ return () => ipcRenderer.removeListener('control:approvalRequest', listener);
+ },
+
// ─── Task kanban (hive/tasks.json) ───────────────────────────────────────
/** Overwrite the hive task ledger with the full task list and commit it. */
hiveWriteTasks: (tasks: HiveTask[]): Promise<{ ok: boolean; error?: string }> =>
diff --cc src/renderer/src/hooks/useHive.ts
index 11403cb0,66e40731..5f667462
--- a/src/renderer/src/hooks/useHive.ts
+++ b/src/renderer/src/hooks/useHive.ts
@@@ -318,22 -265,30 +318,46 @@@ export function useHive(config: Harness
});
}, []);
- // 2b) Context gauge: poll each live agent's current context size (tokens)
- // from its session transcript and map it onto the agent card's 8-segment
- // bar — a fuel gauge for how close the session is to its context limit.
+ // 2b) Consume circuit-breaker state (#7C.4/#5C). Lane A's breaker policy (#6)
+ // pushes BreakerState on `control:breakerState`; this gives it PRECEDENCE
+ // over hook-derived status: a constrained/stopped agent is pinned to
+ // 'looping' (see the breakerArmed guard above) until it genuinely Stops.
+ useEffect(() => {
+ return window.cth.onBreakerState((s) => {
+ breakerLevel.current[s.agentId] = s.level;
+ const { updateAgent, agents } = useStore.getState();
+ if (!agents.some((a) => a.id === s.agentId)) return;
+ if (s.level === 'constrained' || s.level === 'stopped') {
+ updateAgent(s.agentId, { status: 'looping', action: s.reason || 'breaker armed', carrying: undefined });
+ }
+ // 'healthy'/'steering' clear the pin; the next hook event refreshes status.
+ });
+ }, []);
+
++ // 2c) Context gauge (#11/#12): poll each live agent's current context size
++ // (tokens) from its session transcript and map it onto the agent card's
++ // 8-segment bar — a fuel gauge for how close the session is to its limit.
+ useEffect(() => {
+ if (!config?.onboardingComplete) return;
+ const poll = async () => {
+ const { agents, updateAgent } = useStore.getState();
+ for (const a of agents) {
+ if (!a.ptyId) continue;
+ try {
+ const ctx = await window.cth.agentContext(a.id);
+ if (ctx === null) continue;
+ // 1M-context models advertise it in the model id (e.g. "[1m]").
+ const limit = /1m/i.test(a.model ?? '') ? 1_000_000 : 200_000;
+ const progress = Math.max(0, Math.min(8, Math.round((ctx / limit) * 8)));
+ updateAgent(a.id, { contextTokens: ctx, contextLimit: limit, progress });
+ } catch { /* ignore — try again next tick */ }
+ }
+ };
+ const t = setTimeout(poll, 3000); // first fill shortly after boot
+ const iv = setInterval(poll, 15000);
+ return () => { clearTimeout(t); clearInterval(iv); };
+ }, [config?.onboardingComplete]);
+
// 3) Wake idle agents holding unread inbox messages. The assistant is
// send-only (it never receives inbox mail), so it's excluded.
useEffect(() => {