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
feat(hive): agent lifecycle/archival — closing a tab archives, not deletes
Chaitanya Giri7ccc1c4e7e2d
diff --git a/src/main/hive.ts b/src/main/hive.tsindex 39c4cfac..51b7f1cd 100644--- a/src/main/hive.ts+++ b/src/main/hive.ts@@ -54,6 +54,10 @@ export interface AgentMeta {export interface RegistryAgent extends AgentMeta {status: 'idle' | 'working' | 'blocked' | 'gone';lastSeen: number;+ /** True once the agent's terminal/PTY tab is closed. The record is retained+ * (not deleted) so its history/memory survive; only agents with a live PTY+ * are 'active'. Broadcast fan-out + roster reads skip archived agents. */+ archived?: boolean;}export interface Registry {@@ -186,6 +190,8 @@ export class HiveManager {capabilities: meta.capabilities ?? [],role: meta.role ?? (meta.isGod ? 'orchestrator' : 'agent'),status: 'idle',+ // A (re)spawn always means a live terminal — clear any prior archived flag.+ archived: false,lastSeen: Date.now()};if (meta.isGod) reg.godId = meta.id;@@ -215,6 +221,27 @@ export class HiveManager {return { args, env };}+ /**+ * Flip an agent's archived flag and persist the registry. Closing a terminal+ * tab archives the agent (retained + flagged, NOT deleted); a (re)spawn clears+ * it. No-op if the agent isn't registered or the flag is already set the way+ * asked. Best-effort — never throws, so a dying PTY/kill handler can't crash.+ */+ setArchived(id: string, archived: boolean): void {+ const root = this.root();+ if (!root) return;+ try {+ const reg = this.registry();+ const agent = reg.agents[id];+ if (!agent || agent.archived === archived) return;+ agent.archived = archived;+ agent.lastSeen = Date.now();+ this.writeJson(join(root, 'registry.json'), reg);+ this.appendLog({ kind: 'archive', agentId: id, archived });+ this.commit(`hive: ${archived ? 'archive' : 'unarchive'} ${id}`);+ } catch { /* best-effort — never crash a lifecycle handler */ }+ }+/** Claude Code settings that route every relevant hook through the shim. */private hookSettings(shim: string): unknown {const cmd = `node "${shim}"`;@@ -353,8 +380,10 @@ export class HiveManager {}const reg = this.registry();const targets = msg.to === 'broadcast'- // The prep assistant is send-only — never fan broadcasts into its inbox.- ? Object.keys(reg.agents).filter((a) => a !== msg.from && !reg.agents[a]?.isAssistant)+ // The roster for fan-out is the ACTIVE registry: skip the send-only prep+ // assistant and any archived agent (closed tab) so mail never piles into a+ // dead inbox no one will read.+ ? Object.keys(reg.agents).filter((a) => a !== msg.from && !reg.agents[a]?.isAssistant && !reg.agents[a]?.archived): [msg.to === 'god' ? (reg.godId ?? 'god') : msg.to];for (const t of targets) this.deliver(msg, t);this.appendLog({ kind: 'message', from: msg.from, to: msg.to, act: msg.act, subject: msg.subject, id: msg.id });diff --git a/src/main/index.ts b/src/main/index.tsindex b8771c77..24095c21 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -18,6 +18,9 @@ import { enrichMessage } from './assistant';const isDev = !!process.env.ELECTRON_RENDERER_URL;const ptyManager = new PtyManager();+/** Live PTY id → its hive agent id, recorded at spawn. The pty:kill handler only+ * gets the PTY id, so this lets a closed tab archive the right registry agent. */+const ptyToAgent = new Map<string, string>();const hive = new HiveManager(() => readConfig().harnessHome,(channel, payload) => { try { liveWebContents()?.send(channel, payload); } catch { /* window tore down */ } }@@ -112,6 +115,9 @@ ipcMain.handle('pty:spawn', (_evt, opts: SpawnOptions & { hive?: AgentMeta }) =>console.error('[hive] ensureAgent failed:', e);}}+ // Remember which agent owns this PTY so closing the tab can archive it. A+ // live terminal means active — ensureAgent above already cleared `archived`.+ if (opts.hive?.id) ptyToAgent.set(opts.id, opts.hive.id);return ptyManager.spawn(opts);});ipcMain.handle('pty:write', (_evt, id: string, data: string) => {@@ -124,6 +130,13 @@ ipcMain.handle('pty:resize', (_evt, id: string, cols: number, rows: number) => {});ipcMain.handle('pty:kill', (_evt, id: string) => {if (typeof id !== 'string') return { ok: false, error: 'invalid id' };+ // Closing a terminal tab archives the agent: its registry record is retained+ // and flagged (not deleted), and only live-PTY agents stay 'active'.+ const agentId = ptyToAgent.get(id);+ if (agentId && hive.enabled()) {+ try { hive.setArchived(agentId, true); } catch (e) { console.error('[hive] setArchived failed:', e); }+ }+ ptyToAgent.delete(id);return ptyManager.kill(id);});ipcMain.handle('pty:list', () => ptyManager.list());@@ -231,6 +244,12 @@ ipcMain.handle('hive:send', (_evt, partial: Partial<HiveMessage>, from: unknown)const msg = hive.send(partial ?? {}, typeof from === 'string' ? from : 'system');return { ok: true, message: msg };});+ipcMain.handle('hive:setArchived', (_evt, id: unknown, archived: unknown) => {+ if (typeof id !== 'string') return { ok: false, error: 'invalid id' };+ if (!hive.enabled()) return { ok: false, error: 'hive disabled (no harnessHome)' };+ hive.setArchived(id, archived === true);+ return { ok: true };+});// ─── IPC: enrichment assistant (headless Sonnet 1M prompt prep) ─────────────ipcMain.handle('assistant:enrich', async (_evt, payload: unknown) => {diff --git a/src/preload/index.ts b/src/preload/index.tsindex 42e5960a..3f7cd1aa 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -27,7 +27,9 @@ export interface HiveMessage {export interface HiveRegistry {godId: string | null;- agents: Record<string, HiveAgentMeta & { status: string; lastSeen: number }>;+ /** `archived` agents have had their terminal closed — retained + flagged, not+ * deleted; only live-PTY agents are 'active'. */+ agents: Record<string, HiveAgentMeta & { status: string; lastSeen: number; archived?: boolean }>;}/** A message the router just delivered, with its resolved recipient ids. Drives@@ -219,7 +221,13 @@ const api = {// ─── Reset ─────────────────────────────────────────────────────────────────/** Wipe all hive data + the memory palace, reset config, and relaunch the app* into onboarding. The process exits, so this promise never resolves. */- resetAll: (): Promise<void> => ipcRenderer.invoke('app:resetAll')+ resetAll: (): Promise<void> => ipcRenderer.invoke('app:resetAll'),++ // ─── Agent lifecycle (archival) ─────────────────────────────────────────────+ /** Archive/unarchive a hive agent in the registry. Closing a terminal tab+ * archives it automatically via pty:kill; this is the explicit primitive. */+ hiveSetArchived: (id: string, archived: boolean): Promise<{ ok: boolean; error?: string }> =>+ ipcRenderer.invoke('hive:setArchived', id, archived)};contextBridge.exposeInMainWorld('cth', api);diff --git a/src/renderer/src/components/AgentDetailPanel.tsx b/src/renderer/src/components/AgentDetailPanel.tsxindex 0c95fef0..68928877 100644--- a/src/renderer/src/components/AgentDetailPanel.tsx+++ b/src/renderer/src/components/AgentDetailPanel.tsx@@ -21,7 +21,7 @@ export interface AgentDetailPanelProps {export function AgentDetailPanel({ agent }: AgentDetailPanelProps) {const [openTerminalState, setOpenTerminalState] = useState<'idle' | 'opening' | 'ok' | 'error'>('idle');const [openTerminalError, setOpenTerminalError] = useState<string | undefined>();- const removeAgent = useStore(s => s.removeAgent);+ const archiveAgent = useStore(s => s.archiveAgent);const updateAgent = useStore(s => s.updateAgent);const setFullscreen = useStore(s => s.setFullscreen);const fullscreenAgentId = useStore(s => s.fullscreenAgentId);@@ -62,10 +62,10 @@ export function AgentDetailPanel({ agent }: AgentDetailPanelProps) {const onKill = async () => {if (!agent.ptyId) return;- if (!confirm(`Kill ${agent.name}? The PTY process will terminate.`)) return;+ if (!confirm(`Close ${agent.name}? The PTY process will terminate and the agent is archived (kept in history, off the floor).`)) return;await window.cth.killPty(agent.ptyId);disposeTerminal(agent.ptyId);- removeAgent(agent.id);+ archiveAgent(agent.id);};return (diff --git a/src/renderer/src/components/CommandCenterPanel.tsx b/src/renderer/src/components/CommandCenterPanel.tsxindex a71ff27a..608809f4 100644--- a/src/renderer/src/components/CommandCenterPanel.tsx+++ b/src/renderer/src/components/CommandCenterPanel.tsx@@ -247,6 +247,8 @@ function FloorTab() {))}</Section>+ <ArchivedSection />+<Section title="ASSISTANT"><div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><span style={{ fontSize: 13, color: 'var(--cth-ink-700)' }}>Route Michael's queue through Dwight</span>@@ -280,6 +282,52 @@ function FloorTab() {);}+// ─── Archived agents — retained + flagged, kept off the floor ────────────────++function ArchivedSection() {+ const archivedAgents = useStore((s) => s.archivedAgents);+ const removeArchivedAgent = useStore((s) => s.removeArchivedAgent);+ const [open, setOpen] = useState(false);+ if (archivedAgents.length === 0) return null;+ return (+ <Section title={`ARCHIVED (${archivedAgents.length})`}>+ <button+ onClick={() => setOpen((v) => !v)}+ style={{+ display: 'inline-flex', alignItems: 'center', gap: 4,+ padding: '2px 8px 1px', border: 'none', cursor: 'pointer',+ background: 'var(--cth-cream-200)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-700)',+ fontFamily: 'var(--cth-font-ui)', fontSize: 12, color: 'var(--cth-ink-900)',+ marginBottom: open ? 6 : 0+ }}+ >{open ? '▾' : '▸'} {open ? 'hide' : 'show'} closed agents</button>+ {open && archivedAgents.map((a) => (+ <div key={a.id} style={{+ display: 'flex', alignItems: 'center', gap: 8,+ padding: 6, marginBottom: 6, opacity: 0.7,+ background: 'var(--cth-paper-100)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-300)'+ }}>+ <div style={{+ width: 24, height: 24, background: `var(--cth-${a.accent}-light)`,+ boxShadow: 'inset 0 0 0 1px var(--cth-ink-900)',+ display: 'flex', alignItems: 'flex-end', justifyContent: 'center', overflow: 'hidden', flexShrink: 0+ }}>+ <SpritePortrait character={a.character} scale={1} />+ </div>+ <div style={{ flex: 1, minWidth: 0 }}>+ <div style={{ fontFamily: 'var(--cth-font-ui)', fontSize: 13, color: 'var(--cth-ink-700)' }}>{a.name}</div>+ <div style={{ fontSize: 11, color: 'var(--cth-ink-500)', wordBreak: 'break-all' }}>{a.cwd}</div>+ </div>+ <button+ onClick={() => removeArchivedAgent(a.id)}+ style={{ border: 'none', background: 'transparent', cursor: 'pointer', color: 'var(--cth-ink-500)', flexShrink: 0 }}+ ><Icon name="x" /></button>+ </div>+ ))}+ </Section>+ );+}+// ─── Memory tab ──────────────────────────────────────────────────────────────function MemoryTab({ godId }: { godId: string }) {diff --git a/src/renderer/src/components/FullscreenTerminal.tsx b/src/renderer/src/components/FullscreenTerminal.tsxindex a49eb458..e22da648 100644--- a/src/renderer/src/components/FullscreenTerminal.tsx+++ b/src/renderer/src/components/FullscreenTerminal.tsx@@ -16,7 +16,7 @@ export function FullscreenTerminal() {const setFullscreen = useStore(s => s.setFullscreen);const select = useStore(s => s.select);const setAddAgentOpen = useStore(s => s.setAddAgentOpen);- const removeAgent = useStore(s => s.removeAgent);+ const archiveAgent = useStore(s => s.archiveAgent);const updateAgent = useStore(s => s.updateAgent);const agent = agents.find(a => a.id === fullscreenAgentId);@@ -42,10 +42,10 @@ export function FullscreenTerminal() {const onKill = async () => {if (!agent.ptyId) return;- if (!confirm(`Kill ${agent.name}? The PTY process will terminate.`)) return;+ if (!confirm(`Close ${agent.name}? The PTY process will terminate and the agent is archived (kept in history, off the floor).`)) return;await window.cth.killPty(agent.ptyId);disposeTerminal(agent.ptyId);- removeAgent(agent.id);+ archiveAgent(agent.id);setFullscreen(null);};diff --git a/src/renderer/src/store/store.ts b/src/renderer/src/store/store.tsindex 3179674d..05b01020 100644--- a/src/renderer/src/store/store.ts+++ b/src/renderer/src/store/store.ts@@ -61,6 +61,10 @@ export interface Agent {/** Michael's prep assistant ("Dwight") — enriches prompts and forwards them to* Michael via the hive. Send-only: never receives inbox/broadcast mail. */isAssistant?: boolean;+ /** True once this agent's terminal was closed. Archived agents are retained+ * (in the store's `archivedAgents` list + the hive registry) but flagged and+ * kept off the floor; only live-PTY agents are 'active'. */+ archived?: boolean;}export interface FeedEntry {@@ -90,6 +94,10 @@ export type GodStatus = 'booting' | 'ready' | 'failed';interface State {agents: Agent[];+ /** Agents whose terminal was closed — retained + flagged, kept off the active+ * roster/floor. The hive registry retains them durably; this mirrors them for+ * the renderer's "Archived" view. */+ archivedAgents: Agent[];selectedId: string | null;feeds: Record<string, string[]>;addAgentOpen: boolean;@@ -117,6 +125,12 @@ interface State {pushFeed: (id: string, line: string) => void;addAgent: (agent: Agent) => void;removeAgent: (id: string) => void;+ /** Archive an agent (its terminal was closed): move it from the active roster+ * into `archivedAgents` with its PTY cleared. Retained + flagged, NOT deleted. */+ archiveAgent: (id: string) => void;+ /** Permanently forget an archived agent (drops the renderer entry only; the+ * hive registry keeps its record). */+ removeArchivedAgent: (id: string) => void;/** Park a message for an agent. Returns nothing; the flush loop delivers it. */enqueueMessage: (agentId: string, text: string) => void;/** Drop a single queued message (user removed it, or it was just delivered). */@@ -137,6 +151,7 @@ interface State {const LS_SIDEBAR_WIDTH = 'cth.sidebarWidth';const LS_SIDEBAR_TAB = 'cth.sidebarTab';const LS_AGENTS = 'cth.agents';+const LS_ARCHIVED = 'cth.archivedAgents';const LS_SELECTED = 'cth.selectedId';const LS_QUEUES = 'cth.messageQueues';const LS_ENRICH = 'cth.enrichEnabled';@@ -175,6 +190,36 @@ function loadPersistedAgents(): Agent[] {}}+function persistArchived(archived: Agent[]): void {+ try {+ const slim: PersistedAgent[] = archived.map(({ recentAssistantText, recentTextTs, blockReason, ...rest }) => {+ void recentAssistantText; void recentTextTs; void blockReason;+ return rest;+ });+ window.localStorage.setItem(LS_ARCHIVED, JSON.stringify(slim));+ } catch { /* noop */ }+}++function loadPersistedArchived(): Agent[] {+ try {+ const raw = window.localStorage.getItem(LS_ARCHIVED);+ if (!raw) return [];+ const parsed = JSON.parse(raw) as PersistedAgent[];+ if (!Array.isArray(parsed)) return [];+ // Archived agents have no live process — force the flag + clear run-state.+ return parsed.map((a) => ({+ ...a,+ archived: true,+ status: 'idle',+ ptyId: undefined,+ carrying: undefined,+ currentStation: undefined+ }));+ } catch {+ return [];+ }+}+function persistQueues(queues: Record<string, QueuedMessage[]>): void {try {// Only keep non-empty queues so the key stays small.@@ -228,6 +273,7 @@ const initialSidebarTab: SidebarTab = (() => {})();const initialAgents = loadPersistedAgents();+const initialArchivedAgents = loadPersistedArchived();const initialSelectedId = loadPersistedSelectedId(initialAgents);const initialQueues = loadPersistedQueues();const initialEnrichEnabled: boolean = (() => {@@ -244,6 +290,7 @@ function newQueuedId(): string {export const useStore = create<State>((set) => ({agents: initialAgents,+ archivedAgents: initialArchivedAgents,selectedId: initialSelectedId,feeds: {},addAgentOpen: false,@@ -270,9 +317,13 @@ export const useStore = create<State>((set) => ({addAgent: (agent) =>set((s) => {const agents = [...s.agents, agent];+ // Re-spawning an archived agent un-archives it: an id is active xor archived.+ const archivedAgents = s.archivedAgents.filter((a) => a.id !== agent.id);persistAgents(agents, agent.id);+ persistArchived(archivedAgents);return {agents,+ archivedAgents,selectedId: agent.id,feeds: { ...s.feeds, [agent.id]: s.feeds[agent.id] ?? [] }};@@ -287,6 +338,37 @@ export const useStore = create<State>((set) => ({if (_queueGone) persistQueues(messageQueues);return { agents, feeds, selectedId, messageQueues };}),+ archiveAgent: (id) =>+ set((s) => {+ const target = s.agents.find((a) => a.id === id);+ if (!target) return s;+ const agents = s.agents.filter((a) => a.id !== id);+ // Retain a flagged copy; the PTY is gone, so clear all live run-state.+ const archivedEntry: Agent = {+ ...target,+ archived: true,+ ptyId: undefined,+ status: 'idle',+ action: 'archived',+ carrying: undefined,+ currentStation: undefined+ };+ const archivedAgents = [...s.archivedAgents.filter((a) => a.id !== id), archivedEntry];+ const { [id]: _feedGone, ...feeds } = s.feeds;+ const { [id]: _queueGone, ...messageQueues } = s.messageQueues;+ const selectedId = s.selectedId === id ? (agents[0]?.id ?? null) : s.selectedId;+ persistAgents(agents, selectedId);+ persistArchived(archivedAgents);+ if (_queueGone) persistQueues(messageQueues);+ return { agents, archivedAgents, feeds, selectedId, messageQueues };+ }),+ removeArchivedAgent: (id) =>+ set((s) => {+ if (!s.archivedAgents.some((a) => a.id === id)) return s;+ const archivedAgents = s.archivedAgents.filter((a) => a.id !== id);+ persistArchived(archivedAgents);+ return { archivedAgents };+ }),enqueueMessage: (agentId, text) =>set((s) => {const trimmed = text.trim();