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(voice): conversational read-layer — fix get_memory dead-ends, add agent/board tools, expand persona
Chaitanya Giribbe94bde617f
diff --git a/src/main/hive.ts b/src/main/hive.tsindex 51190fbd..81da4938 100644--- a/src/main/hive.ts+++ b/src/main/hive.ts@@ -1113,6 +1113,21 @@ export class HiveManager {const p = join(this.agentDir(id), 'memory.md');return existsSync(p) ? readFileSync(p, 'utf8') : '';}+ /** Whether an agent has recorded NON-TRIVIAL memory — i.e. has appended real+ * notes beyond the boilerplate header ensureAgent seeds. Lets the voice+ * read-layer answer "what has the team remembered" and enumerate who has+ * anything worth reading (every registered agent technically has a memory.md,+ * but most of the floor's history lives in a handful of them). Cheap: reads a+ * small markdown file; never throws. Works for ANY id, active OR archived. */+ hasMemory(id: string): boolean {+ const p = join(this.agentDir(id), 'memory.md');+ if (!existsSync(p)) return false;+ try {+ // A fresh seed is ~90 chars (one header line + the prompt). Anything+ // meaningfully longer means the agent appended durable facts.+ return readFileSync(p, 'utf8').trim().length > 200;+ } catch { return false; }+ }inbox(id: string): HiveMessage[] {return this.listMessages(join(this.agentDir(id), 'inbox'));}diff --git a/src/main/hooks.ts b/src/main/hooks.tsindex 70b1aef0..e134f4af 100644--- a/src/main/hooks.ts+++ b/src/main/hooks.ts@@ -52,6 +52,13 @@ export class HookServer {* Lets the harness read per-agent telemetry (e.g. current context size)* even when several agents share one cwd. */private transcriptPaths = new Map<string, string>();+ /** agentId → the latest context-window accounting from the statusLine shim+ * (current tokens + the REAL window size — 200k vs 1M, which nothing else+ * exposes). The renderer already gets this pushed live on `hive:contextUpdate`;+ * we also retain the last value here so a main-side read (the voice read-layer's+ * get_agent_detail / list_agents) can report "how full is each agent's context"+ * without depending on a renderer round-trip. */+ private contextById = new Map<string, { tokens: number; limit: number; ts: number }>();constructor(private hive: HiveManager,@@ -100,6 +107,12 @@ export class HookServer {return this.transcriptPaths.get(agentId);}+ /** The latest context-window accounting for an agent (current tokens + the real+ * window size), or undefined if no statusLine tick has fired for it yet. */+ contextFor(agentId: string): { tokens: number; limit: number; ts: number } | undefined {+ return this.contextById.get(agentId);+ }+private handle(p: HookPayload): unknown {const agentId = p.agent_id ?? undefined;const event = p.hook_event_name ?? 'Unknown';@@ -121,6 +134,13 @@ export class HookServer {const cw = p.context_window;if (agentId && cw && typeof cw.total_input_tokens === 'number'&& typeof cw.context_window_size === 'number' && cw.context_window_size > 0) {+ // Retain for main-side reads (voice get_agent_detail / list_agents) …+ this.contextById.set(agentId, {+ tokens: cw.total_input_tokens,+ limit: cw.context_window_size,+ ts: Date.now()+ });+ // … and forward live to the renderer's agent-card context gauge.this.getWebContents()?.send('hive:contextUpdate', {agentId,tokens: cw.total_input_tokens,diff --git a/src/main/index.ts b/src/main/index.tsindex 424b269d..e774f0c5 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -2568,6 +2568,54 @@ ipcMain.handle('hive:agentContext', (_evt, agentId: unknown) => {return readContextTokens(tp) ?? 0;});+// A consolidated, NON-SENSITIVE per-agent directory for the voice read-layer+// (Realtime Michael's get_agent_detail / list_agents). One read that joins+// everything the office-floor sidebar + telemetry know per agent: the registry+// record (name/role/provider/cwd/status/archived/isGod/isAssistant/sessionId/+// cwdValid), live token + breaker + last-tool telemetry, and the current context+// window fill. Includes ARCHIVED agents (unlike the heartbeat's fleet.json, which+// is live-only) so Michael can speak to inactive agents — their cwd and memory+// stay reachable. PII-free: no secrets, env, or API keys ever leave main; cost is+// carried as tokens (+ a usd field the voice layer deliberately never speaks).+ipcMain.handle('hive:agentDirectory', () => {+ if (!hive.enabled()) return { godId: null, agents: [] };+ const reg = hive.registry();+ const snap = telemetry.snapshot();+ const usageById = new Map(snap.usage.map((u) => [u.agentId, u]));+ const now = Date.now();+ const agents = Object.entries(reg.agents).map(([id, a]) => {+ const u = usageById.get(id);+ const spans = snap.spans[id] ?? [];+ const tokens = u ? u.input + u.output + u.cacheRead + u.cacheCreation : 0;+ const ctx = hookServer.contextFor(id);+ return {+ id,+ name: a.name,+ role: a.role ?? (a.isGod ? 'orchestrator' : 'agent'),+ provider: a.provider ?? 'claude',+ model: u?.model ?? null,+ status: a.status ?? 'idle',+ cwd: a.cwd ?? null,+ cwdValid: a.cwdValid ?? null,+ archived: !!a.archived,+ isGod: !!a.isGod,+ isAssistant: !!a.isAssistant,+ sessionId: a.sessionId ?? null,+ hasMemory: hive.hasMemory(id),+ inboxBacklog: hive.inboxBacklog(id),+ breaker: breaker.levelFor(id),+ tokens,+ usd: u ? Number(u.usd.toFixed(4)) : 0,+ lastTool: spans.length ? spans[spans.length - 1].tool : null,+ lastActiveSecAgo: u ? Math.round((now - u.ts) / 1000) : null,+ contextTokens: ctx?.tokens ?? null,+ contextLimit: ctx?.limit ?? null,+ contextPct: ctx && ctx.limit > 0 ? Math.round((ctx.tokens / ctx.limit) * 100) : null+ };+ });+ return { godId: reg.godId, agents };+});+// ─── 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.diff --git a/src/preload/index.ts b/src/preload/index.tsindex 5e88c975..8dc6d390 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -48,6 +48,43 @@ export interface HiveRegistry {agents: Record<string, HiveAgentMeta & { status: string; lastSeen: number; archived?: boolean }>;}+/** One row of the consolidated voice read-layer directory (`hive:agentDirectory`):+ * everything the office-floor sidebar + telemetry know for an agent, joined into+ * one PII-free record. Includes archived agents. */+export interface AgentDirectoryEntry {+ id: string;+ name: string;+ role: string;+ provider: string;+ /** Live model id (normalized), if any usage has been recorded — else null. */+ model: string | null;+ status: string;+ cwd: string | null;+ /** Whether `cwd` is an absolute, existing directory (spawn-usable). */+ cwdValid: boolean | null;+ archived: boolean;+ isGod: boolean;+ isAssistant: boolean;+ sessionId: string | null;+ /** Whether the agent has recorded non-trivial memory beyond the seed header. */+ hasMemory: boolean;+ inboxBacklog: number;+ breaker: string;+ tokens: number;+ /** Aggregate spend; carried for completeness — the voice layer speaks tokens. */+ usd: number;+ lastTool: string | null;+ lastActiveSecAgo: number | null;+ contextTokens: number | null;+ contextLimit: number | null;+ contextPct: number | null;+}++export interface AgentDirectory {+ godId: string | null;+ agents: AgentDirectoryEntry[];+}+/** One question→answer exchange with the human, recorded ON the task card. */export interface HumanQA {q: string;@@ -534,6 +571,9 @@ const api = {hiveLog: (n?: number): Promise<unknown[]> => ipcRenderer.invoke('hive:log', n ?? 200),hiveMemory: (id: string): Promise<string> => ipcRenderer.invoke('hive:memory', id),hiveInbox: (id: string): Promise<HiveMessage[]> => ipcRenderer.invoke('hive:inbox', id),+ /** Consolidated per-agent directory (registry + telemetry + context), incl.+ * archived agents. Backs Realtime Michael's get_agent_detail / list_agents. */+ hiveAgentDirectory: (): Promise<AgentDirectory> => ipcRenderer.invoke('hive:agentDirectory'),// ─── Ephemeral workers (P4 — Slack-triggered isolated workers) ───────────/** Live ephemeral workers + worktrees preserved awaiting integration/GC. */diff --git a/src/renderer/src/realtime/session.ts b/src/renderer/src/realtime/session.tsindex 9b0bb8f1..4974a31a 100644--- a/src/renderer/src/realtime/session.ts+++ b/src/renderer/src/realtime/session.ts@@ -65,7 +65,19 @@ const MICHAEL_PERSONA =VOICE & STYLE. You speak out loud over a live connection. Be concise and natural — like a sharp, calm chief of staff giving a verbal briefing. Lead with the answer in one sentence, then add detail only if it helps. Never read markdown, file paths, or code aloud unless asked. Use plain spoken numbers and names. Brevity is fine; the human can always ask for more.-WHAT YOU KNOW. You have live, read-only awareness of the hive through your tools: the fleet roster (each agent's id and name, live-vs-idle, token usage, circuit-breaker state), the task board (kanban cards in todo / doing / blocked / done, each with an owner), schedules, configuration, memory, and recent activity. When asked what's going on, CALL the relevant tool and answer with specific facts — real names, real statuses, real numbers — never a vague guess. If a tool returns nothing or you're unsure, say so plainly.+WHAT YOU CAN LOOK UP. You have live, read-only awareness of the WHOLE hive through your tools — use them liberally, and ALWAYS call the relevant one before answering a factual question. Your read tools:+- get_fleet_status — the live roster: who is active, who the god orchestrator is, and each worker's name, role, and engine.+- list_agents — the FULL roster INCLUDING archived (inactive) agents, with each agent's engine, working directory, context fill, and breaker state. Use it to enumerate everyone, find who is archived, or see who is near their context limit.+- get_agent_detail — everything about ONE agent (by name or id): its engine and model, its WORKING DIRECTORY, whether it's active or archived, live status, how full its context window is, tokens used, breaker state, and whether it has memory.+- get_memory — read the team's memory. You can ALWAYS answer with this: search across everyone, read ONE agent's notes (active OR archived), or search within a single agent. It never dead-ends.+- get_tasks — the kanban board: counts plus the in-progress and blocked cards with their owners.+- get_board — the orchestrator's plan narrative, in prose.+- get_schedules — the recurring scheduled missions.+- get_config — non-sensitive settings (autonomy, default model, caps, breaker, which features are on). Never secrets.+- get_cost — token usage across the hive.+- get_activity — the recent hive activity log.++NEVER say "I can't access that", "the tool doesn't allow that", or "I don't have that" BEFORE you have actually CALLED a tool. You CAN read any agent's memory (active OR archived), any agent's working directory, full per-agent status, token usage, context-window fill, schedules, configuration, and the board. When a question is about the hive, call the matching tool FIRST and answer with specific facts — real names, real statuses, real numbers — never a vague guess. Only if a tool genuinely returns nothing do you say so, plainly and briefly.HIVE VOCABULARY. Agents have an id like "creed-mqp3l5wn" and a friendly name like "Creed"; refer to them by name. "god" is the orchestrator whose voice you are. A card's status is todo, doing, blocked, or done. The circuit breaker is healthy, or steering an agent that's looping or idle. Blocked usually means waiting on the human.diff --git a/src/renderer/src/realtime/tools.ts b/src/renderer/src/realtime/tools.tsindex a9a1727d..f4881b6f 100644--- a/src/renderer/src/realtime/tools.ts+++ b/src/renderer/src/realtime/tools.ts@@ -67,6 +67,25 @@ function clip(s: string, n: number): string {return s.length > n ? s.slice(0, n).trimEnd() + ' (truncated)' : s;}+/** The trailing folder name of a path — speech-friendly (the persona avoids+ * reading full file paths aloud unless asked). e.g. /a/b/cth-voice-tools → cth-voice-tools. */+function shortDir(p: string): string {+ const parts = (p || '').replace(/\/+$/, '').split('/').filter(Boolean);+ return parts.length ? parts[parts.length - 1] : p;+}++/** Strip markdown to plain speakable prose (headers, emphasis, bullets, links,+ * code fences) and collapse whitespace. */+function despan(md: string): string {+ return (md || '')+ .replace(/```[\s\S]*?```/g, ' ')+ .replace(/\[(.*?)\]\([^)]*\)/g, '$1')+ .replace(/^\s*[-+*]\s+/gm, '')+ .replace(/[#>*_`~|]/g, '')+ .replace(/\s+/g, ' ')+ .trim();+}+const obj = (x: unknown): Record<string, unknown> =>x && typeof x === 'object' ? (x as Record<string, unknown>) : {};@@ -285,12 +304,12 @@ export function realtimeReadTools(): ReturnType<typeof tool>[] {tool({name: 'get_memory',description:- 'Search the shared team memory, or read one agent saved notes. Pass a query to semantically search everything the hive has learned; pass an agentId to read that agent memory file; pass neither for memory system status. Call this when the user asks what the team learned, remembered, or decided.',+ "Read the team's memory. You can ALWAYS answer with this — it never dead-ends. Pass a query to search everything the hive has learned; pass an agentId to read ONE agent's notes (works for any agent, active OR archived); pass BOTH to search within that one agent's notes; pass neither for memory status. Semantic search is used when available, otherwise a direct text search across every agent's memory file. Call this whenever the user asks what the team learned, remembered, decided, or noted.",parameters: {type: 'object',properties: {- query: { type: 'string', description: 'Optional. A natural-language search over the shared memory palace.' },- agentId: { type: 'string', description: 'Optional. An agent id to read that agent saved memory notes.' }+ query: { type: 'string', description: "Optional. What to search for across the team's memory." },+ agentId: { type: 'string', description: "Optional. An agent id to read or scope the search to — any agent, active or archived." }},required: [],additionalProperties: false@@ -300,20 +319,64 @@ export function realtimeReadTools(): ReturnType<typeof tool>[] {const a = obj(input);const query = str(a.query).trim();const agentId = str(a.agentId).trim();++ // Direct text fallback across every agent's memory.md (INCLUDING archived+ // agents), the board, and tasks — works with or without the semantic+ // memory CLI, so a query can never dead-end. Optionally narrow to one agent.+ const textFallback = async (q: string, onlyAgent?: string): Promise<string> => {+ const res = await window.cth.textSearch(q);+ if (!res.ok || !res.results.length) return '';+ let hits = res.results;+ if (onlyAgent) hits = hits.filter((r) => r.source.startsWith(`${onlyAgent}/`) || r.source === onlyAgent);+ if (!hits.length) return '';+ const bySource = new Map<string, string[]>();+ for (const r of hits.slice(0, 14)) {+ const who = r.source.replace(/\/memory\.md$/, '');+ if (!bySource.has(who)) bySource.set(who, []);+ bySource.get(who)!.push(r.excerpt);+ }+ const lines = [...bySource.entries()].slice(0, 6).map(([who, ex]) => `${who} noted ${ex.slice(0, 2).join('; ')}`);+ return `From the team's notes — ${lines.join('. ')}.`;+ };++ // query + agentId → search WITHIN one agent (semantic wing first, then text).+ if (query && agentId) {+ const res = await window.cth.searchMemory(query, agentId);+ if (res.ok && res.output.trim()) return clip(res.output.trim(), 1600);+ const tf = await textFallback(query, agentId);+ if (tf) return clip(tf, 1600);+ const mem = await window.cth.hiveMemory(agentId);+ const ql = query.toLowerCase();+ const matched = mem.split('\n').map((l) => l.trim()).filter((l) => l.toLowerCase().includes(ql)).slice(0, 8);+ if (matched.length) return clip(`From ${agentId}'s memory — ${matched.join(' ')}`, 1600);+ return mem.trim()+ ? `I read ${agentId}'s memory but found nothing about "${query}".`+ : `${agentId} has not recorded any memory yet.`;+ }++ // query alone → semantic across the whole palace, then text fallback across all agents.if (query) {const res = await window.cth.searchMemory(query);- if (!res.ok) return `Memory search is unavailable right now${res.error ? ` (${res.error})` : ''}.`;- return res.output.trim() ? clip(res.output.trim(), 1600) : `I found nothing in memory for "${query}".`;+ if (res.ok && res.output.trim()) return clip(res.output.trim(), 1600);+ const tf = await textFallback(query);+ if (tf) return clip(tf, 1600);+ return `I searched the team's memory but found nothing about "${query}".`;}++ // agentId alone → read that agent's notes directly (any agent, active OR archived).if (agentId) {const mem = await window.cth.hiveMemory(agentId);return mem.trim() ? clip(mem.trim(), 1600) : `${agentId} has not recorded any memory yet.`;}++ // neither → status, but make clear search always works.const status = await window.cth.memoryStatus();- if (!status.available) return 'The semantic memory system is not available in this build.';- if (!status.active)- return `Memory is ${status.enabled ? 'enabled but not active' : 'disabled'}. Ask me to search a topic and I will try.`;- return 'Memory is active. Ask me to search for a topic, or name an agent to read their notes.';+ const sem = status.active+ ? 'Semantic memory is active'+ : status.available+ ? 'Semantic memory is enabled but idle'+ : 'Semantic memory is offline';+ return `${sem} — but I can always text-search every agent's notes, active or archived. Ask me to search a topic, or name an agent to read their memory.`;}, 'memory')}),@@ -349,6 +412,113 @@ export function realtimeReadTools(): ReturnType<typeof tool>[] {});return `Most recent activity: ${lines.join('; ')}.`;}, 'activity log')+ }),++ // ── get_agent_detail ──────────────────────────────────────────────────+ tool({+ name: 'get_agent_detail',+ description:+ 'Everything known about ONE agent: name, role, the engine and model it runs, its working directory, whether it is active or archived, its live status, how full its context window is, how many tokens it has used, its circuit-breaker state, what it last did, and whether it has recorded memory. Call this when the user asks about a specific agent — where it is working, which directory it is in, how it is doing, or for its full status. Accepts an id or a name.',+ parameters: {+ type: 'object',+ properties: {+ agentId: { type: 'string', description: 'The agent id or friendly name to look up (e.g. "kevin-mqpbq43v" or "Kevin").' }+ },+ required: ['agentId'],+ additionalProperties: false+ },+ execute: (input) =>+ spoken(async () => {+ const a = obj(input);+ const want = str(a.agentId).trim().toLowerCase();+ if (!want) return 'Tell me which agent you mean.';+ const dir = await window.cth.hiveAgentDirectory();+ const list = Array.isArray(dir.agents) ? dir.agents : [];+ const e =+ list.find((x) => x.id.toLowerCase() === want) ??+ list.find((x) => x.name.toLowerCase() === want) ??+ list.find((x) => x.id.toLowerCase().startsWith(want) || x.name.toLowerCase().startsWith(want));+ if (!e) return `I don't see an agent matching "${str(a.agentId)}".`;+ const parts: string[] = [];+ const role = e.role ? `, the ${e.role},` : '';+ const where = e.archived+ ? 'archived — its terminal is closed, but its working directory and memory are still here'+ : `active and ${e.status}`;+ parts.push(`${e.name}${role} runs on ${e.provider}${e.model ? ` with model ${e.model}` : ''}, ${where}.`);+ if (e.cwd)+ parts.push(+ `Working directory: ${e.cwd}${e.cwdValid === false ? ', which is not a valid directory — spawning there would fail' : ''}.`+ );+ if (typeof e.contextPct === 'number') parts.push(`Its context window is ${e.contextPct} percent full.`);+ else if (typeof e.contextTokens === 'number') parts.push(`It is carrying ${tokens(e.contextTokens)} tokens of context.`);+ if (e.tokens) parts.push(`It has used ${tokens(e.tokens)} tokens so far.`);+ parts.push(`Circuit breaker: ${e.breaker}.`);+ if (e.lastTool) parts.push(`Last tool was ${e.lastTool}${typeof e.lastActiveSecAgo === 'number' ? `, ${ago(Date.now() - e.lastActiveSecAgo * 1000)}` : ''}.`);+ if (e.inboxBacklog) parts.push(`${plural(e.inboxBacklog, 'message')} waiting in its inbox.`);+ parts.push(e.hasMemory ? "It has recorded memory — ask me to read it." : 'It has not recorded much memory yet.');+ return parts.join(' ');+ }, 'agent detail')+ }),++ // ── list_agents ───────────────────────────────────────────────────────+ tool({+ name: 'list_agents',+ description:+ 'The FULL roster, including archived (inactive) agents: each one\'s name, engine, active-or-archived state, working directory, context fill, and breaker state. Use this to enumerate EVERYONE (including inactive agents), or to answer "where is X working", "who is archived", or "who is near their context limit". For live workers only, get_fleet_status is lighter.',+ parameters: {+ type: 'object',+ properties: {+ includeArchived: { type: 'boolean', description: 'Default true. Set false to list only active agents.' }+ },+ required: [],+ additionalProperties: false+ },+ execute: (input) =>+ spoken(async () => {+ const a = obj(input);+ const includeArchived = a.includeArchived !== false;+ const dir = await window.cth.hiveAgentDirectory();+ const all = Array.isArray(dir.agents) ? dir.agents : [];+ if (!all.length) return 'The hive has no registered agents.';+ const active = all.filter((e) => !e.archived);+ const archived = all.filter((e) => e.archived);+ const near = active+ .filter((e) => typeof e.contextPct === 'number' && e.contextPct >= 70)+ .map((e) => `${e.name} at ${e.contextPct} percent`);+ const describe = (e: typeof all[number]): string =>+ `${e.name} on ${e.provider}${e.cwd ? ` in ${shortDir(e.cwd)}` : ''}${+ typeof e.contextPct === 'number' ? `, context ${e.contextPct} percent` : ''+ }`;+ const parts: string[] = [];+ parts.push(+ `${plural(active.length, 'active agent')}${archived.length ? ` and ${plural(archived.length, 'archived agent')}` : ''}.`+ );+ if (active.length) parts.push(`Active: ${active.slice(0, 12).map(describe).join('; ')}.`);+ if (includeArchived && archived.length)+ parts.push(+ `Archived: ${archived+ .slice(0, 12)+ .map((e) => `${e.name}${e.cwd ? ` (last in ${shortDir(e.cwd)})` : ''}`)+ .join('; ')}.`+ );+ if (near.length) parts.push(`Near their context limit: ${near.join(', ')}.`);+ return parts.join(' ');+ }, 'agent roster')+ }),++ // ── get_board ─────────────────────────────────────────────────────────+ tool({+ name: 'get_board',+ description:+ 'The hive plan narrative — the human-readable board the orchestrator keeps in prose (the current plan, priorities, and notes). Call this when the user asks about the plan, the strategy, the roadmap, or what the board says.',+ parameters: { type: 'object', properties: {}, required: [], additionalProperties: false },+ execute: () =>+ spoken(async () => {+ const board = await window.cth.hiveBoard();+ const text = despan(board || '');+ if (!text) return 'The board is empty right now.';+ return clip(text, 1800);+ }, 'board')})];}