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(codex): lifecycle-hook bridge for hive parity + unify agy/codex dispatch
Chaitanya Giri0a3502af7ee7
diff --git a/src/main/hive.ts b/src/main/hive.tsindex 2923dc52..dfa70d5a 100644--- a/src/main/hive.ts+++ b/src/main/hive.ts@@ -19,7 +19,7 @@*/import {existsSync, mkdirSync, readFileSync, writeFileSync, renameSync,- readdirSync, statSync, rmSync, appendFileSync+ readdirSync, statSync, rmSync, appendFileSync, symlinkSync, copyFileSync} from 'node:fs';import { join, dirname } from 'node:path';import { homedir } from 'node:os';@@ -322,12 +322,13 @@ export class HiveManager {const claudeProvider = isClaudeProvider(meta.provider ?? 'claude');// Non-hive-aware providers (Antigravity's `agy`, OpenAI's `codex`) don't- // understand Claude Code's flags or hook protocol — no telemetry, no- // `--settings` hooks. But they DO take an INITIAL prompt to orient the- // session, so we still inject the same hive identity+protocol as the first- // turn — the closest thing to `--append-system-prompt` these CLIs offer- // (after the first turn the session continues normally). This is what makes- // a Gemini/Codex worker hive-aware without Claude installed at all.+ // understand Claude Code's flags (no `--append-system-prompt`, no telemetry,+ // no `--settings`). Instead: (1) the hive identity+protocol rides in as the+ // session's INITIAL prompt — the closest thing to `--append-system-prompt`+ // these CLIs offer (after the first turn the session continues normally); and+ // (2) lifecycle hooks are wired via the preset's `hookBridge` below. Together+ // that makes a Gemini/Codex worker a full hive citizen — live status ++ // Stop→inbox-drain — without Claude installed at all.//// How the prompt rides in differs by CLI:// - agy takes it under a flag (`agy -i "<prompt>"`) → push [flag, prompt].@@ -338,25 +339,39 @@ export class HiveManager {const preset = providerPreset(meta.provider ?? 'claude');const flag = preset.initialPromptFlag;const prompt = this.injectedPrompt(meta, dir, root, opts.semanticMemory ?? false);- // Only agy exposes a Claude-compatible lifecycle-hook surface we can bridge- // (PreToolUse/PostToolUse/Stop/…). Install the agy-hook shim so a Gemini- // worker gets the SAME live status + inbox-drain Claude does — on the- // subscription, no SDK/API key. Codex has NO such hooks and cannot reuse the- // bridge, so it is NOT installed for codex; codex relies on the renderer's- // idle inbox-wake nudge to drain its inbox (see useHive.ts) and on its outbox- // being drained provider-agnostically by the router.- if (meta.provider === 'antigravity') {+ // Both agy and codex expose a Claude-style lifecycle-hook surface, so each+ // gets the SAME live status + Stop→inbox-drain Claude does — selected by the+ // preset's `hookBridge`. agy needs a translating shim (its hook stdin/stdout+ // shape differs from Claude's); codex reuses the Claude `cth-hook` shim+ // verbatim (its hook payload + response contract are already Claude-shaped)+ // and is isolated to a per-agent CODEX_HOME so the user's global ~/.codex is+ // never mutated. Both share the HIVE_SOCK wiring below.+ const preArgs: string[] = [];+ const bridge = preset.hookBridge;+ if (bridge) {const sock = this.sockPath();if (sock) {env.HIVE_SOCK = sock;- try { this.installAgyHooks(); } catch (e) { console.error('[hive] installAgyHooks failed:', e); }+ try {+ if (bridge === 'agy') this.installAgyHooks();+ else if (bridge === 'codex') {+ env.CODEX_HOME = this.installCodexHooks(dir);+ // Codex refuses to run hooks from a config dir without persisted+ // "hook trust" (normally an interactive gate). Our hooks.json is+ // hive-authored inside an isolated CODEX_HOME, so we bypass that gate+ // for this automated spawn — the flag's documented use ("automation+ // that already vets hook sources"). Without it the hooks silently+ // never fire. Must precede the positional prompt.+ preArgs.push('--dangerously-bypass-hook-trust');+ }+ } catch (e) { console.error(`[hive] install ${bridge} hooks failed:`, e); }}}// Inject the protocol text whichever way the CLI accepts it. If a provider// somehow exposes neither a flag nor a positional prompt, spawn bare.- if (flag) return { args: [flag, prompt], env };+ if (flag) return { args: [...preArgs, flag, prompt], env };// Positional initial prompt (codex). Append as a trailing argv element.- return { args: [prompt], env };+ return { args: [...preArgs, prompt], env };}// Stage 7A — first-party Claude Code telemetry → the embedded loopback OTLP@@ -610,8 +625,8 @@ export class HiveManager {// assistant, any archived agent (closed tab), and providers that can't// drain an inbox (hookless custom commands) so mail never piles into a dead// inbox no one reads. Claude, Codex AND Antigravity workers ARE included —- // each can drain its inbox: Claude via its Stop hook, Antigravity via the- // agy-hook Stop→drain bridge, Codex via the renderer's idle inbox-wake nudge.+ // each can drain its inbox on Stop: Claude via its native Stop hook, and+ // Antigravity/Codex via their `hookBridge` Stop→drain (agy-hook / codex-hook).? Object.keys(reg.agents).filter((a) =>a !== msg.from&& !reg.agents[a]?.isAssistant@@ -634,10 +649,10 @@ export class HiveManager {continue;}// A provider that can't drain its own inbox (a hookless custom command)- // would let direct mail rot unread. Claude (Stop hook), Antigravity- // (agy-hook Stop→drain bridge) and Codex (renderer idle inbox-wake nudge)- // all drain their inbox, so they receive directly into their inbox/. For a- // provider that can't, try a terminal work-order handoff to its REPL (#53);+ // would let direct mail rot unread. Claude (native Stop hook) and+ // Antigravity/Codex (their `hookBridge` Stop→drain) all drain their inbox,+ // so they receive directly into their inbox/. For a provider that can't, try+ // a terminal work-order handoff to its REPL (#53);// if the renderer is unavailable, bounce to god to relay. God is exempt// (the bounce target).if (t !== godId && !canReceiveInbox(reg.agents[t]?.provider)) {@@ -834,6 +849,61 @@ export class HiveManager {}}+ /** Codex lifecycle-hook bridge → full hive parity for a `codex` worker (live+ * status + Stop→inbox-drain), the codex counterpart of installAgyHooks().+ *+ * Codex's hook contract is already Claude-shaped: snake_case stdin+ * (hook_event_name/tool_name/tool_input/session_id/cwd) and a matching response+ * contract, where `Stop` honoring {decision:'block',reason} means "continue,+ * using reason as the next prompt" — exactly what drainForStop() returns. So we+ * reuse the Claude `cth-hook` shim VERBATIM (no translator, unlike agy) and let+ * HookServer handle everything unchanged.+ *+ * ISOLATION: rather than mutate the user's global ~/.codex (which also holds+ * their login), we point this worker at a PER-AGENT CODEX_HOME (`<dir>/.codex`,+ * alongside Claude's settings.json) holding only our hooks.json — so the hooks+ * fire ONLY for hive workers and a personal `codex` run is untouched. The user's+ * ~/.codex/auth.json + config.toml are linked in (read-only) so login + model/+ * provider/trust settings still apply. Best-effort + idempotent on respawn.+ * Returns the CODEX_HOME path for the caller to put in the worker's env. */+ private installCodexHooks(dir: string): string {+ const home = join(dir, '.codex');+ try {+ mkdirSync(home, { recursive: true });+ const shim = this.shimPath();+ if (shim) {+ // No matcher = match all tools/events; every event routes to the same+ // cth-hook shim (it reads the event from the payload's hook_event_name).+ const entry = { hooks: [{ type: 'command', command: `node ${shim}`, timeout: 0 }] };+ const hooks = {+ PreToolUse: [entry],+ PostToolUse: [entry],+ Stop: [entry],+ SubagentStop: [entry],+ SessionStart: [entry],+ UserPromptSubmit: [entry],+ PreCompact: [entry],+ PostCompact: [entry]+ };+ writeFileSync(join(home, 'hooks.json'), JSON.stringify({ hooks }, null, 2), 'utf8');+ }+ // Carry the user's Codex login + config into the relocated home so the+ // worker authenticates and respects the user's model/provider/trust config.+ // Symlink (read-only intent); fall back to a copy where symlinks need+ // privilege (Windows). Skip if already present (idempotent).+ const userHome = join(homedir(), '.codex');+ for (const f of ['auth.json', 'config.toml']) {+ const src = join(userHome, f);+ const dest = join(home, f);+ if (existsSync(src) && !existsSync(dest)) {+ try { symlinkSync(src, dest); }+ catch { try { copyFileSync(src, dest); } catch { /* best-effort */ } }+ }+ }+ } catch (e) { console.error('[hive] installCodexHooks failed:', e); }+ return home;+ }+/** Write the live fleet snapshot Michael reads (`fleet.json`, gitignored).* Best-effort — called from a timer, must never throw. */writeFleetSnapshot(snapshot: unknown): void {diff --git a/src/shared/agentProvider.ts b/src/shared/agentProvider.tsindex 8c847521..fbfd02dd 100644--- a/src/shared/agentProvider.ts+++ b/src/shared/agentProvider.ts@@ -39,15 +39,28 @@ export interface AgentProviderPreset {autoFlag?: string;/** Claude Code accepts the hive identity injection (`--append-system-prompt`* + hook `--settings`). Other CLIs don't — they spawn with the shared AGENT_*- * env only. Gates the Claude-specific spawn injection in hive.ensureAgent. */+ * env only. Gates the Claude-specific spawn injection in hive.ensureAgent.+ * NOTE: this gates the *Claude-only* flag path specifically — it is NOT the+ * same as "participates in the hive". A non-hiveAware provider can still be a+ * full hive citizen (live status + Stop→inbox-drain) via a `hookBridge`. */hiveAware: boolean;+ /** Which config-file lifecycle-hook bridge a NON-hiveAware provider uses to get+ * the same live status + Stop→inbox-drain that Claude gets from `--settings`:+ * - 'agy' → installAgyHooks() writes ~/.gemini/.../hooks.json (translating+ * shim, because agy's stdin/stdout shape differs from Claude's).+ * - 'codex' → installCodexHooks() writes a per-agent CODEX_HOME/hooks.json and+ * reuses the Claude `cth-hook` shim verbatim (Codex's hook payload+ * + response contract are already Claude-shaped).+ * Claude leaves this undefined (it uses its native `--settings` path, gated by+ * hiveAware); `custom` leaves it undefined (no bridge → no hooks). This is the+ * single switch hive.ensureAgent dispatches on to wire the bridge. */+ hookBridge?: 'agy' | 'codex';/** Whether the router may DELIVER inbox mail to this provider (vs bouncing it* to the god). Requires a way for the agent to actually drain its inbox: Claude- * via its Stop hook, Antigravity via the agy-hook bridge's Stop→drain, Codex- * via the renderer's idle inbox-wake nudge (no hook surface of its own). A- * provider with no inbox-drain path (custom) can't, so its mail still bounces.+ * via its Stop hook, and Antigravity/Codex via their `hookBridge` Stop→drain.+ * A provider with no inbox-drain path (custom) can't, so its mail still bounces.* Distinct from hiveAware: agy/codex are NOT hiveAware (no Claude injection)- * but CAN receive inbox. */+ * but CAN receive inbox via their bridge. */canReceiveInbox: boolean;/** For non-hive-aware CLIs that still take an INITIAL prompt to orient the* session (Antigravity's `agy -i "<prompt>"`), the flag to pass it under. The@@ -90,14 +103,19 @@ export const AGENT_PROVIDER_PRESETS: AgentProviderPreset[] = [nonInteractiveEnv: { CODEX_NON_INTERACTIVE: '1' },supportsModel: true,modelFlag: '--model',- // Codex is NOT hiveAware: it has no Claude `--append-system-prompt`/`--settings`- // hook surface. The hive protocol is injected as Codex's INITIAL prompt, which- // it takes POSITIONALLY (`codex "<prompt>"`) — hence initialPromptFlag is- // undefined and hive.ts appends the prompt as a quoted trailing arg.+ // Codex is NOT hiveAware in the Claude-flag sense: it has no+ // `--append-system-prompt`/`--settings`. The hive protocol is injected as+ // Codex's INITIAL prompt, which it takes POSITIONALLY (`codex "<prompt>"`) —+ // hence initialPromptFlag is undefined and hive.ts appends it as a trailing arg.hiveAware: false,- // Codex can receive inbox: it has no Stop hook, but the renderer's idle- // inbox-wake nudge types the "you have new inbox mail" line into idle Codex- // PTYs (same path as agy), so mail is delivered rather than bounced to god.+ // …but Codex DOES expose a Claude-style hooks system (hooks.json / config.toml+ // [hooks]; PreToolUse/PostToolUse/Stop/…), so it gets full hive parity via the+ // 'codex' bridge: a per-agent CODEX_HOME/hooks.json wired to the cth-hook shim+ // (see hive.installCodexHooks). Stop→drain works natively (Codex's Stop honors+ // {decision:'block',reason} = continue-with-prompt, exactly like Claude).+ hookBridge: 'codex',+ // Inbox drains via the codex-hook bridge's Stop→drain (the renderer's idle+ // inbox-wake nudge remains as a harmless fallback for an idle worker).canReceiveInbox: true,initialPromptFlag: undefined,// Codex has no stable session-resume CLI flag in the curated reference; spawn@@ -114,6 +132,7 @@ export const AGENT_PROVIDER_PRESETS: AgentProviderPreset[] = [modelFlag: '--model',autoFlag: '--dangerously-skip-permissions',hiveAware: false,+ hookBridge: 'agy', // installAgyHooks() → ~/.gemini/.../hooks.json (translating shim)canReceiveInbox: true, // via the agy-hook bridge (Stop→drain); verified agy honors hook decisionsinitialPromptFlag: '-i', // agy --prompt-interactive: orient the session, then continueresumeFlag: '--conversation' // agy: resume a previous conversation by ID@@ -159,8 +178,8 @@ export function isHiveAwareProvider(provider: AgentProvider | undefined): boolea/** Whether the router may deliver inbox mail to this provider (else bounce to* the god). True for any provider that can actually drain its inbox — Claude- * (Stop hook), Antigravity (agy-hook Stop→drain bridge) and Codex (renderer- * idle inbox-wake nudge); false for hookless custom commands. */+ * (Stop hook), Antigravity and Codex (their `hookBridge` Stop→drain); false for+ * hookless custom commands. */export function canReceiveInbox(provider: AgentProvider | undefined): boolean {return providerPreset(provider ?? 'claude').canReceiveInbox;}