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 gts47/main into integrate/v0.3.4 — Vyapak's terminal/queue/roster wave, auto-compact philosophy carved out

Chaitanya Giri2ed3b49c6ee6
diff --cc CHANGELOG.md
index 385422cb,0d068f20..4609836b
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -4,269 -4,31 +4,294 @@@ All notable changes to this project ar
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to
[Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+ ## [Unreleased]
+
+ Terminal reliability: the blank pane and the message queue that silently stopped
+ delivering are both fixed, and fullscreen gets a proper agent roster.
+
+ ### Added
+ - **Fullscreen agent roster rail.** The horizontal tab bar ran out of room past a handful of agents and hid the operator controls; it's replaced by a left rail — `+ agent` pinned at the top, god agents ungrouped above everything, workers bucketed under repository headers, restore-team and its dismiss chips pinned at the bottom. An isolated agent's cwd is its own git worktree, so a new `mainRepoRoot` helper follows a linked worktree back to its main checkout (cached per cwd) and groups key on the absolute repo root, so two checkouts with the same name stay separate. Notes render on the row (one line per bullet) instead of behind a hover popover, the note editor becomes a textarea so Enter makes a new bullet instead of dropping every bullet but the first, pause/halt/steer come back in fullscreen, god agents render the full Command Center, and drag-to-reorder carries over (confined to an agent's own repository group). The destructive kill button is gone.
+ - **`typing` badge — see why a queue is held.** A message queue held by your own unsent text on an agent's prompt used to look identical to an idle agent with nothing to do. Agent cards and the fullscreen roster now show a **"your draft"** badge whenever you have unsubmitted text on that agent's prompt. It's derived at render from the same check the delivery gate uses, so the badge can never disagree with the reason nothing is being delivered.
+ - **[`docs/message-queue.md`](./docs/message-queue.md)** — the delivery contract: who may type into an agent's terminal, when, and what automation is never allowed to do to your text.
+
+ ### Changed
+ - **One gate for every automatic writer.** The queue kept breaking because two loops each decided for themselves when it was safe to type into a terminal. The inbox-wake nudge now enqueues like scheduled `/compact` already did, so a single drain loop owns every "is this terminal free?" decision — idle, off cooldown, past boot grace, delivery not paused, no user draft in the way.
+ - **Automation never destroys or closes what you own.** A draft block lasts half an hour rather than a minute, a picker block half an hour rather than three minutes, and when either expires delivery simply types *after* whatever is on the line (the two fuse into one prompt). Wiping the line first, and sending Escape at an open picker, are both gone — deleting text is worse than garbling one prompt, and we can't verify that Escape closed anything. Both keys remain on the composer's own button, where you asked for them.
+ - **Terminal zoom scales the whole pane.** Cmd +/- moved out of `PtyTerminalView` into a shared subscribable module, so it now scales the message composer and the roster along with the terminal instead of leaving them pinned at sizes tuned for a 14" display.
+ - **Changing an agent's model within the same provider resumes its session** instead of starting fresh (best-effort — an agent with no recorded session still gets its model changed).
+ - **Restore team runs in parallel** and the login-shell capture is memoised, so rebuilding a roster no longer serialises one shell probe per agent. Agents are added in roster order rather than completion order.
+
+ ### Fixed
+ - **Blank terminal pane where typing does nothing.** Three causes, which is why every single-cause fix only half-worked. (a) WebGL is now a lease taken on attach and released on detach — a browser allows only ~16 live contexts and silently discards the oldest past that cap, so restoring a team blew the cap and Chromium killed a background terminal's renderer while its pty, buffer and subscription stayed healthy. (b) `requestInitialPtyRedraw` latches only once the redraw actually succeeds, instead of burning the terminal's one chance on a failed fire-and-forget IPC. (c) The needs-repaint marker is cleared only after the refresh returns, so a throw no longer discards the last record that the terminal needed repainting.
+ - **Message queue silently stopped delivering to an agent.** (a) Only a *bare* command opens a picker — `/model` prompts you to choose, `/model sonnet` applies the argument and returns to the prompt; first-token matching latched the block on both and the submitting Enter couldn't clear it. (b) The picker block now expires like the draft block does, so a picker closed in a way we can't observe no longer wedges the queue for the rest of the session. (c) `lineBuf` moved onto the pool entry and is reset everywhere `inputDirty` is — as a closure variable it survived a draft clear, so the next keystroke recomputed the block from text that had just been deleted.
+ - **Phantom drafts blocked delivery against text that didn't exist.** `inputDirty` is inferred by counting keystrokes, and a TUI that swallows keys for its own UI leaves it set while the prompt is visibly empty. The prompt is now read from xterm's rendered buffer (cursor row, prompt chrome stripped) — deliberately one-directional: the screen can only *clear* a phantom draft, never invent one, because being wrong the other way would type over something you really wrote.
+ - **A queued message could be typed into an open picker and acked as delivered.** Clearing the input line no longer clears the picker latch — Ctrl-U kills the input line, it does not close a menu — so automation is no longer told the prompt is free while a picker still owns it.
+ - **A model or command change died on reload.** `updateAgent` now persists when a durable field changes (volatile run-state fields — status, action, progress, context counters — still skip the write, so a burst of terminal output doesn't rewrite storage).
+ - **The roster stopped spawning `git rev-parse` on every chunk of terminal output** — failed and in-flight repo lookups are cached, so an agent outside a repo is looked up once.
+
+## [0.3.3] — 2026-07-03
+
+**An IDE on the floor, and a seventh engine.** Two headliners: a **built-in Monaco IDE** — the
+VS Code editor engine in a full-window overlay, with a git CHANGES rail, side-by-side diffs vs
+HEAD, a file tree, editor tabs, and Cmd/Ctrl+S save — and **GitHub Copilot CLI** as a first-class
+agent engine, the project's **first community-contributed provider**
+([PR #101](https://github.com/chaitanyagiri/munder-difflin/pull/101) by
+[@anxkhn](https://github.com/anxkhn)).
+
+### Added
+- **Built-in Monaco IDE panel.** A title-bar **IDE** button toggles a full-window IDE overlay
+ (matching the existing fullscreen-overlay pattern — the office floor, terminals, and voice UX are
+ untouched). Left rail: a **git CHANGES list** (click a file → read-only **side-by-side diff vs
+ HEAD**) plus the reused workspace **file tree** (click → edit). Right: **editor tabs** with
+ dirty-state dots, save, and close; **Cmd/Ctrl+S** saves the active tab. The workspace root
+ snapshots from the selected/god/first agent cwd. Monaco is **fully self-hosted** —
+ electron-vite-safe bootstrap with bundled `?worker` imports and `loader.config({ monaco })`, no
+ CDN — themed to the harness's light palette, and **all fs/git access goes through main-process
+ IPC** (`git:diff` + preload bridge; the renderer holds no fs/git access)
+ (`src/renderer/src/ide/*`, `src/main/git.ts`).
+- **GitHub Copilot CLI agent engine** (`copilot`, npm `@github/copilot`) — community-contributed.
+ Registered as a provider preset driven in Copilot's documented non-interactive **print mode**:
+ `copilot -p "<prompt>" -s --allow-all-tools --no-ask-user [--model <id>]`, with the auto-approval
+ flags **gated by the floor auto-mode toggle** like every other engine. Includes a
+ **`COPILOT_MODELS` picker** (Claude Sonnet 4.5 default · GPT-5.4 · auto), `--resume` session
+ continuity (best-effort), voice-hire (`spawn`) support, binary inference for pasted commands, and
+ the official `npm install -g @github/copilot` offered by the missing-CLI installer. Non-hiveAware
+ by design: print mode exits per turn and exposes no hook bridge, so `canReceiveInbox` is `false`
+ and routed mail bounces to the GOD orchestrator instead of silently dropping
+ (`src/shared/agentProvider.ts`, PR #101 — thanks [@anxkhn](https://github.com/anxkhn)).
+- **Agent-provider registry test.** A self-contained, framework-free test
+ (`node test/agent-provider.test.cjs`) transpiles the shared registry and asserts provider
+ selection, the copilot command shape, model/resume passthrough, and codex non-regression.
+
+### Fixed
+- **IDE: no silent loss of edits typed during an in-flight save.** Keystrokes entered while a save
+ was still writing can no longer be dropped when the save completes.
+
+## [0.3.2] — 2026-06-27
+
+**Talk to Michael.** The headline is **Realtime Michael** — a low-latency **voice channel to the
+GOD orchestrator**, running alongside the async terminal floor. Press **Talk**, and Michael listens,
+answers, and *acts* in real time: he reads the hive (tasks, board, memory, agents, activity) and —
+behind spoken **echo-back confirmation** for anything destructive — creates and assigns work,
+dispatches agents, spawns and kills workers, and steers the floor, all attributed to a distinct
+**michael-voice** actor that pings the GOD terminal. He greets you on connect, **speaks task
+completions the moment they land** ("respond when done"), and runs under a live cost meter with a
+hard spend cap and an idle auto-disconnect. It's **bring-your-own OpenAI key**: the key is decrypted
+**main-only**, minted into short-lived ephemeral session tokens, and never reaches the renderer. Plus
+**Slack hardening** (proactive posting off by default; no sends without an explicit thread), a
+dedicated **auto-compact** maintenance schedule decoupled from missions, and **per-agent environment
+metadata**.
+
+> **Live verification note.** The realtime voice loop is **human-verified end-to-end** on a real
+> OpenAI key — connect → mic → Michael answers via the read tools, and the full destructive action
+> path (spoken echo-back confirm → spawn / kill / dispatch → the worker appears on the floor →
+> completion spoken back) was exercised live. It requires **your own OpenAI key with Realtime API
+> access**; without one the **Talk** button stays visibly disabled with a "needs OpenAI key" cue.
+
+### Added
+- **Realtime Michael — talk to the GOD orchestrator by voice.** A new low-latency realtime channel
+ (OpenAI Realtime API over WebRTC) sits next to the async terminal. A **Talk** toggle (on Michael's
+ card and in any fullscreen terminal) opens a mic session with EC/NS/AGC, semantic-VAD turn-taking +
+ barge-in, and a device picker for both microphone and speaker. Michael runs his own persona and
+ answers in a natural voice, with an `Off → Connecting → Listening → Responding → Working` state
+ machine surfaced live on his card (`src/renderer/src/realtime/*`, `src/main/realtime.ts`,
+ `RealtimeMichaelToggle.tsx`).
+- **BYOK ephemeral-token mint.** The voice session authenticates with a **short-lived ephemeral
+ client secret** minted main-side from your stored OpenAI key — the real key is decrypted main-only
+ and never crosses IPC. The renderer's CSP allows the WebRTC SDP exchange to reach `api.openai.com`
+ while keeping everything else locked down (`src/main/realtime.ts`, renderer `index.html` CSP).
+- **Voice action set with tiered echo-back confirmation.** Michael can *do* things by voice — read
+ tools (tasks / board / memory / agents / activity / cost) plus the full action set: create and
+ assign tasks, dispatch agents, pause / steer / halt, spawn / hire, kill, and edit schedules. Every
+ **destructive** verb is gated behind a spoken **echo-back confirmation** (a distinct confirm token,
+ never a bare "yes"), with hard refusals for killing the GOD agent or targeting all agents at once
+ (`src/renderer/src/realtime/actions.ts`, `src/main/realtimeActions.ts`).
+- **"Respond when done" completion loop.** Voice-dispatched work reports back on its own: a
+ main-process completion watcher detects when a dispatched task finishes (card → done or a done
+ reply in the inbox) and **proactively pushes the event into the live session so Michael speaks it
+ unprompted**, while a `CompletionToast` shows it on screen. If the session is closed, completions
+ queue to a desktop notification and a "completions since last session" warm-start; a `wait_for`
+ tool covers the block-until-done case (`src/main/realtimeCompletionWatcher.ts`,
+ `CompletionToast.tsx`).
+- **michael-voice as a distinct actor.** Actions taken by voice are attributed to a separate
+ **michael-voice** identity in messages, the board, and the activity log, and notify the GOD PTY —
+ so a voice-driven dispatch is auditable and never silently impersonates a worker.
+- **Cost guard + idle auto-disconnect for voice sessions.** A live session cost HUD by the Talk
+ toggle, a configurable **spend cap** that auto-disconnects when hit, and a configurable **idle
+ auto-disconnect** (default 3 min, 30 s–10 min or Off) so a forgotten-open mic can't run up a bill
+ (`src/renderer/src/realtime/cost*`, **Settings → AI Engines**).
+- **Greeting on connect.** When a session goes live, Michael opens with a warm, rotating greeting
+ ("Hi, what's up?", "Hey, how's it going?", …) instead of waiting in silence — best-effort and
+ guarded so a not-yet-ready data channel never blocks a successful connect.
+- **Conversational read-layer.** The voice read tools were reworked to actually answer hive
+ questions: `get_memory` no longer dead-ends, and new agent/board tools plus an expanded persona let
+ Michael talk through roster, tasks, and floor state naturally.
+- **Voice read-layer over hive messages (read/brief-only).** Realtime Michael can now read message
+ *content*, not just metadata: a `get_messages` tool returns a **full message by id, one mailbox, or
+ the latest across the floor** to brief the operator. **All redaction is main-side** —
+ `voiceMessages()` runs every `subject`/`body` through `redactSecrets()` before the result leaves
+ the main process, so the renderer/voice layer only ever receives already-redacted bodies (no
+ provider / Slack / GitHub / AWS / Google key, JWT, PEM private-key block, or `Bearer` token can
+ leak) and holds **zero** redaction policy. Read-only: it adds no write/mutate path — voice writes
+ still go through the separate confirm-gated action spine (`src/main/hive.ts` `voiceMessages` +
+ `redactSecrets`, `src/renderer/src/realtime/{tools.ts,VOICE-MESSAGE-ACCESS.md}`,
+ `test/voice-messages.test.cjs`).
+- **Talk reachable from any fullscreen terminal.** The Talk toggle is no longer Michael-only chrome —
+ it's reachable in any fullscreen terminal view (the toggle is global/session state, so it's correct
+ everywhere), while the per-session cost HUD stays Michael-only (`FullscreenTerminal.tsx`).
+- **OpenAI Realtime key — documented and gated.** **Settings → AI Engines** now documents the
+ **OpenAI Realtime key** as its own requirement (the same OpenAI provider key, distinct from your
+ Anthropic key; main mints a short-lived token from it per session). The Talk button shows a live
+ enabled/disabled status and an inline **"needs OpenAI key"** cue when none is set, so connecting
+ never lands on a silently-dead button (`RealtimeMichaelToggle.tsx`, `SettingsModal.tsx`,
+ `AiEnginesSettings.tsx`).
+- **Dedicated auto-compact maintenance schedule.** Auto-compaction is now a **persistent,
+ configurable maintenance mission** of its own, decoupled from the standup mission it used to ride
+ on (so editing standups can't silently drop it). It reappears disabled rather than vanishing, with
+ a mandatory warning and a configurable interval in the **Schedules** tab, plus a migration
+ (`src/main/schedules*`, `SchedulesTab`).
+- **Per-agent environment metadata + cwd guard.** Each agent now carries queryable environment
+ metadata with a working-directory validity guard, and a new agent-env query tool (`src/main/hive.ts`).
+
+### Changed
+- **"Voice" is now "Talk".** The voice feature is renamed **Talk** throughout, with a redesigned
+ navigation: the GOD card pops with a dedicated **Talk** line, and the worker nav cards are
+ compacted to make room (`src/renderer/src/components/*`).
+- **Robust voice task-matching (findCard).** Resolving a task by voice is now tolerant of
+ hyphens/punctuation, phrasing, and truncation: both the spoken phrase and the stored title are
+ normalized, candidates are **scored** (exact / prefix / token-coverage / substring), and close
+ matches trigger a spoken **"which one?"** disambiguation instead of silently mutating the wrong card
+ (`src/main/realtimeActions.ts`, `test/realtime-findcard.test.cjs`).
+
+### Fixed
+- **Fullscreen agent modal now opens above the fullscreen view.** The Add-Agent modal launched from
+ the in-fullscreen "+ agent" button rendered *behind* the fullscreen terminal (z-index 100 vs 250)
+ and was non-interactive. It's lifted to the dialog tier (300) so it's on top and clickable, and the
+ fullscreen Esc handler now closes the modal first instead of exiting fullscreen underneath it
+ (`AddAgentModal.tsx`, `FullscreenTerminal.tsx`).
+- **Voice `get_memory` no longer dead-ends.** The conversational read tools were fixed so memory
+ lookups return usable answers instead of stalling the turn.
+
+### Security
+- **BYOK voice secret invariant.** The real OpenAI key is encrypted at rest and decrypted
+ **main-only**; the renderer only ever sees a **short-lived ephemeral client secret** minted per
+ session. The key never crosses IPC and is never logged. The voice read-layer reports **tokens, not
+ dollars** (de-monetized chrome), and every destructive voice action is held behind spoken echo-back
+ confirmation with hard refusals for killing the GOD agent or targeting all agents at once.
+- **Slack: proactive posting off by default + explicit-thread guard.** App/voice Slack sends are now
+ **off by default** behind a config flag + Settings toggle, and a request with no explicit
+ channel+thread is **refused** rather than guessed — closing an unattended-broadcast path
+ (`src/main/slack.ts`, Settings).
+
+## [0.3.1] — 2026-06-22
+
+Three more coding CLIs join the floor — **OpenCode**, **Crush**, and **pi.dev** — each usable as a
+worker *and* as Michael, with **bring-your-own keys + local LLMs**. Plus two reliability fixes: the
+sleep-frozen message router and Codex workers' filesystem permissions.
+
+> **Live verification note.** The three engines are wired end-to-end and selectable as god, and
+> their architecture (preset + bridge + payload contract) was reviewed line-by-line. Their bridges'
+> *runtime* behavior needs real model calls, so the following are **on-device checks pending BYOK
+> keys / a local LLM** (not runtime-proven here):
+> 1. each bridge's **turn-end signal** actually fires — OpenCode `session.idle`, pi `agent_end`,
+> Crush's proxy-synthesized `Stop` — flipping the agent to *idle*;
+> 2. **OpenCode local-LLM** happy path: pick `local/<id>` with a base-URL set and confirm a turn
+> completes (the injected config now registers the *selected* model id);
+> 3. **Crush** routes through the proxy on an OpenAI-wire model (the default god is now
+> `openai/gpt-4o`) and Crush honors the partial `base_url` override;
+> 4. the **auto-mode gate** holds (no `permission:allow` / `--yolo` when the floor toggle is off).
+>
+> Crucially, mail delivery does **not** depend on those signals: a new **provider-agnostic
+> PTY-quiescence idle fallback** flips any silent-but-pinned-`working` agent to idle, so the
+> provider-agnostic idle inbox-wake nudge drains a god even if a bridge's turn-end signal never
+> fires. That backstop is the safety net under shipping all three as `canReceiveInbox:true`.
+
+### Added
+- **Three new selectable engines: OpenCode · Crush · pi.dev.** Each lands as a declarative
+ `AgentProviderPreset` and appears automatically in the Add-Agent picker (worker) and the god
+ engine picker (orchestrator). Each gets a **bridge** for live status + turn-end inbox-drain:
+
+ | Engine | Identity | Bridge | Notes |
+ |---|---|---|---|
+ | **OpenCode** | `opencode` (anomalyco/opencode, TS) | **native plugin** (`session.idle`) | bundled per-agent plugin; no traffic interception; auto-approve via gated `OPENCODE_CONFIG_CONTENT` |
+ | **Crush** | `crush` (charmbracelet, Go) | **proxy** (qwen-tier) | per-agent `CRUSH_GLOBAL_CONFIG` routes traffic through the loopback sidecar (Crush has no base-URL env) |
+ | **pi.dev** | `pi` (earendil-works) | **hooks** (bundled extension) | `pi.on(event)` → HIVE_SOCK; extension auto-approves tools only when the floor is in auto mode |
+
+- **BYOK + local-LLM config UI (Settings → AI Engines).** A new per-provider config surface: API
+ keys for the backend model-providers (Anthropic / OpenAI / Google / OpenRouter / Groq) stored
+ **write-only** in the encrypted secret broker (never read back to the renderer; materialized
+ main-only at spawn), plus per-engine **local base-URL** + default-model fields
+ (`HarnessConfig.providerBaseUrls` / `providerDefaultModels`). Pi/OpenCode/Crush/Qwen pick up the
+ keys + endpoints at spawn; auto-mode stays gated behind the floor toggle, and each engine runs
+ unsandboxed in auto mode (surfaced as a caveat).
+- **Provider-agnostic idle backstop (PTY-quiescence fallback).** A floor-wide check flips any agent
+ pinned `working` with no terminal output for a short window back to *idle* — so the idle
+ inbox-wake nudge can always drain a non-Claude god even if its bridge's turn-end signal (Stop /
+ `session.idle` / `agent_end`) never fires. This is the safety net under shipping all three engines
+ as god-eligible (`canReceiveInbox:true`) while their bridges await on-device verification
+ (`src/renderer/src/hooks/useHive.ts`).
+
+### Fixed
+- **Codex hive workers get full filesystem + auto-approval from spawn (parity with Claude).** A Codex-engine agent in auto mode launched with `-a never -s workspace-write`, whose sandbox scopes writes to the PTY cwd (the user's project). But a hive worker must also write to its agent folder at `<harnessHome>/hive/agents/<id>/` (move `inbox/` → `.done/`, append `memory.md`, drop outbox JSON, write deliverables) — a **different path tree from cwd**, which `workspace-write` blocked. So a freshly spawned Codex worker couldn't complete HIVE PROTOCOL housekeeping and reported "it does not have permissions … grant write permission to the agent folder." Codex's auto-mode flag is now `--dangerously-bypass-approvals-and-sandbox` — the documented equivalent of Claude's `bypassPermissions` / Antigravity's `--dangerously-skip-permissions` (skip all approval prompts **and** drop the OS sandbox), so a Codex worker has the same filesystem access and auto-approval as a Claude worker from the get-go (`src/shared/agentProvider.ts`; reference/copy updated in `src/shared/codexCommands.ts`, `OnboardingWizard.tsx`, `renderer/store/config.ts`). Claude/agy/antigravity behavior is unchanged.
+- **Re-arm the hive message router on wake (god→worker delivery survives sleep).** The outbox→inbox router is a `setInterval` (`hive.routeOnce` every ~1.5s) that, like the always-on beats, freezes during true macOS system sleep. `onSystemResume()` already re-armed the mission scheduler, the fleet/breaker beats, and keep-awake on `powerMonitor` `resume`/`unlock-screen` — but it never re-armed the router. So after a long sleep (e.g. laptop closed overnight) the scheduler→god path recovered while **every agent's outbox silently stopped draining**: god→worker, worker↔worker, and broadcast mail piled up undelivered, and no `message` event was logged. The resume handler now re-arms the router (clear-then-set, idempotent) **and** immediately drains the accumulated backlog instead of waiting for the first post-wake tick; the renderer's idle inbox-wake nudge then wakes each parked recipient once its mail lands (`src/main/index.ts`). Verified by `scripts/verify-keepalive-catchup.mjs` (now also reproduces the pre-fix backlog stall and proves the re-arm + flush).
+- **Open-source model quick-picks + local-setup guides in Add-Agent.** Hiring a worker on a local-capable CLI engine (OpenCode/Crush/pi.dev) now shows curated **OSS-model quick-picks** — a **Local** bucket (Mac-runnable Ollama tags: gpt-oss 20B/120B, Qwen3 30B-A3B/Coder, DeepSeek-R1 32B, Mistral Small, GLM-4.7-Flash, Llama 3.3 70B) and a **third-party OSS provider** bucket (BYOK: gpt-oss/Llama via Groq, DeepSeek-V4-Flash, GLM-4.6, Kimi K2.6, Qwen3-Coder via OpenRouter). Picking one fills the engine-correct slug (OpenCode `local/<tag>`, Crush/pi `ollama/<tag>`; provider slugs identical across engines) and rebuilds the command. Slugs are transcribed from a verified catalog — bleeding-edge frontier models are intentionally left out of code defaults. The Add-Agent help line and **Settings → AI Engines** local-setup area now hyperlink two how-to guides (run on open models · set up on a Mac Mini) (`src/shared/ossModels.ts`, `AddAgentModal.tsx`, `AiEnginesSettings.tsx`).
+- **Crush no longer dies with `Unknown command` on spawn (the hive protocol now reaches it).** A Crush worker was launched as `crush --model <m> --yolo "You are …(the whole hive protocol)"` — the protocol passed as a positional arg. But bare `crush` is an interactive Bubble Tea TUI on a Cobra root command, which reads the first positional as a **subcommand**, so it aborted with `unknown command "You are…"`; the protocol never reached the model, the worker never learned it was a hive agent, and the PTY died. Crush has no `--prompt` flag and `crush run` is one-shot, so the protocol is now **typed into the TUI** instead: a new preset capability `seedDelivery:'type-into-tui'` makes the spawn drop the positional (`crush [--model m] [--yolo]`) and hand the protocol back as a `seedPrompt`, which the renderer types in as the worker's first turn after a boot-grace — through the **same per-pty write-chain as the inbox-wake nudge**, so the seed and a nudge can never jam onto one line. Covers fresh Crush spawns, restores, and Crush-as-Michael (`src/shared/agentProvider.ts`, `src/main/hive.ts`, `src/main/index.ts`, `src/preload/index.ts`, `src/renderer/src/hooks/useHive.ts`, `AddAgentModal.tsx`, `AgentStrip.tsx`, `store.ts`).
+- **Auto restart-and-continue after a first-time engine-CLI install (no dead-end).** When an agent's engine binary (OpenCode/Crush/pi.dev/Codex/…) wasn't installed, the missing-CLI short-circuit ran the provider's installer in the PTY, then printed *"click restart & continue to launch the agent"* — but no such button exists for a not-yet-started agent, so the PTY just sat at `process exited (code 0)` and the agent dead-ended. Now, on a **clean install exit**, the PTY-exit handler auto restart-and-continues: it re-runs the *same* spawn into the *same* pty/window (carrying a `noAutoInstall` flag) so the freshly-installed CLI launches with no user click, and the renderer re-arms that terminal in place (clears the "process exited" line, re-enables input) via a new `pty:relaunch` signal. Provider-agnostic (every engine's installer path) and idempotent by construction — `noAutoInstall` guarantees the installer can never fire twice, and providers with no bundled installer (manual-hint-only) are never armed for relaunch. The install banner copy is now honest ("Installed — launching the agent…") (`src/main/index.ts`, `src/main/pty.ts`, `src/preload/index.ts`, `src/renderer/src/components/terminalPool.ts`).
+
+## [0.3.0] — 2026-06-21
+
+A platform release: the floor stops being Claude-shaped. **Selectable agent engines** make
+every hire — and Michael himself — a pluggable engine (Claude Code / Antigravity / Codex /
+local providers), each with its own **per-hire skills + MCP catalog** behind a consent UI. A
+new **integrations registry + loopback secret broker** turns "connect a service" into a
+write-only, registry-driven Settings flow. Michael can now **spawn an ephemeral worker straight
+from Slack** — reply, then tear it down safely with worktree GC and token caps — surfaced in a
+new **Workers tab**. Plus **temporal date-range skills** and a **worker capability catalog**, a
+**Provider / Hive picker** in onboarding and add-agent, the **Agent Gallery** (the rebranded
+Hiring Fair) with **six off-the-shelf hires**, feature-aware onboarding, and wake-reliability
+hardening. Everything from v0.2.8 and earlier is included.
+
+### Added
+- **Selectable agent engines + per-hire capabilities.** A new engine abstraction (`agentProvider` + an `mcpCatalog`, mirrored across a 3-file config) makes the runtime behind each agent *pluggable* — Claude Code, Antigravity, Codex, or a **local provider** (a claw/qwen backend proxy bridge with default-MCP merge). Each hire carries its own **manifest** of allowed skills + MCP servers (a default-deny allowlist over the catalog), with **bundled skills** shipped via Electron `extraResources` (`resources/skills` → `<resources>/skills`) and a **consent UI** that surfaces every skill/MCP a hire wants before it can use it — untrusted hire input is reviewed, never auto-granted.
+- **Swappable Michael (god) engine.** The orchestrator is no longer hard-wired to one CLI: `useHive` gains an engine-spawn path, Onboarding gains an **engine picker** for Michael, and a **change-engine flow** lets you re-home the god orchestrator onto a different engine without rebuilding the floor.
+- **Integrations registry + loopback secret broker.** A declarative **integrations registry** (`src/shared/integrations.ts`) plus a **loopback secret broker** (`src/main/integrationBroker.ts`): secrets are **write-only** (set once, never read back into the renderer) and reached only through the broker over loopback. A **registry-driven Settings UI** (`IntegrationsRegistry`) renders each integration's config form from the spec — conformed to registry spec v1 — and a first wave of **declarative templates** (the canonical schema + initial YC-style templates) ships in the registry. The `integrations:*` surface is exposed to the renderer through a dedicated preload bridge.
+- **God-triggered ephemeral Slack worker loop.** Michael can now **spawn an isolated worker directly in response to a Slack request** — the worker does the work, posts its reply back into the thread, and is then **torn down safely**. Lifecycle hardening adds **worktree garbage collection**, **token-cap wiring** per spawned worker, and a **teardown-safety gate** that refuses to auto-discard a worker's *unintegrated* work. The `pty:spawn` IPC handler was refactored into a reusable `spawnAgentCore` that underpins worker spawning, and a new **Workers tab** surfaces live ephemeral workers in the UI.
+- **Temporal date-range skills + worker capability catalog.** A family of date-range skills (`today` / `yesterday` / `thisWeek` / `lastWeek` / `thisMonth` / `thisQuarter` / `thisYear` / `lastMonth` / `lastQuarter` / `lastYear` / `last7Days` / `last30Days` … plus an arbitrary-range `temporal` resolver backed by `temporal/when.mjs`) resolve a named window to concrete ISO dates without hand-math. A **worker capability catalog** lets each spawned worker read exactly which skills and brokered integrations it has and how to call them.
+- **Provider / Hive picker UI.** A new `HivePicker` component plus a `ProviderLogo` set (real provider logos) appear in **onboarding** and the **add-agent** flow, so choosing the engine/provider for a hire is a first-class, visual step instead of a free-text command.
+- **Agent Gallery + six off-the-shelf hires.** The community gallery is rebranded from *The Hiring Fair* to the **Agent Gallery**, and ships **six ready-made, off-the-shelf hires** you can browse, review, and spawn.
+- **Feature-aware onboarding + a permissions & reliability step.** First-run onboarding now adapts to the features you have available and adds an explicit permissions & reliability step.
+- **Visible engine-CLI installer.** When the engine binary for a chosen provider is missing, the installer now runs **visibly** instead of failing silently, so a first-time setup self-heals.
+
+### Changed
+- **The Hiring Fair → Agent Gallery.** The gallery is renamed throughout (landing page, in-app links, copy) to *Agent Gallery*; existing hire links and the `/hires/` path continue to work.
+- **Add-Agent config IA rework + Command Center UX fixes.** The Add-Agent modal's configuration is reorganized around the new engine/capability model, with assorted Command Center UX cleanups.
+- **VDE prototype (experimental).** An experimental Virtual Desktop Environment prototype lands behind the scenes, with a Groq chat-completion module (`src/main/groq.ts`) powering its AI assist.
+
+### Fixed
+- **Orchestrator delegates opportunistically to existing agents.** Michael now checks the live roster (active agents in `registry.json` + their state in `fleet.json`) before spawning, and prefers routing a task to an existing agent that already fits — above all when the request names one ("ask Pam…", "have Jim…") — instead of reflexively creating a new agent; he only spawns a fresh one when no existing agent is a sensible fit, and says that he checked. Encoded in both the floor orchestrator prompt and the Slack autonomous-request protocol (`src/main/hive.ts`, `src/main/index.ts`).
+- **Auto-revive wedged terminals on wake.** A terminal that wedged while the machine slept is now detected and auto-revived when the machine wakes, instead of sitting dead until manually restarted.
+- **Catch up missed schedules on wake (power keep-alive hardening).** Scheduled missions whose fire time elapsed while the machine was asleep are now caught up on wake rather than silently skipped (verified by `scripts/verify-keepalive-catchup.mjs`).
+- **Worker stale-done guard.** A worker is now released only on a `done` authored *after* it was spawned, so a stale `done` from a prior life can no longer prematurely release or tear down a live worker.
+- **Floor: "add agent" button stays on one line.** The add-agent button no longer wraps as the roster fills.
+- **Voice button disabled with a tooltip when the Groq key is missing**, instead of failing on click.
+
+### Security
+- **Confined the `integrations:test` probe path.** The connectivity-test path for integrations is now constrained so it can't be turned into a secret-exfiltration or SSRF primitive — a brokered, bounded probe rather than an arbitrary outbound request driven by registry/secret input.
+
+## [0.2.8] — 2026-06-15
+
+A feature release: **shareable hires** — package a role-configured agent as a portable
+manifest, share it as a file or host it in a gallery, and import it into any office with one
+click. Plus **The Hiring Fair**, a community gallery of ready-made roles, and a hardened,
+untrusted-input import pipeline.
+
+### Added
+- **Shareable hires (#70, #71).** A portable `munder-difflin/hire@1` JSON manifest describing a role-configured agent — name, sprite, provider, model, command flags, goal, capability tags, token budget. Two import paths, one pipeline: a `munderdifflin://hire?src=<https-manifest-url>` deep link (fetched and validated in the main process, queued, then pulled by the renderer on mount) and an *import hire…* button in the Add-Agent modal that reads a local manifest file. Either way the manifest only **pre-fills** the Add-Agent modal behind an "imported" banner; spawning stays an explicit human click — import never auto-spawns. Protocol registration ships for all three platforms (macOS `open-url`, Windows/Linux single-instance lock + cold-start argv forwarding), and packaged builds register the scheme via `electron-builder.yml`.
+- **The Hiring Fair — community gallery** at [munderdiffl.in/hires](https://munderdiffl.in/hires/) (`docs/hires/`, static, no build step, served by the existing GitHub Pages setup). Seed roles drawn from the cast (Pam writes docs, Dwight enforces QA, Jim reviews PRs, Creed audits security, Angela audits the office's own token spend, Stanley does the migrations nobody wants), each with a Claude Code / Antigravity / Codex provider toggle (per-provider variants generated from one base manifest), function filters matching the landing page, and a client-side validator identical to the app's alongside a JSON schema (`docs/hires/spec/`). Model suggestions are data-driven (`docs/hires/models.json`), so new models are a one-line update.
+
+### Security
+- **A hire manifest is untrusted input — defense in depth.** No auto-spawn and no executable field: `provider: "custom"` is rejected and the binary always comes from the user's local provider preset. Embedded CLI flags are gated by a **default-deny allowlist** (`SAFE_FLAG_NAMES`) — only known-harmless flags pass, nothing system-prompt/settings-related — replacing an earlier denylist that drifted as each CLI added flags. `model` is constrained to a safe charset (`MODEL_RE`), and a command-line quoter neutralizes `cmd.exe` metacharacters (`& | ^ < > ( ) % !`) on **every** spawn path — closing a Windows command-injection class (PoC `"model":"x&calc"`). The manifest fetch is https-only, manual-redirect with per-hop re-validation (kills redirect SSRF into `127.0.0.1` / `169.254.169.254`, including an IPv6-bracket bypass), streamed with a 64 KB byte cap (no trusting `content-length`), a 10s timeout, and ≤5 hops. The dependency-free validator (`src/shared/hire.ts`) is shared by the main process, the renderer, the gallery (`docs/hires/validator.js`), and the JSON schema, so all four stay in sync.
+
## [0.2.7] — 2026-06-13
A feature release: talk to your agents with your voice, an opt-in enterprise Knowledge
diff --cc README.md
index 62c3214a,21af37ce..f9162226
--- a/README.md
+++ b/README.md
@@@ -111,9 -94,8 +111,9 @@@ terminal/event plane, and [`DESIGN.md`]
| Area | What works today |
|---|---|
- | **Real terminals** | Spawn Claude Code, Antigravity (`agy` / Gemini), OpenAI Codex, or a custom command in a `node-pty` PTY. Full read/write/resize/kill, live streaming over IPC, multi-agent. |
+ | **Real terminals** | Spawn Claude Code, Antigravity (`agy` / Gemini), OpenAI Codex (GPT), xAI Grok, Kimi Code, or a custom command in a `node-pty` PTY. Full read/write/resize/kill, live streaming over IPC, multi-agent. |
-| **Multi-provider hive** | Claude Code, Antigravity, Codex, and Grok workers can all participate in the same hive. Claude uses native hooks; the other first-class providers receive protocol injection plus lifecycle-hook bridges for safe routing. |
+| **Built-in Monaco IDE** *(new in v0.3.3)* | A title-bar **IDE** button opens a full-window Monaco editor (the VS Code editor engine, self-hosted — no CDN) over the floor: git CHANGES rail with **side-by-side diffs vs HEAD**, workspace file tree, editor tabs with dirty-state tracking, **Cmd/Ctrl+S** save. All fs/git access is brokered through the main process. |
- | **Multi-provider hive** | Claude Code, Antigravity, and Codex workers can all participate in the same hive. Claude uses native hooks; Antigravity gets a native `agy-hook` bridge; Codex receives the protocol as its initial prompt and participates through inbox/outbox routing. |
++| **Multi-provider hive** | Claude Code, Antigravity, Codex, and Grok workers can all participate in the same hive. Claude uses native hooks; Antigravity gets a native `agy-hook` bridge; Grok gets an AGENT_ID-scoped lifecycle-hook adapter; Codex receives the protocol as its initial prompt and participates through inbox/outbox routing. |
| **The hive** | On-disk multi-agent layer: per-agent identity + long-term memory, atomic-file mailboxes, a shared blackboard, append-only event log, single-committer git. |
| **GOD orchestrator** | An always-on supervisor agent that adjudicates traffic, routes tasks, scribes the blackboard, and escalates only critical items to you. |
| **Memory layer** | Markdown-first long-term memory per agent, mined into a shared semantic palace for instant recall; searchable from the UI. Degrades gracefully when the index isn't installed. |
@@@ -174,15 -144,9 +175,16 @@@
```
- At least one supported terminal-agent CLI on your `PATH`: **[Claude Code](https://claude.com/claude-code)**
(`claude`, the default command), **Antigravity** (`agy`, Gemini), **OpenAI Codex** (`codex`),
- **OpenCode** (`opencode`), **Crush** (`crush`), or **pi.dev** (`pi`). Claude uses native hooks,
- Antigravity uses the `agy-hook` bridge, Codex participates through initial-prompt protocol injection
- **xAI Grok** (`grok`), or **Kimi Code** (`kimi`).
- Claude uses native hooks, Antigravity uses the `agy-hook` bridge, and Codex participates through
- initial-prompt protocol injection plus inbox/outbox routing.
++ **xAI Grok** (`grok`), **Kimi Code** (`kimi`), **OpenCode** (`opencode`), **Crush** (`crush`), or
++ **pi.dev** (`pi`). Claude uses native hooks, Antigravity uses the `agy-hook` bridge, Grok uses an
++ AGENT_ID-scoped lifecycle-hook adapter, Codex participates through initial-prompt protocol injection
+ plus inbox/outbox routing, and OpenCode / Crush / pi.dev wire in via a native-plugin / proxy / hooks
+ bridge respectively. A missing engine CLI self-heals — the harness runs the installer in the
+ terminal, then auto restart-and-continues into the freshly-installed binary.
+- *Optional:* **bring-your-own API keys + local LLMs.** For the CLI engines, set per-provider keys and
+ local base-URLs (Ollama / LM Studio / vLLM) in **Settings → AI Engines**; see the guides on
+ [running on open models](https://munderdiffl.in/blog/run-munder-difflin-on-open-models/) and
+ [running on a Mac Mini](https://munderdiffl.in/blog/run-munder-difflin-on-a-mac-mini/).
- *Optional:* the semantic memory index for instant cross-session recall (the app works without it —
markdown memory still functions).
@@@ -281,10 -245,9 +283,11 @@@ docs/ `logo.png`
docs/media/ `og.png` (social previews) + rendered Remotion clips
landing-remotion/ Remotion project that renders the landing page's "how it works" clips
HIVE.md · SPEC.md · DESIGN.md multi-agent · terminal/event · visual design
+ docs/message-queue.md who may type into an agent's terminal, and when
```
+<div align="right">(<a href="#munder-difflin">↑ back to top</a>)</div>
+
## Design system
The aesthetic is **Animal Crossing × Earthbound × SNES menu UI** — pixel-snapped, chunky, friendly.
@@@ -323,8 -276,8 +326,8 @@@ Shipped in **v0.2.0–v0.3.2**
Next up:
- [ ] **More chat integrations** — Telegram and richer chat bridges that pipe a channel straight into Michael's queue (and route his replies back out), so you can run the floor from your phone.
- - [x] **More engines & providers** — the engine abstraction is in (Claude Code, Antigravity, Codex, local providers), and **v0.3.1 shipped OpenCode, Crush, and pi.dev** as worker+god engines with BYOK keys + local LLMs (live runtime verification pending on-device keys). Keep adding engines and broadening the per-hire capability catalog on top of it.
-- [ ] **More provider CLIs** — extend the provider layer beyond Claude Code, Antigravity, Codex, and Grok.
-- [ ] **Realtime Michael** — a low-latency realtime LLM channel for quick, snappy back-and-forth with the orchestrator, alongside the async terminal.
++- [x] **More engines & providers** — the engine abstraction is in (Claude Code, Antigravity, Codex, local providers), **v0.3.1 shipped OpenCode, Crush, and pi.dev** as worker+god engines with BYOK keys + local LLMs, and **v0.3.4 adds xAI Grok and Kimi Code**. Keep adding engines and broadening the per-hire capability catalog on top of it.
+- [ ] **More integration templates** — grow the integrations registry beyond the first-wave templates.
- [ ] **Fuller avatar coverage** — push the remaining station visits and tool-bubbles to be driven 100% by real Claude Code hook events.
- [ ] **Durable layout & command history** — extend persistence to agent layout and per-session command history.
diff --cc docs/sitemap.xml
index 9f338076,48397355..aca0c1b2
--- a/docs/sitemap.xml
+++ b/docs/sitemap.xml
@@@ -10,7 -10,7 +10,7 @@@
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://munderdiffl.in/</loc>
- <lastmod>2026-07-08</lastmod>
- <lastmod>2026-06-11</lastmod>
++ <lastmod>2026-08-05</lastmod>
<changefreq>weekly</changefreq>
<priority>1.0</priority>
</url>
diff --cc package-lock.json
index 23a16442,0e91820b..6373f1ad
--- a/package-lock.json
+++ b/package-lock.json
@@@ -1,12 -1,12 +1,12 @@@
{
"name": "munder-difflin",
- "version": "0.3.2",
- "version": "0.2.7",
++ "version": "0.3.3",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "munder-difflin",
- "version": "0.3.2",
- "version": "0.2.7",
++ "version": "0.3.3",
"hasInstallScript": true,
"dependencies": {
"@codemirror/lang-css": "^6.3.1",
diff --cc package.json
index 2a2c5c64,96c6e923..24a7332d
--- a/package.json
+++ b/package.json
@@@ -19,6 -19,7 +19,7 @@@
"typecheck:node": "tsc --noEmit -p tsconfig.node.json",
"typecheck:web": "tsc --noEmit -p tsconfig.web.json",
"typecheck": "npm run typecheck:node && npm run typecheck:web",
- "test:focused": "node --test test/auto-compact.test.cjs test/codex-remote.test.cjs test/control.test.cjs test/provider-automation.test.cjs test/provider-config.test.cjs test/queue-delivery.test.cjs test/terminal-automation.test.cjs test/terminal-recovery.test.cjs",
++ "test:focused": "node --test test/codex-remote.test.cjs test/control.test.cjs test/provider-automation.test.cjs test/provider-config.test.cjs test/queue-delivery.test.cjs test/terminal-automation.test.cjs test/terminal-recovery.test.cjs test/roster.test.cjs test/proc-kill.test.cjs",
"dist": "npm run build && electron-builder",
"dist:mac": "npm run build && electron-builder --mac",
"dist:win": "npm run build && electron-builder --win",
diff --cc src/main/config.ts
index 6e21c0f0,edbaa173..4202645c
--- a/src/main/config.ts
+++ b/src/main/config.ts
@@@ -4,12 -4,10 +4,13 @@@ import { dirname, join } from 'node:pat
import { homedir } from 'node:os';
import {
autoModeFlagForProvider,
+ defaultCommandForProvider,
inferAgentProvider,
+ providerPreset,
type AgentProvider
} from '../shared/agentProvider';
+import { defaultMcpDefaults } from '../shared/mcpCatalog';
+import type { IntegrationRecord } from '../shared/integrations';
/** A recurring auto-dispatched mission fired on an interval by the scheduler. */
export interface ScheduledMission {
@@@ -333,15 -241,10 +339,19 @@@ const DEFAULTS: HarnessConfig =
registeredRepos: [],
autoMode: true,
defaultCommand: 'claude',
+ godProvider: 'claude',
+ godModel: 'claude-opus-4-8',
+ // Global default model for every agent that hasn't picked one explicitly — wins
+ // over the role-based tiers (modelForRole) in the spawn handler, so all agents
+ // (incl. god) default to Fable 5. A per-agent model choice still overrides it.
+ defaultModel: 'claude-fable-5',
+ // Seeded from the MCP catalog so the consent defaults never drift from it
+ // (safe-readonly ON, write/secret OFF).
+ mcpDefaults: defaultMcpDefaults(),
+ maxConcurrentWorkers: 4,
+ workerIdleTimeoutMinutes: 20,
+ integrations: [],
+ defaultWorkerTokenCap: 0, // 0 = unlimited (human directive: NO per-worker cap)
semanticMemory: true,
embeddingModel: 'minilm',
missions: [OPS_STANDUP_MISSION],
diff --cc src/main/git.ts
index ec182d6c,48826f34..fd967203
--- a/src/main/git.ts
+++ b/src/main/git.ts
@@@ -144,71 -142,25 +144,90 @@@ export async function isRepo(cwd: strin
return res.ok && res.stdout.trim() === 'true';
}
+const MAX_DIFF_BYTES = 2 * 1024 * 1024; // 2 MB — keep the diff view responsive
+
+/** A file's two sides for a working-tree-vs-HEAD diff. `head` is the committed
+ * version ('' for a new/untracked file); `working` is the on-disk version ('' for
+ * a file deleted from the working tree). The renderer feeds these straight into
+ * Monaco's DiffEditor (original = head, modified = working). */
+export interface GitDiff {
+ ok: true;
+ path: string; // resolved absolute path (display only)
+ relPath: string;
+ head: string;
+ working: string;
+ headExists: boolean; // file is tracked at HEAD
+ workingExists: boolean; // file is present in the working tree
+ isBinary: boolean; // either side is binary → not text-diffable
+}
+
+/**
+ * Diff a single file: its committed (HEAD) content vs its current working-tree
+ * content. `relPath` MUST be repo-root-relative and is path-validated against
+ * `cwd` with the shared fs guard (no escaping the workspace). All git/fs access
+ * stays in the main process — the renderer only ever receives the two text sides.
+ */
+export async function getDiff(
+ cwd: string, relPath: string
+): Promise<GitDiff | { ok: false; error: string }> {
+ const abs = safeJoin(cwd, relPath);
+ if (!abs) return { ok: false, error: 'path escapes repository root' };
+
+ // HEAD side: `git show HEAD:<path>` — errors (untracked / new file) → no head version.
+ let head = '';
+ let headExists = false;
+ const show = await runGit(cwd, ['show', `HEAD:${relPath}`]);
+ if (show.ok) { head = show.stdout; headExists = true; }
+
+ // Working side: read the on-disk file. ENOENT → deleted from the working tree.
+ let working = '';
+ let workingExists = false;
+ let workingBinary = false;
+ try {
+ const s = await stat(abs);
+ if (s.size > MAX_DIFF_BYTES) {
+ return { ok: false, error: `file too large to diff (${(s.size / 1048576).toFixed(1)} MB)` };
+ }
+ const buf = await readFile(abs);
+ workingExists = true;
+ if (buf.includes(0)) workingBinary = true;
+ else working = buf.toString('utf8');
+ } catch {
+ workingExists = false;
+ }
+
+ const isBinary = workingBinary || head.includes('\0');
+ return {
+ ok: true,
+ path: abs,
+ relPath,
+ head: isBinary ? '' : head,
+ working: isBinary ? '' : working,
+ headExists,
+ workingExists,
+ isBinary
+ };
+}
+
+ /** The MAIN working tree of the repository `cwd` belongs to.
+ *
+ * For a normal checkout that's just the repo root. For a linked worktree it is
+ * the original repo, NOT the worktree directory — an isolated agent's cwd is
+ * `<harnessHome>/worktrees/<agent-id>`, whose basename is the agent id and says
+ * nothing about which project it's working on. `--git-common-dir` resolves to
+ * the shared `.git` of the main checkout from anywhere in the worktree family.
+ * Returns null when `cwd` isn't a git repo (or git is unavailable). */
+ export async function mainRepoRoot(cwd: string): Promise<string | null> {
+ const res = await runGit(cwd, ['rev-parse', '--path-format=absolute', '--git-common-dir']);
+ if (!res.ok) return null;
+ const gitDir = res.stdout.trim();
+ if (!gitDir) return null;
+ // `<repo>/.git` → `<repo>`. A bare repo has no working tree to name, so its
+ // own path is the best answer we have.
+ const stripped = gitDir.replace(/[\\/]\.git[\\/]?$/, '');
+ return stripped || gitDir;
+ }
+
/** Derive a safe `agent/<id>` branch name from a worktree path's basename. */
function agentBranchFor(wtPath: string): string {
const base = wtPath.split(/[\\/]/).filter(Boolean).pop() ?? 'agent';
diff --cc src/main/hive.ts
index 5c7679ed,ff2551fa..2140c9f8
--- a/src/main/hive.ts
+++ b/src/main/hive.ts
@@@ -528,74 -371,16 +529,75 @@@ export class HiveManager
// never fire. Must precede the positional prompt.
preArgs.push('--dangerously-bypass-hook-trust');
}
- else if (bridge === 'grok') this.installGrokHooks();
- } catch (e) { console.error(`[hive] install ${bridge} hooks failed:`, e); }
- }
+ else if (desc.shim === 'pi') {
+ // Pi (earendil-works) has a rich pi.on(event) lifecycle. We drop a
+ // bundled extension into a PER-AGENT PI_CODING_AGENT_DIR (so the user's
+ // global ~/.pi is never touched) that posts cth-hook-shaped payloads to
+ // HIVE_SOCK on tool_call/agent_end and auto-approves tools when the floor
+ // is in auto mode. HIVE_AUTO_APPROVE (set in spawnAgentCore from
+ // config.autoMode) gates the auto-allow — Pam guardrail #5.
+ // LIVE-UNVERIFIED: the exact extension API surface needs BYOK keys to
+ // prove; the renderer idle inbox-wake nudge is the guaranteed drain.
+ env.PI_CODING_AGENT_DIR = this.installPiHooks(dir);
+ }
+ else if (desc.shim === 'opencode') {
+ // OpenCode (anomalyco/opencode) has no Claude-shaped Stop hook, but its
+ // plugin API exposes a real session.idle event (god Decision 1). We drop
+ // a bundled plugin into a PER-AGENT OPENCODE config dir that posts
+ // HIVE_SOCK payloads on tool.execute.before/after + session.idle — the
+ // same Stop→drain semantics, provider-agnostic, no traffic interception.
+ // LIVE-UNVERIFIED (plugin auto-load + session.idle firing); the renderer
+ // idle inbox-wake nudge is the guaranteed drain fallback.
+ env.OPENCODE_CONFIG_DIR = this.installOpenCodePlugin(dir);
+ }
++ else if (desc.shim === 'grok') this.installGrokHooks();
+ } else if (desc.kind === 'proxy') {
+ // Stable per-spawn session id, stamped on every synthesized payload so
+ // recordSession (registry resume key) and the cost ledger persist.
+ const spawnTs = String(Date.now());
+ const sessionId = `proxy-${meta.id}-${createHash('sha1').update(root + meta.id + spawnTs).digest('hex').slice(0, 12)}`;
+ env.HIVE_PROXY_SESSION = sessionId;
+ // The CLI normally reads its upstream base URL from `baseUrlEnv`; capture
+ // the user's configured value as the sidecar's UPSTREAM, then point the
+ // CLI at the loopback proxy instead. Fall back to the cloud default if
+ // the user hasn't set one.
+ const upstream = process.env[desc.baseUrlEnv]
+ || (desc.api === 'anthropic' ? 'https://api.anthropic.com' : 'https://api.openai.com/v1');
+ const port = await this.startProxyBridge(meta.id, { sock, sessionId, api: desc.api, upstream });
+ // Only redirect the CLI through the proxy if the sidecar actually bound a
+ // port. On failure leave routing untouched → the CLI talks to its real
+ // upstream directly (degraded: no synthesized hive events, but it still
+ // runs). The degradation is logged, not hidden (1e).
+ if (port > 0) {
+ const loopback = `http://127.0.0.1:${port}`;
+ if (meta.provider === 'crush') {
+ // Crush has NO base-URL env override, so the generic env-rewrite is a
+ // no-op for it. Route it instead via a per-agent CRUSH_GLOBAL_CONFIG
+ // whose chosen provider's base_url points at the loopback proxy
+ // (installCrushConfig — sibling of installCodexHooks). `upstream`
+ // (captured above from the inert sentinel env or cloud default) is the
+ // proxy's real target. Per-agent CRUSH_GLOBAL_DATA isolates session
+ // state from the user's global ~/.config/crush.
+ const crush = this.installCrushConfig(dir, loopback, desc.api);
+ env.CRUSH_GLOBAL_CONFIG = crush.config;
+ env.CRUSH_GLOBAL_DATA = crush.data;
+ } else {
+ env[desc.baseUrlEnv] = loopback;
+ }
+ }
+ else console.error(`[hive] proxy bridge for ${meta.id} did not bind — spawning without hive events`);
+ }
+ } catch (e) { console.error(`[hive] install ${desc.kind} bridge failed:`, e); }
}
- // Inject protocol text only through a form the CLI explicitly supports.
- // Kimi/custom have neither an interactive prompt flag nor positional prompt
- // support, so they spawn bare instead of receiving an invalid argument.
+ // Inject the protocol text whichever way the CLI accepts it.
+ // type-into-tui (Crush): the bare TUI reads a positional as a Cobra subcommand
+ // → `Unknown command`. So DROP the positional and hand the protocol back as
+ // seedPrompt; the renderer types it into the TUI after boot (ondev-b).
+ if (preset.seedDelivery === 'type-into-tui') return { args: [...preArgs], env, seedPrompt: prompt };
+ // If a provider somehow exposes neither a flag nor a positional prompt, spawn bare.
if (flag) return { args: [...preArgs, flag, prompt], env };
- // Positional initial prompt (codex). Append as a trailing argv element.
- return { args: [...preArgs, prompt], env };
+ if (preset.positionalInitialPrompt) return { args: [...preArgs, prompt], env };
+ return { args: preArgs, env };
}
// Stage 7A — first-party Claude Code telemetry → the embedded loopback OTLP
@@@ -1403,94 -936,48 +1413,136 @@@
return home;
}
+ /** Pi (earendil-works) bridge. Pi has a rich `pi.on(event, …)` lifecycle but no
+ * Claude-shaped hook file; instead we drop a bundled EXTENSION into a PER-AGENT
+ * PI_CODING_AGENT_DIR (so the user's global ~/.pi is never mutated) that, when Pi
+ * loads it, posts cth-hook-shaped payloads to HIVE_SOCK on tool_call/agent_end and
+ * auto-approves tool calls when the floor is in auto mode (HIVE_AUTO_APPROVE).
+ * Emitting an `agent_end`→`Stop` keeps the harness status in step (→ idle), which
+ * lets the renderer idle inbox-wake nudge deliver mail. Returns the per-agent dir
+ * for PI_CODING_AGENT_DIR.
+ *
+ * LIVE-UNVERIFIED: Pi's exact extension-discovery path + event API need BYOK keys
+ * to confirm; this is written best-effort and wrapped so a wrong guess can never
+ * break the spawn. The renderer nudge is the guaranteed drain regardless. */
+ private installPiHooks(dir: string): string {
+ const home = join(dir, '.pi-agent');
+ try {
+ // Pi discovers extensions under its agent dir; we write to the documented
+ // `extensions/` location (and keep it isolated per agent).
+ const extDir = join(home, 'extensions');
+ mkdirSync(extDir, { recursive: true });
+ writeFileSync(join(extDir, 'hive-bridge.js'), PI_EXTENSION, 'utf8');
+ // A manifest so Pi auto-loads the extension on start (best-effort; harmless if
+ // Pi ignores it). Kept minimal and hive-authored.
+ const manifest = { name: 'munder-hive-bridge', version: '0.3.1', main: 'extensions/hive-bridge.js', auto: true };
+ writeFileSync(join(home, 'extensions.json'), JSON.stringify(manifest, null, 2), 'utf8');
+ } catch (e) { console.error('[hive] installPiHooks failed:', e); }
+ return home;
+ }
+
+ /** OpenCode (anomalyco/opencode) bridge — god Decision 1 (native plugin, not proxy).
+ * OpenCode has no Claude-shaped Stop hook, but its plugin API exposes a real
+ * `session.idle` lifecycle event. We drop a bundled PLUGIN into a PER-AGENT config
+ * dir's `plugin/` folder (OpenCode auto-loads `*.js` plugins from there) that posts
+ * HIVE_SOCK payloads on tool.execute.before/after + session.idle — the same
+ * Stop→drain semantics as codex's hooks, provider-agnostic, no traffic interception.
+ * Returns the config dir for OPENCODE_CONFIG_DIR (isolates from ~/.config/opencode).
+ *
+ * LIVE-UNVERIFIED: plugin auto-load + session.idle firing + the inject path need
+ * BYOK keys to confirm; written best-effort, wrapped so it can't break the spawn.
+ * The renderer idle inbox-wake nudge is the guaranteed drain fallback. */
+ private installOpenCodePlugin(dir: string): string {
+ const home = join(dir, '.opencode');
+ try {
+ const pluginDir = join(home, 'plugin');
+ mkdirSync(pluginDir, { recursive: true });
+ writeFileSync(join(pluginDir, 'hive-bridge.js'), OPENCODE_PLUGIN, 'utf8');
+ } catch (e) { console.error('[hive] installOpenCodePlugin failed:', e); }
+ return home;
+ }
+
+ /** Crush (charmbracelet/crush) proxy routing. Crush has NO base-URL env override, so
+ * the generic proxy env-rewrite is a no-op for it; instead we write a per-agent
+ * CRUSH_GLOBAL_CONFIG whose standard providers' `base_url` all point at the loopback
+ * proxy (so whatever model the worker picks, its LLM traffic routes through the
+ * sidecar → synthesized Status/Stop/cost → status goes idle → the terminal
+ * work-order + renderer nudge deliver mail). A per-agent CRUSH_GLOBAL_DATA isolates
+ * session state from the user's global ~/.config/crush. Keys ride BYOK env vars
+ * (Crush reads ANTHROPIC_API_KEY/OPENAI_API_KEY/… directly), so none are written
+ * here. `api` follows the proxy's wire shape (advisory). Returns the config + data
+ * paths for the spawn env.
+ *
+ * LIVE-UNVERIFIED: the single-upstream proxy serves one provider/endpoint shape at a
+ * time — for full synthesized events pick a model whose provider matches the
+ * configured upstream (or a local OpenAI-compatible endpoint). Cross-provider mixing
+ * is humanQA; the renderer nudge still delivers mail regardless. */
+ private installCrushConfig(dir: string, loopbackUrl: string, api: 'openai' | 'anthropic'): { config: string; data: string } {
+ const config = join(dir, 'crush.json');
+ const data = join(dir, '.crush-data');
+ try {
+ mkdirSync(data, { recursive: true });
+ // Override base_url → loopback for ONLY the provider whose wire-shape matches
+ // the proxy (`api`): the single-upstream sidecar forwards bytes unchanged, so
+ // routing a different-wire/host provider (e.g. anthropic when api='openai', or
+ // openrouter/groq which are openai-wire but different hosts) through it would
+ // hit the wrong endpoint and the call would fail. Those are left to their real
+ // upstreams (working calls, un-proxied — no synthesized events, but mail still
+ // drains via the renderer nudge + the pty-quiescence idle fallback). For the
+ // default god (openai-wire) and a local OpenAI-compatible endpoint this routes
+ // through the proxy cleanly. Cross-provider Crush-via-proxy is on-device
+ // live-verify (Dwight verify-crush MF1; the default god model is openai-wire to
+ // match). Literal loopback (Dwight's b1 — no ${VAR} expansion edge cases);
+ // Crush merges config so only base_url is rewritten.
+ const wireProvider = api === 'anthropic' ? 'anthropic' : 'openai';
+ const providers: Record<string, { base_url: string }> = { [wireProvider]: { base_url: loopbackUrl } };
+ writeFileSync(config, JSON.stringify({ providers }, null, 2), 'utf8');
+ } catch (e) { console.error('[hive] installCrushConfig failed:', e); }
+ return { config, data };
+ }
+
+ /** Grok lifecycle-hook bridge → live hive status, session capture, guarded
+ * inbox delivery, and operator gates for `grok` workers.
+ *
+ * Grok supports the same hook events and decision vocabulary as Claude Code,
+ * but its stdin payload uses camelCase keys. A small adapter normalizes those
+ * keys to HookServer's Claude-shaped contract. The hook is installed in the
+ * user's global Grok hook directory because global hooks are trusted and
+ * Grok sessions/resume stay in the user's normal GROK_HOME. The adapter is
+ * strictly scoped by AGENT_ID, so ordinary Grok sessions exit without doing
+ * anything. Best-effort and idempotent. */
+ private installGrokHooks(): void {
+ const root = this.root();
+ if (!root) return;
+ try {
+ const shim = join(root, 'bin', 'grok-hook.cjs');
+ mkdirSync(join(root, 'bin'), { recursive: true });
+ writeFileSync(shim, GROK_HOOK_SHIM, 'utf8');
+ const tool = (matcher?: string) => ({
+ ...(matcher ? { matcher } : {}),
+ // Let Grok apply its event-aware defaults (5s normally, 600s for Stop).
+ hooks: [{ type: 'command', command: `node ${shim}` }]
+ });
+ const hooks = {
+ PreToolUse: [tool('.*')],
+ PostToolUse: [tool('.*')],
+ Stop: [tool()],
+ SubagentStop: [tool('.*')],
+ SessionStart: [tool('.*')],
+ UserPromptSubmit: [tool()],
+ PreCompact: [tool('.*')],
+ PostCompact: [tool('.*')]
+ };
+ const hookDir = join(homedir(), '.grok', 'hooks');
+ mkdirSync(hookDir, { recursive: true });
+ writeFileSync(
+ join(hookDir, 'munder-hive.json'),
+ JSON.stringify({ hooks }, null, 2),
+ 'utf8'
+ );
+ } catch (e) { console.error('[hive] installGrokHooks failed:', e); }
+ }
+
/** Write the live fleet snapshot Michael reads (`fleet.json`, gitignored).
* Best-effort — called from a timer, must never throw. */
writeFleetSnapshot(snapshot: unknown): void {
@@@ -1830,301 -1317,76 +1882,375 @@@ process.stdin.on('end', () =>
});
`;
+// ─── pi bridge extension (written to <agentDir>/.pi-agent/extensions/) ───────
+// A bundled extension for Pi (earendil-works). Pi exposes a pi.on(event,…)
+// lifecycle; this posts cth-hook-shaped payloads to HIVE_SOCK on tool_call /
+// tool_result / agent_end and AUTO-APPROVES tool calls when the floor is in auto
+// mode (HIVE_AUTO_APPROVE, gated by config.autoMode — Pam guardrail #5). The
+// agent_end→Stop keeps the harness status in step (→ idle) so the renderer idle
+// inbox-wake nudge can deliver mail. Fully wrapped so a wrong API guess can never
+// break the spawn. LIVE-UNVERIFIED (Pi's exact extension surface needs BYOK keys).
+const PI_EXTENSION = `'use strict';
+var net = require('node:net');
+var SOCK = process.env.HIVE_SOCK;
+var AGENT = process.env.AGENT_ID || null;
+var AUTO = process.env.HIVE_AUTO_APPROVE === '1';
+function post(payload) {
+ try {
+ if (!SOCK) return;
+ payload.agent_id = payload.agent_id || AGENT;
+ var c = net.createConnection(SOCK, function () { try { c.end(JSON.stringify(payload) + '\\n'); } catch (e) {} });
+ c.on('error', function () {});
+ } catch (e) {}
+}
+function register(pi) {
+ if (!pi || typeof pi.on !== 'function') return false;
+ try {
+ pi.on('tool_call', function (ev) {
+ post({ hook_event_name: 'PreToolUse', tool_name: ev && (ev.name || (ev.tool && ev.tool.name)), tool_input: ev && (ev.args || ev.input) });
+ if (AUTO) { try { if (ev && typeof ev.approve === 'function') ev.approve(); } catch (e) {} return { approve: true }; }
+ return undefined;
+ });
+ pi.on('tool_result', function (ev) { post({ hook_event_name: 'PostToolUse', tool_name: ev && (ev.name || (ev.tool && ev.tool.name)) }); });
+ pi.on('agent_end', function () { post({ hook_event_name: 'Stop' }); });
+ return true;
+ } catch (e) { return false; }
+}
+try { if (typeof globalThis !== 'undefined' && globalThis.pi) register(globalThis.pi); } catch (e) {}
+module.exports = function (pi) { return register(pi); };
+module.exports.activate = function (pi) { return register(pi); };
+module.exports.default = module.exports;
+`;
+
+// ─── opencode bridge plugin (written to <agentDir>/.opencode/plugin/) ────────
+// A bundled plugin for OpenCode (anomalyco/opencode) — god Decision 1. OpenCode
+// has no Claude-shaped Stop hook but its plugin API exposes a real session.idle
+// event; this posts cth-hook-shaped payloads to HIVE_SOCK on tool.execute.before/
+// after + session.idle. The session.idle→Stop keeps status in step (→ idle) so the
+// renderer idle inbox-wake nudge delivers mail. ESM (OpenCode runs on Bun). Fully
+// wrapped. LIVE-UNVERIFIED (plugin auto-load + session.idle firing need BYOK keys).
+const OPENCODE_PLUGIN = `import { createConnection } from 'node:net';
+const SOCK = process.env.HIVE_SOCK;
+const AGENT = process.env.AGENT_ID || null;
+function post(payload) {
+ try {
+ if (!SOCK) return;
+ payload.agent_id = payload.agent_id || AGENT;
+ const c = createConnection(SOCK, () => { try { c.end(JSON.stringify(payload) + '\\n'); } catch (e) {} });
+ c.on('error', () => {});
+ } catch (e) {}
+}
+export const HiveBridge = async () => {
+ return {
+ event: async (input) => {
+ try { if (input && input.event && input.event.type === 'session.idle') post({ hook_event_name: 'Stop' }); } catch (e) {}
+ },
+ 'tool.execute.before': async (input) => {
+ try { post({ hook_event_name: 'PreToolUse', tool_name: input && (input.tool || input.name) }); } catch (e) {}
+ },
+ 'tool.execute.after': async (input) => {
+ try { post({ hook_event_name: 'PostToolUse', tool_name: input && (input.tool || input.name) }); } catch (e) {}
+ }
+ };
+};
+export default HiveBridge;
+`;
+
+// ─── proxy-bridge sidecar (written to <hive>/bin/hive-proxy.cjs) ─────────────
+// One per proxy-tier agent (qwen). A dependency-free, loopback-only reverse
+// proxy: the agent's CLI is pointed at this (via ANTHROPIC_BASE_URL/OPENAI_BASE_URL),
+// and it forwards every request to the user's real upstream UNCHANGED (headers,
+// body, streaming). It TEES each response to synthesize the same HIVE_SOCK payloads
+// the hook shims emit — Status (context gauge), PostToolUse (breaker), Stop (idle
+// drain), and the new CostSample (cost ledger) — so a hookless CLI becomes a hive
+// citizen. NEVER logs bodies or keys; the captured body is parsed in-memory and
+// dropped. Idle is heuristic: a turn that ends with no tool call and no new request
+// within an ~800ms debounce → Stop (a new request cancels it).
+const PROXY_BRIDGE_SHIM = `#!/usr/bin/env node
+'use strict';
+const http = require('http');
+const https = require('https');
+const net = require('net');
+const { URL } = require('url');
+
+const SOCK = process.env.HIVE_SOCK;
+const AGENT_ID = process.env.AGENT_ID || null;
+const UPSTREAM = process.env.UPSTREAM_BASE_URL || '';
+const SESSION = process.env.HIVE_PROXY_SESSION || null;
+const API = process.env.HIVE_PROXY_API === 'anthropic' ? 'anthropic' : 'openai';
+
+function trimSlash(s) { while (s.length && s.charAt(s.length - 1) === '/') s = s.slice(0, -1); return s; }
+
+// Per-model context-window size for the Status gauge; fallback 200k.
+function ctxSize(model) {
+ const m = String(model || '').toLowerCase();
+ if (m.indexOf('[1m]') !== -1 || m.indexOf('-1m') !== -1) return 1000000;
+ if (m.indexOf('claude') !== -1) return 200000;
+ if (m.indexOf('gpt-4o') !== -1 || m.indexOf('gpt-4.1') !== -1 || m.indexOf('o1') !== -1 || m.indexOf('o3') !== -1) return 128000;
+ if (m.indexOf('qwen') !== -1) return 262144;
+ return 200000;
+}
+
+// Fire-and-forget emit of a shim-shaped payload to the hive socket. Never throws.
+function emit(payload) {
+ if (!SOCK) return;
+ try {
+ const c = net.createConnection(SOCK, function () { c.end(JSON.stringify(payload) + '\\n'); });
+ c.on('error', function () {});
+ } catch (e) {}
+}
+
+let stopTimer = null;
+function armStop() {
+ if (stopTimer) clearTimeout(stopTimer);
+ stopTimer = setTimeout(function () {
+ stopTimer = null;
+ emit({ hook_event_name: 'Stop', agent_id: AGENT_ID, session_id: SESSION });
+ }, 800);
+ if (stopTimer.unref) stopTimer.unref();
+}
+function cancelStop() { if (stopTimer) { clearTimeout(stopTimer); stopTimer = null; } }
+
+function safeArgs(s) {
+ if (s == null) return {};
+ if (typeof s === 'object') return s;
+ try { return JSON.parse(s); } catch (e) { return { _raw: String(s).slice(0, 500) }; }
+}
+
+// Parse a completed response (single JSON or an SSE stream) and synthesize events.
+function parseAndEmit(bodyStr, isSse) {
+ const objs = [];
+ if (isSse) {
+ const lines = bodyStr.split('\\n');
+ for (let i = 0; i < lines.length; i++) {
+ const ln = lines[i];
+ const idx = ln.indexOf('data:');
+ if (idx === -1) continue;
+ const data = ln.slice(idx + 5).trim();
+ if (!data || data === '[DONE]') continue;
+ try { objs.push(JSON.parse(data)); } catch (e) {}
+ }
+ } else {
+ try { objs.push(JSON.parse(bodyStr)); } catch (e) {}
+ }
+ if (!objs.length) { armStop(); return; }
+
+ let model = null, input = 0, output = 0, cacheRead = 0, cacheCreation = 0, sawUsage = false;
+ const toolCalls = [];
+ const oaiTools = {}; // accumulate streaming openai tool_calls by index
+
+ for (let i = 0; i < objs.length; i++) {
+ const o = objs[i];
+ if (!o || typeof o !== 'object') continue;
+ if (o.model) model = o.model;
+ if (API === 'anthropic') {
+ if (o.type === 'message_start' && o.message) {
+ if (o.message.model) model = o.message.model;
+ const u = o.message.usage || {};
+ input += u.input_tokens || 0;
+ cacheRead += u.cache_read_input_tokens || 0;
+ cacheCreation += u.cache_creation_input_tokens || 0;
+ sawUsage = true;
+ } else if (o.type === 'message_delta' && o.usage) {
+ output += o.usage.output_tokens || 0;
+ sawUsage = true;
+ } else if (o.type === 'content_block_start' && o.content_block && o.content_block.type === 'tool_use') {
+ toolCalls.push({ name: o.content_block.name, input: o.content_block.input || {} });
+ } else if (o.usage && !o.type) {
+ // non-streaming full message body
+ const u = o.usage;
+ input += u.input_tokens || 0;
+ output += u.output_tokens || 0;
+ cacheRead += u.cache_read_input_tokens || 0;
+ cacheCreation += u.cache_creation_input_tokens || 0;
+ sawUsage = true;
+ }
+ if (Array.isArray(o.content)) {
+ for (let j = 0; j < o.content.length; j++) {
+ const blk = o.content[j];
+ if (blk && blk.type === 'tool_use') toolCalls.push({ name: blk.name, input: blk.input || {} });
+ }
+ }
+ } else {
+ if (o.usage) {
+ const u = o.usage;
+ input += u.prompt_tokens || 0;
+ output += u.completion_tokens || 0;
+ if (u.prompt_tokens_details && u.prompt_tokens_details.cached_tokens) cacheRead += u.prompt_tokens_details.cached_tokens;
+ sawUsage = true;
+ }
+ const choices = o.choices || [];
+ for (let c = 0; c < choices.length; c++) {
+ const ch = choices[c];
+ if (!ch) continue;
+ if (ch.message && Array.isArray(ch.message.tool_calls)) {
+ for (let t = 0; t < ch.message.tool_calls.length; t++) {
+ const tc = ch.message.tool_calls[t];
+ if (tc && tc.function) toolCalls.push({ name: tc.function.name, input: safeArgs(tc.function.arguments) });
+ }
+ }
+ if (ch.delta && Array.isArray(ch.delta.tool_calls)) {
+ for (let t = 0; t < ch.delta.tool_calls.length; t++) {
+ const tc = ch.delta.tool_calls[t];
+ if (!tc) continue;
+ const k = (tc.index != null ? tc.index : t);
+ if (!oaiTools[k]) oaiTools[k] = { name: null, args: '' };
+ if (tc.function) {
+ if (tc.function.name) oaiTools[k].name = tc.function.name;
+ if (tc.function.arguments) oaiTools[k].args += tc.function.arguments;
+ }
+ }
+ }
+ }
+ }
+ }
+ const keys = Object.keys(oaiTools);
+ for (let i = 0; i < keys.length; i++) {
+ const t = oaiTools[keys[i]];
+ if (t.name) toolCalls.push({ name: t.name, input: safeArgs(t.args) });
+ }
+
+ if (sawUsage) {
+ emit({ hook_event_name: 'Status', agent_id: AGENT_ID, context_window: { total_input_tokens: input + cacheRead + cacheCreation, context_window_size: ctxSize(model) } });
+ emit({ hook_event_name: 'CostSample', agent_id: AGENT_ID, session_id: SESSION, model: model, input: input, output: output, cache_read: cacheRead, cache_creation: cacheCreation });
+ }
+ if (toolCalls.length) {
+ cancelStop(); // a tool call means the turn continues
+ for (let i = 0; i < toolCalls.length; i++) {
+ emit({ hook_event_name: 'PostToolUse', agent_id: AGENT_ID, session_id: SESSION, tool_name: toolCalls[i].name, tool_input: toolCalls[i].input });
+ }
+ } else {
+ armStop();
+ }
+}
+
+let upstreamUrl = null;
+try { upstreamUrl = new URL(UPSTREAM); } catch (e) {}
+
+const server = http.createServer(function (req, res) {
+ cancelStop(); // a new request means the turn is still going
+ if (!upstreamUrl) { res.statusCode = 502; res.end('proxy: no upstream'); return; }
+ let target;
+ try { target = new URL(trimSlash(UPSTREAM) + req.url); } catch (e) { res.statusCode = 502; res.end('proxy: bad url'); return; }
+ const isHttps = target.protocol === 'https:';
+ const lib = isHttps ? https : http;
+ const headers = Object.assign({}, req.headers);
+ headers.host = target.host;
+ // Ask upstream for plaintext so the tee can parse SSE/JSON reliably; the client
+ // gets uncompressed bytes (loopback — negligible) and no content-encoding to undo.
+ delete headers['accept-encoding'];
+ const opts = {
+ protocol: target.protocol,
+ hostname: target.hostname,
+ port: target.port || (isHttps ? 443 : 80),
+ method: req.method,
+ path: target.pathname + target.search,
+ headers: headers
+ };
+ const upReq = lib.request(opts, function (upRes) {
+ res.writeHead(upRes.statusCode || 502, upRes.headers);
+ const ct = String((upRes.headers['content-type'] || ''));
+ const wantParse = ct.indexOf('json') !== -1 || ct.indexOf('event-stream') !== -1;
+ const isSse = ct.indexOf('event-stream') !== -1;
+ const chunks = [];
+ let total = 0;
+ upRes.on('data', function (chunk) {
+ res.write(chunk); // stream straight through to the CLI
+ if (wantParse && total < 4194304) { chunks.push(chunk); total += chunk.length; }
+ });
+ upRes.on('end', function () {
+ res.end();
+ if (wantParse && chunks.length) {
+ try { parseAndEmit(Buffer.concat(chunks).toString('utf8'), isSse); } catch (e) {}
+ }
+ });
+ upRes.on('error', function () { try { res.end(); } catch (e) {} });
+ });
+ upReq.on('error', function () { try { res.statusCode = 502; res.end('proxy: upstream error'); } catch (e) {} });
+ req.pipe(upReq);
+});
+
+server.on('error', function () {
+ try { process.stdout.write(JSON.stringify({ port: 0 }) + '\\n'); } catch (e) {}
+ process.exit(0);
+});
+server.listen(0, '127.0.0.1', function () {
+ const addr = server.address();
+ const port = (addr && typeof addr === 'object') ? addr.port : 0;
+ try { process.stdout.write(JSON.stringify({ port: port }) + '\\n'); } catch (e) {}
+});
+`;
++
+ // ─── grok-hook shim (written to <hive>/bin/grok-hook.cjs) ───────────────────
+ // Grok's lifecycle events and decisions are Claude-compatible, but the wire
+ // payload is camelCase and uses snake_case event values. Normalize the input for
+ // HookServer and translate its Claude-style permission denial into Grok's direct
+ // decision form. Scoped by AGENT_ID so the trusted global hook is inert outside
+ // Munder-spawned workers.
+ const GROK_HOOK_SHIM = `#!/usr/bin/env node
+ 'use strict';
+ const net = require('net');
+ const agentId = process.env.AGENT_ID || null;
+ let data = '';
+ process.stdin.setEncoding('utf8');
+ process.stdin.on('data', (d) => { data += d; });
+ process.stdin.on('end', () => {
+ const sock = process.env.HIVE_SOCK;
+ if (!agentId || !sock) { process.exit(0); }
+ let grok = {};
+ try { grok = JSON.parse(data || '{}'); } catch (_) {}
+ const names = {
+ pre_tool_use: 'PreToolUse',
+ post_tool_use: 'PostToolUse',
+ post_tool_use_failure: 'PostToolUseFailure',
+ permission_denied: 'PermissionDenied',
+ stop: 'Stop',
+ stop_failure: 'StopFailure',
+ session_start: 'SessionStart',
+ session_end: 'SessionEnd',
+ user_prompt_submit: 'UserPromptSubmit',
+ notification: 'Notification',
+ subagent_start: 'SubagentStart',
+ subagent_stop: 'SubagentStop',
+ pre_compact: 'PreCompact',
+ post_compact: 'PostCompact'
+ };
+ const payload = {
+ hook_event_name: names[grok.hookEventName] || grok.hookEventName || 'Unknown',
+ agent_id: agentId,
+ session_id: grok.sessionId,
+ cwd: grok.cwd || grok.workspaceRoot,
+ tool_name: grok.toolName,
+ tool_input: grok.toolInput,
+ stop_hook_active: grok.stopHookActive,
+ prompt: grok.prompt,
+ source: grok.source,
+ notification_type: grok.notificationType,
+ message: grok.message
+ };
+ let resp = '';
+ const done = () => {
+ let out = null;
+ try {
+ const r = JSON.parse(resp || '{}');
+ if (r.continue === false) out = { continue: false, stopReason: r.stopReason };
+ else if (r.decision === 'block') out = { decision: 'block', reason: r.reason };
+ else if (r.hookSpecificOutput && r.hookSpecificOutput.permissionDecision === 'deny') {
+ out = { decision: 'deny', reason: r.hookSpecificOutput.permissionDecisionReason };
+ } else if (r.hookSpecificOutput && r.hookSpecificOutput.additionalContext) {
+ out = r;
+ }
+ } catch (_) {}
+ if (out) { try { process.stdout.write(JSON.stringify(out)); } catch (_) {} }
+ process.exit(0);
+ };
+ try {
+ const c = net.createConnection(sock, () => c.write(JSON.stringify(payload) + '\\n'));
+ c.setEncoding('utf8');
+ c.on('data', (d) => { resp += d; });
+ c.on('end', done);
+ c.on('error', () => process.exit(0));
+ setTimeout(() => process.exit(0), 5000).unref();
+ } catch (_) { process.exit(0); }
+ });
+ `;
diff --cc src/main/hooks.ts
index 3f4658ea,311a452f..ef1b5a63
--- a/src/main/hooks.ts
+++ b/src/main/hooks.ts
@@@ -200,28 -139,13 +199,22 @@@ export class HookServer
this.breaker?.recordToolUse(agentId, p.tool_name, p.tool_input);
}
+ // Compaction exemption (issue #109): PreCompact opens it so the compaction
+ // token burst can't trip the Δoutput arms; PostCompact — or any SessionStart,
+ // since a fresh session makes in-flight compaction state moot — closes it
+ // down to the trailing grace (a no-op when nothing was compacting).
+ if (event === 'PreCompact' && agentId) this.breaker?.recordCompactStart(agentId);
+ if ((event === 'PostCompact' || event === 'SessionStart') && agentId) {
+ this.breaker?.recordCompactEnd(agentId);
+ }
+
if ((event === 'Stop' || event === 'SubagentStop') && agentId) {
- // Loop guard: a previous Stop hook already blocked this turn → let it stop.
+ // Respect any upstream Stop hook that already re-entered this boundary.
if (p.stop_hook_active) { this.emit(agentId, event, p); return {}; }
- const drain = this.hive.drainForStop(agentId);
- if (drain.block) {
- // The agent is NOT idle — we're forcing it to keep working to process
- // its inbox. Tell the renderer that (blocked: true) so it doesn't flash
- // 'idle' on a Stop that never actually stops. Without this, an agent
- // re-engaged by a queued/dispatched message reads as idle while working.
- this.emit(agentId, event, p, true);
- return { decision: 'block', reason: drain.reason };
- }
- // A genuine stop with nothing queued → idle. Surface it as a desktop toast.
+ // Never turn unread hive mail into a forced continuation at Stop. That old
+ // path bypassed terminal-draft/HITL safety and could spend credits while a
+ // user was answering a question. Inbox files remain durable; the renderer
+ // wakes the agent later through its guarded idle-only delivery path.
this.notify(agentId ?? 'Agent', 'finished — idle');
this.emit(agentId, event, p);
return {};
diff --cc src/main/index.ts
index 253f4a03,eba0fbc4..d1d71f12
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@@ -1,18 -1,23 +1,23 @@@
-import { app, BrowserWindow, clipboard, dialog, ipcMain, Menu, powerSaveBlocker, screen, shell, Notification } from 'electron';
+import { app, BrowserWindow, clipboard, dialog, ipcMain, Menu, powerMonitor, powerSaveBlocker, screen, shell, Notification } from 'electron';
import { spawn } from 'node:child_process';
- import { rmSync, existsSync, readFileSync, readdirSync, statSync, cpSync, writeFileSync, unlinkSync, mkdirSync, renameSync, createWriteStream } from 'node:fs';
+ import {
+ rmSync, existsSync, readFileSync, readdirSync, statSync, cpSync, writeFileSync,
- unlinkSync, mkdirSync, createWriteStream, copyFileSync, lstatSync, readlinkSync,
- symlinkSync
++ unlinkSync, mkdirSync, renameSync, createWriteStream, copyFileSync, lstatSync,
++ readlinkSync, symlinkSync
+ } from 'node:fs';
import { randomBytes, createHash, timingSafeEqual } from 'node:crypto';
- import { join, resolve, sep, basename } from 'node:path';
+ import { join, resolve, sep, basename, dirname } from 'node:path';
import { request as httpsRequest } from 'node:https';
import { PtyManager, type SpawnOptions } from './pty';
-import { enableOpsStandupAutoCompact } from '../shared/autoCompact';
++import { resolveCommand as resolveCliCommand } from './shellEnv';
import {
readConfig, writeConfig, resetConfig, ensureHarnessHome, ensureClaudePermissionsAccepted,
- modelForRole, OPS_STANDUP_MISSION, HEARTBEAT_MISSION, type HarnessConfig, type ScheduledMission
+ modelForRole, OPS_STANDUP_MISSION, HEARTBEAT_MISSION, COMPACT_MAINTENANCE_MISSION, type HarnessConfig, type ScheduledMission
} from './config';
import { listDir, readFileText, writeFileText } from './fs';
import {
- getBranch, getStatus, getLog, getBranches, getAheadBehind, isRepo, getDiff,
- getBranch, getStatus, getLog, getBranches, getAheadBehind, isRepo, mainRepoRoot,
- addWorktree, removeWorktree
++ getBranch, getStatus, getLog, getBranches, getAheadBehind, isRepo, getDiff, mainRepoRoot,
+ addWorktree, removeWorktree, worktreeHasUnintegratedWork, worktreeIsGcSafe
} from './git';
import { HiveManager, type AgentMeta, type HiveMessage, type HiveTask } from './hive';
import { HookServer } from './hooks';
@@@ -27,27 -32,24 +32,35 @@@ import { listIssues, listCIRuns } from
import { SlackWebhookServer, SlackReplyServer, postSlackReply, type SlackEventFile } from './slack';
import { WebhookServer, type WebhookInbound, type WebhookTaskStatus } from './webhook';
import { transcribeWithGroq, DEFAULT_GROQ_MODEL } from './freeflow';
+import { registerRealtimeIpc } from './realtime';
+import { registerRealtimeActionIpc } from './realtimeActions';
+import { initCompletionWatcher } from './realtimeCompletionWatcher';
+import type { TaskCard, InboxMessage } from './realtimeCompletionWatcher';
import { TelemetryCollector } from './telemetry';
+import { IntegrationBroker } from './integrationBroker';
+import * as integrations from './integrations';
+import { validateBaseUrl, buildAuthHeaders, resolveUpstreamUrl, secretRefFor, INTEGRATION_TEMPLATES } from '../shared/integrations';
+ import { RosterStore } from './roster';
import { ControlRegistry } from './control';
+import { fetchHireManifest, readHireManifestFile } from './hire';
+import { parseHireDeepLink, type HireManifest } from '../shared/hire';
import { ClosingTimeController } from './closingTime';
import {
inferAgentProvider,
isClaudeProvider,
nonInteractiveEnvForProvider,
providerPreset,
- type AgentProvider
+ installInfoForProvider,
+ type AgentProvider,
+ type ProviderInstallInfo
} from '../shared/agentProvider';
+ import {
+ CODEX_REMOTE_SOCKET_RELATIVE,
+ codexRemoteAliasPath,
+ codexRemoteEndpoint,
+ codexRemoteSocketFits,
+ withCodexRemoteArgs
+ } from '../shared/codexRemote';
const isDev = !!process.env.ELECTRON_RENDERER_URL;
@@@ -65,6 -66,119 +78,121 @@@ process.on('unhandledRejection', (reaso
});
const ptyManager = new PtyManager();
+
+ function runCodexDaemonCommand(
+ executable: string,
+ args: string[],
+ env: NodeJS.ProcessEnv,
+ timeoutMs = 20_000
+ ): Promise<{ ok: boolean; error?: string }> {
+ return new Promise((resolveResult) => {
+ let settled = false;
+ let stderr = '';
+ let child: ReturnType<typeof spawn>;
+ try {
+ child = spawn(executable, args, {
+ env,
+ stdio: ['ignore', 'ignore', 'pipe'],
+ windowsHide: true
+ });
+ } catch (e) {
+ resolveResult({ ok: false, error: e instanceof Error ? e.message : String(e) });
+ return;
+ }
+ let timer: NodeJS.Timeout;
+ const finish = (result: { ok: boolean; error?: string }): void => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ resolveResult(result);
+ };
+ child.stderr?.on('data', (chunk) => {
+ if (stderr.length < 8_000) stderr += String(chunk);
+ });
+ child.once('error', (e) => finish({ ok: false, error: e.message }));
+ child.once('exit', (code) => {
+ finish(code === 0
+ ? { ok: true }
+ : { ok: false, error: stderr.trim() || `Codex exited with code ${code ?? 'unknown'}` });
+ });
+ timer = setTimeout(() => {
+ try { child.kill(); } catch { /* already exited */ }
+ finish({ ok: false, error: `Codex daemon command timed out after ${timeoutMs}ms` });
+ }, timeoutMs);
+ });
+ }
+
+ /** Start/enable one managed remote-control daemon for this isolated Codex home,
+ * then point the TUI at its app-server socket. Failure is non-fatal: the worker
+ * still starts as a normal local Codex session. */
+ async function enableCodexRemoteForSpawn(
+ opts: SpawnOptions & { hive?: AgentMeta },
+ agentId: string
+ ): Promise<boolean> {
+ if (process.platform === 'win32') return false;
+ const realHome = opts.env?.CODEX_HOME;
+ if (!realHome) return false;
+ try {
+ const alias = codexRemoteAliasPath(realHome, agentId);
+ // Bail before touching the filesystem if even the short alias would exceed
+ // sun_path — the daemon would start and then die on bind, and the warning
+ // below names the real reason instead of a generic readiness timeout.
+ if (!codexRemoteSocketFits(alias)) {
+ console.warn('[codex-remote] socket path exceeds sun_path; starting local TUI:', alias);
+ return false;
+ }
+ const aliasRoot = dirname(alias);
+ mkdirSync(aliasRoot, { recursive: true });
+ if (existsSync(alias)) {
+ const st = lstatSync(alias);
+ if (!st.isSymbolicLink() || resolve(dirname(alias), readlinkSync(alias)) !== resolve(realHome)) {
+ console.warn('[codex-remote] short home alias is occupied; starting local TUI:', alias);
+ return false;
+ }
+ } else {
+ symlinkSync(realHome, alias, 'dir');
+ }
+
+ const socket = join(alias, CODEX_REMOTE_SOCKET_RELATIVE);
+ const env: NodeJS.ProcessEnv = {
+ ...process.env,
+ ...(opts.env ?? {}),
+ CODEX_HOME: alias
+ };
- const executable = ptyManager.resolveCommand(opts.command);
++ // shellEnv's resolver mirrors PtyManager's (which is private + returns
++ // {path, found}); the daemon just needs the best executable path.
++ const executable = resolveCliCommand(opts.command);
+ const started = await runCodexDaemonCommand(
+ executable,
+ ['app-server', 'daemon', 'start'],
+ env
+ );
+ if (!started.ok) {
+ console.warn('[codex-remote] daemon start failed; starting local TUI:', started.error);
+ return false;
+ }
+ const enabled = await runCodexDaemonCommand(
+ executable,
+ ['app-server', 'daemon', 'enable-remote-control'],
+ env
+ );
+ if (!enabled.ok) {
+ console.warn('[codex-remote] enable failed; starting local TUI:', enabled.error);
+ return false;
+ }
+ if (!existsSync(socket)) {
+ console.warn('[codex-remote] daemon returned without a control socket; starting local TUI');
+ return false;
+ }
+ opts.env = { ...(opts.env ?? {}), CODEX_HOME: alias };
+ opts.args = withCodexRemoteArgs(opts.args ?? [], codexRemoteEndpoint(alias));
+ return true;
+ } catch (e) {
+ console.warn('[codex-remote] setup failed; starting local TUI:',
+ e instanceof Error ? e.message : e);
+ return false;
+ }
+ }
/** 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>();
@@@ -1715,114 -1482,79 +1843,173 @@@ function installAppMenu(): void
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
}
+/** Build the shell script the missing-CLI auto-install path runs IN PLACE of a
+ * missing engine CLI. When the provider has a known installer it prints a banner
+ * then RUNS the install visibly (so the user can watch + finish any sign-in);
+ * otherwise it prints a manual instruction only and runs nothing. The script is
+ * emitted in the current platform shell's syntax ($SHELL on unix, cmd.exe on
+ * Windows). The only user-derived value (the missing binary name) is sanitized to
+ * a safe identifier; the install command itself is a trusted hardcoded constant. */
+function buildMissingCliScript(bin: string, provider: AgentProvider): string {
+ const info: ProviderInstallInfo = installInfoForProvider(provider);
+ const safeBin = (bin || provider).replace(/[^A-Za-z0-9._-]/g, '') || provider;
+ const cmd = info.command; // trusted constant, or undefined → manual hint only
+ const label = info.label;
+ const docs = info.docsUrl;
+ const rule = '------------------------------------------------------------';
+
+ if (process.platform === 'win32') {
+ // ONE cmd.exe line: `&` chains steps, `^&` prints a literal ampersand, and the
+ // script carries NO double-quotes (it is wrapped verbatim in `/d /s /c "..."`).
+ // We avoid `if errorlevel` branching (untestable here) — a combined success/
+ // failure hint after the install is robust and satisfies the manual-fallback DoD.
+ const parts: string[] = ['echo.', `echo ${rule}`, `echo Engine CLI not found: ${safeBin}`, 'echo.'];
+ if (cmd) {
+ parts.push(
+ `echo Installing the ${label} CLI now so you can watch:`,
+ 'echo.',
+ `echo ${cmd}`,
+ `echo ${rule}`,
+ 'echo.',
+ cmd,
+ 'echo.',
+ 'echo [done] If it succeeded, the agent launches automatically.',
+ 'echo If it failed, run the command above manually, then restart the agent.'
+ );
+ } else {
+ parts.push(
+ `echo No bundled installer for the ${label} provider.`,
+ 'echo Install it manually, then restart the agent to launch it.'
+ );
+ if (docs) parts.push(`echo Docs: ${docs}`);
+ parts.push(`echo ${rule}`);
+ }
+ return parts.join(' & ');
+ }
+
+ // unix ($SHELL -lc <script>): one statement per line, single-quoted echo text so
+ // no shell metacharacter expands. We avoid `!` so any shell with history
+ // expansion never fires. npm is found via the interactive PATH spawn() injects.
+ const lines: string[] = [
+ `echo ''`,
+ `echo '${rule}'`,
+ `echo ' Engine CLI not found: ${safeBin}'`,
+ `echo ''`
+ ];
+ if (cmd) {
+ lines.push(
+ `echo ' Installing the ${label} CLI now so you can watch — finish any'`,
+ `echo ' sign-in it prompts for, then come back to this terminal.'`,
+ `echo ''`,
+ `echo ' ${cmd}'`,
+ `echo '${rule}'`,
+ `echo ''`,
+ cmd,
+ `__clirc=$?`,
+ `echo ''`,
+ `if [ $__clirc -eq 0 ]; then`,
+ ` echo ' [done] Installed — launching the agent…'`,
+ `else`,
+ ` echo " [x] Install exited with code $__clirc — finish it manually:"`,
+ ` echo ' ${cmd}'`,
+ ...(docs ? [` echo ' Docs: ${docs}'`] : []),
+ ` echo ' Then restart the agent to launch it.'`,
+ `fi`
+ );
+ } else {
+ lines.push(
+ `echo ' No bundled installer for the ${label} provider.'`,
+ `echo ' Install it manually, then restart the agent to launch it.'`,
+ ...(docs ? [`echo ' Docs: ${docs}'`] : []),
+ `echo '${rule}'`
+ );
+ }
+ return lines.join(String.fromCharCode(10));
+}
+
// ─── IPC: pty lifecycle ─────────────────────────────────────────────────────
+ /** Codex stores its rollout transcripts under a PER-AGENT CODEX_HOME
+ * (<hive>/agents/<id>/.codex/sessions/<Y>/<M>/<D>/rollout-*-<sessionId>.jsonl).
+ * A NEWLY added agent gets an empty CODEX_HOME, so `codex resume <sid>` finds
+ * nothing and silently opens a BLANK session — which is exactly what the Add
+ * Agent "resume session" field looked like it was doing. Find the agent whose
+ * CODEX_HOME owns this rollout and RETURN that home so the resumed agent can be
+ * pointed at it (the rollout AND its state_5.sqlite index live there together). */
+ function findCodexHomeForSession(sessionId: string, siblingsRoot: string): string | null {
+ try {
+ if (!sessionId || !/^[0-9a-fA-F][0-9a-fA-F-]{15,}$/.test(sessionId)) return null;
+ let fallbackHome: string | null = null;
+ // Walk each sibling agent's CODEX_HOME (<agent>/.codex) looking for the
+ // rollout that owns this session. We RETURN that home rather than copy the
+ // rollout out of it: Codex indexes sessions in its state_5.sqlite, so a lone
+ // rollout file in a fresh home is invisible to `codex resume`. Pointing the
+ // resumed agent at the OWNING home gives it the rollout AND the index.
+ let agents: Array<{ name: string; isDirectory(): boolean }>;
+ try {
+ agents = readdirSync(siblingsRoot, { withFileTypes: true }) as unknown as Array<{ name: string; isDirectory(): boolean }>;
+ } catch { return null; }
+ for (const a of agents) {
+ if (!a.isDirectory()) continue;
+ const home = join(siblingsRoot, a.name, '.codex');
+ const sessions = join(home, 'sessions');
+ if (!existsSync(sessions)) continue;
+ const stack = [sessions];
+ let hasRollout = false;
+ while (stack.length && !hasRollout) {
+ const d = stack.pop() as string;
+ let ents: Array<{ name: string; isDirectory(): boolean; isFile(): boolean }>;
+ try {
+ ents = readdirSync(d, { withFileTypes: true }) as unknown as Array<{ name: string; isDirectory(): boolean; isFile(): boolean }>;
+ } catch { continue; }
+ for (const e of ents) {
+ const pth = join(d, e.name);
+ if (e.isDirectory()) stack.push(pth);
+ else if (e.isFile() && e.name.endsWith('.jsonl') && e.name.includes(sessionId)) { hasRollout = true; break; }
+ }
+ }
+ if (!hasRollout) continue;
+ // Prefer the home whose Codex state DB actually INDEXES this session — a
+ // fresh/seeded home may carry only a stray rollout copy (no index), which
+ // `codex resume` can't open. Match the id as raw bytes in state_5.sqlite
+ // (+ its WAL). Homes with the rollout but no index are a last-resort fallback.
+ const idBuf = Buffer.from(sessionId);
+ let indexed = false;
+ for (const db of ['state_5.sqlite', 'state_5.sqlite-wal']) {
+ try { if (readFileSync(join(home, db)).includes(idBuf)) { indexed = true; break; } } catch { /* no db */ }
+ }
+ if (indexed) return home;
+ if (!fallbackHome) fallbackHome = home;
+ }
+ return fallbackHome;
+ } catch (e) {
+ console.error('[resume] findCodexHomeForSession failed:', e);
+ return null;
+ }
+ }
+
-ipcMain.handle('pty:spawn', async (evt, opts: SpawnOptions & {
- hive?: AgentMeta;
- isolate?: boolean;
- resume?: boolean;
- requireResume?: boolean;
- resumeSessionId?: string;
- provider?: AgentProvider;
-}) => {
+/** Spawn options shared by the `pty:spawn` IPC handler and the god-triggered
+ * ephemeral-worker watcher. */
- type AgentSpawnOptions = SpawnOptions & { hive?: AgentMeta; isolate?: boolean; resume?: boolean; resumeSessionId?: string; provider?: AgentProvider; noAutoInstall?: boolean };
++type AgentSpawnOptions = SpawnOptions & { hive?: AgentMeta; isolate?: boolean; resume?: boolean; requireResume?: boolean; resumeSessionId?: string; provider?: AgentProvider; noAutoInstall?: boolean };
+
+ipcMain.handle('pty:spawn', async (evt, opts: AgentSpawnOptions) => {
if (!opts || typeof opts.id !== 'string' || typeof opts.cwd !== 'string' || typeof opts.command !== 'string') {
return { ok: false, error: 'invalid SpawnOptions' };
}
+ // Record the spawning window as the PTY's owner so its output routes ONLY back
+ // to that floor, then run the shared spawn core.
+ const owner = BrowserWindow.fromWebContents(evt.sender)?.webContents ?? null;
+ return spawnAgentCore(opts, owner);
+});
+
+/** Core agent-spawn logic — provider inference, the missing-CLI installer
+ * short-circuit, git-worktree isolation, hive provisioning, model/resume flags,
+ * and the final PTY spawn. Extracted VERBATIM from the `pty:spawn` IPC handler so
+ * it can ALSO be invoked by the god-triggered ephemeral-worker watcher (which has
+ * no renderer `evt`). `owner` is the window that should receive this PTY's output
+ * (null → the primary window). Behavior-identical to the prior inline handler. */
+async function spawnAgentCore(opts: AgentSpawnOptions, owner: Electron.WebContents | null): Promise<{ ok: boolean; error?: string; worktreePath?: string; resumeNotFound?: boolean; resumed?: boolean; seedPrompt?: string }> {
// Which CLI is this? Explicit wins; else inferred from the binary
- // (claude/codex/agy). Non-Claude providers skip every Claude-only spawn step
+ // (claude/codex/grok/agy). Non-Claude providers skip every Claude-only spawn step
// below. Persist the resolved provider onto opts (+ hive meta) so the registry
// record and downstream provider-aware steps agree on one value.
const provider = inferAgentProvider(opts.command, opts.provider ?? opts.hive?.provider);
@@@ -1962,15 -1634,22 +2149,26 @@@
const cfg = readConfig();
const args = opts.args ?? [];
// Model precedence: an explicit per-agent --model (from the renderer) wins;
- // else the user's global defaultModel; else the role-based default tier.
+ // else the user's global defaultModel; else the role-based default tier. The
+ // GOD is special-cased: it has its own engine config (godProvider/godModel), so
+ // modelForRole resolves it and that wins over the worker-oriented defaultModel.
if (!args.includes('--model')) {
- const m = cfg.defaultModel ?? modelForRole(opts.hive);
+ const m = opts.hive.isGod
+ ? modelForRole(opts.hive, cfg)
+ : cfg.defaultModel ?? modelForRole(opts.hive, cfg);
if (m) args.push('--model', m);
}
+ // Name the Remote Control session after the agent (Michael, Jim, Dev1…) so it
+ // is identifiable in claude.ai / the mobile app. Otherwise Claude defaults the
+ // prefix to the machine hostname (e.g. "vyapaks-macbook-pro-…"), which is
+ // opaque when several agents run at once — especially with remoteControlAtStartup
+ // on, where RC auto-enables for every session. Slugify the friendly name into a
+ // single safe token; Claude still appends its own random suffix for uniqueness.
+ if (!args.includes('--remote-control-session-name-prefix')) {
+ const label = (opts.hive.name || opts.hive.id || '')
+ .trim().replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '');
+ if (label) args.push('--remote-control-session-name-prefix', label);
+ }
// Coarse runaway cap.
if (typeof cfg.maxTurns === 'number' && cfg.maxTurns > 0 && !args.includes('--max-turns')) {
args.push('--max-turns', String(cfg.maxTurns));
@@@ -2032,57 -1749,16 +2268,64 @@@
if (Object.keys(nonInteractiveEnv).length > 0) {
opts.env = { ...(opts.env ?? {}), ...nonInteractiveEnv };
}
+ // ── BYOK keys + per-provider config for the non-Claude CLI engines (v0.3.1) ──
+ // OpenCode / Crush / pi / qwen read BYOK API keys from standard env vars and, for
+ // the local-LLM path, a per-provider base URL. Keys are write-only in the broker
+ // (read MAIN-ONLY here, never logged); base URLs ride HarnessConfig. Claude/codex
+ // use their own login, so they skip this. Pam guardrails #3/#4/#5.
+ if (opts.hive && (provider === 'opencode' || provider === 'crush' || provider === 'pi' || provider === 'qwen')) {
+ const cfg = readConfig();
+ const extra: Record<string, string> = {};
+ // 1) BYOK keys — LEAST-PRIVILEGE (Pam/Jim NIT-2): inject ONLY the key for the
+ // spawned model's provider prefix when we can identify it; fall back to all
+ // stored keys when the model/prefix is unknown (default model, qwen slugs,
+ // custom). Reduces the blast radius vs handing every CLI all keys.
+ const modelIdx = (opts.args ?? []).indexOf('--model');
+ const modelSlug = modelIdx >= 0 ? (opts.args?.[modelIdx + 1] ?? '') : '';
+ const prefix = modelSlug.includes('/') ? modelSlug.split('/')[0].toLowerCase() : '';
+ const PREFIX_BACKEND: Record<string, string> = {
+ anthropic: 'anthropic', openai: 'openai', google: 'google', gemini: 'google', groq: 'groq', openrouter: 'openrouter'
+ };
+ const scoped = PREFIX_BACKEND[prefix];
+ const backends = scoped ? [scoped] : Object.keys(BACKEND_KEY_ENV);
+ for (const backend of backends) {
+ const key = integrations.getSecret(providerKeyRef(backend));
+ if (!key) continue;
+ extra[BACKEND_KEY_ENV[backend]] = key;
+ // OpenCode/AI-SDK's Google provider reads GOOGLE_GENERATIVE_AI_API_KEY, not
+ // GEMINI_API_KEY — inject both so google/* authenticates (Jim NIT #1).
+ if (backend === 'google') extra.GOOGLE_GENERATIVE_AI_API_KEY = key;
+ }
+ // 2) Floor auto-state for pi's bundled extension auto-allow (guardrail #5): it
+ // only auto-approves tool calls when this is '1' (i.e. floor auto mode on).
+ extra.HIVE_AUTO_APPROVE = cfg.autoMode ? '1' : '0';
+ // 3) OpenCode's auto-approve + local provider live in its single config-injection
+ // env var, built dynamically so permission:allow is GATED on autoMode (#2).
+ if (provider === 'opencode') {
+ const oc: Record<string, unknown> = { autoupdate: false };
+ if (cfg.autoMode) oc.permission = { edit: 'allow', bash: 'allow', webfetch: 'allow' };
+ const baseUrl = cfg.providerBaseUrls?.opencode;
+ if (baseUrl) {
+ // Register the model id the user actually selects (the part after 'local/')
+ // so `--model local/<id>` resolves; default to 'local'. Without this the
+ // dropdown's `local/llama3` failed against a config that only declared model
+ // 'local' (Jim verify-opencode MUST-FIX #2).
+ const localModel = (prefix === 'local' && modelSlug.slice(6)) || 'local';
+ oc.provider = {
+ local: { npm: '@ai-sdk/openai-compatible', name: 'Local (self-hosted)', options: { baseURL: baseUrl }, models: { [localModel]: { name: localModel } } }
+ };
+ }
+ extra.OPENCODE_CONFIG_CONTENT = JSON.stringify(oc);
+ }
+ opts.env = { ...(opts.env ?? {}), ...extra };
+ }
+ // Codex Remote is daemon-based (there is no `/remote-control` slash command).
+ // Start/enable the daemon under this agent's isolated CODEX_HOME and connect
+ // the TUI to it so the thread is visible in ChatGPT mobile. Best-effort: an
+ // unavailable/older Codex install still gets a normal local terminal.
+ if (provider === 'codex' && opts.hive?.id) {
+ await enableCodexRemoteForSpawn(opts, opts.hive.id);
+ }
- // Record the spawning window as the PTY's owner so its output (pty:data/exit)
- // routes ONLY back to that floor — never leaking into another window's stream.
- const owner = BrowserWindow.fromWebContents(evt.sender)?.webContents ?? null;
const res = ptyManager.spawn(opts, owner);
syncKeepAwake(); // arm the power-save blocker while ≥1 agent PTY is alive (#18)
// Hand the resolved worktree path back to the renderer so it can persist it on
@@@ -2341,13 -1966,17 +2599,23 @@@ ipcMain.handle('git:aheadBehind', (_evt
if (typeof cwd !== 'string') return { error: 'invalid cwd' };
return getAheadBehind(cwd);
});
+ipcMain.handle('git:diff', (_evt, cwd: unknown, relPath: unknown) => {
+ if (typeof cwd !== 'string' || typeof relPath !== 'string') {
+ return { ok: false, error: 'invalid args' };
+ }
+ return getDiff(cwd, relPath);
+});
+ // ─── IPC: roster mirror (shared between dev and a packaged build) ───────────
+ // The renderer's store is built synchronously at module load, before any async
+ // IPC could resolve, so the read is `ipcMain.on` + `returnValue` — one blocking
+ // round trip at boot, in exchange for the roster being correct on first paint
+ // instead of flashing an empty floor and then filling in.
+ const roster = new RosterStore(() => readConfig().harnessHome);
+ ipcMain.on('roster:readSync', (evt) => { evt.returnValue = roster.read(); });
+ ipcMain.handle('roster:read', () => roster.read());
+ ipcMain.handle('roster:write', (_evt, snap: unknown) => roster.write(snap));
+
// ─── IPC: hive (multi-agent coordination) ───────────────────────────────────
ipcMain.handle('hive:registry', () => hive.registry());
ipcMain.handle('hive:board', () => hive.board());
@@@ -3413,15 -2459,9 +3696,16 @@@ ipcMain.handle('workers:stop', (_evt, w
function bootstrapHiveServices(): void {
if (!hive.enabled()) return;
hive.ensureHive();
+ control.replaceAutoDeliveryPauses(readConfig().autoDeliveryPausedAgents ?? []);
archiveOrphanedAgents(); // #57/#58: archive stale archived:false entries with no live PTY
hive.startRouter();
+ startEphemeralWorkerWatcher(); // poll HIVE_ROOT/spawn-requests → ephemeral workers
+ // Phase 2: the loopback secret broker. Bind it BEFORE workers spawn so each spawn can
+ // be granted a capability token + the broker URL in its env. Loopback-only, idempotent.
+ void integrationBroker.start().then((r) => {
+ if (r.ok) console.log('[broker] integration broker listening on', integrationBroker.url());
+ else console.error('[broker] failed to start:', r.error);
+ });
ensureDefaultMissions(); // one-time: seed the built-in hourly ops standup
syncMissions(); // arm recurring auto-dispatch missions now the router is live
hookServer.start();
diff --cc src/main/pty.ts
index 7dc7cd16,4a27de84..af033348
--- a/src/main/pty.ts
+++ b/src/main/pty.ts
@@@ -2,8 -2,6 +2,8 @@@ import * as pty from 'node-pty'
import type { WebContents } from 'electron';
import { existsSync } from 'node:fs';
import { spawnSync } from 'node:child_process';
+import { ensureKilled } from './procKill';
- import { userShellPath } from './shellEnv';
++import { captureFromLoginShell, userShellPath } from './shellEnv';
interface PtySession {
id: string;
@@@ -203,19 -201,16 +206,17 @@@ export class PtyManager
`${home}\\.claude\\local\\${command}.cmd`,
`${home}\\.claude\\local\\${command}`
];
- for (const c of winCandidates) if (existsSync(c)) return c;
+ for (const c of winCandidates) if (existsSync(c)) return { path: c, found: true };
// Last resort — let node-pty try; will fail with ENOENT if missing.
- return command;
+ return { path: command, found: false };
}
// macOS / Linux — `which` against an interactive shell so we pick up nvm/asdf/brew paths.
- try {
- const res = spawnSync(process.env.SHELL ?? '/bin/zsh', ['-ilc', `which ${command}`], {
- encoding: 'utf8',
- timeout: 3000
- });
- const path = res.stdout.trim().split('\n').pop();
- const which = this.captureFromLoginShell(`which ${command}`);
++ // Fenced capture (shellEnv): rc-file chatter can't poison the which output.
++ const which = captureFromLoginShell(`which ${command}`);
+ if (which) {
+ const path = which.trim().split('\n').map((l) => l.trim()).filter(Boolean).pop();
- if (path && existsSync(path)) return path;
+ if (path && existsSync(path)) return { path, found: true };
- } catch { /* fall through */ }
+ }
// Common explicit locations
const candidates = [
`/opt/homebrew/bin/${command}`,
@@@ -236,14 -231,19 +237,15 @@@
if (!existsSync(opts.cwd)) {
return { ok: false, error: `cwd does not exist: ${opts.cwd}` };
}
- const resolved = this.resolveCommand(opts.command);
+ const resolved = this.resolveCommand(opts.command).path;
try {
- // Build a user-shell PATH so child can resolve subprocess deps.
- const userPath = (() => {
- // Windows has no interactive login-shell PATH problem — use the process PATH directly.
- if (process.platform === 'win32') return process.env.PATH || '';
- const shellPath = this.captureFromLoginShell('printf %s "$PATH"')?.trim();
- // A PATH is a single colon-joined line. Anything multi-line is rc-file
- // noise that slipped the fence — fall back rather than hand the agent a
- // corrupt PATH it would carry into every subprocess it spawns.
- if (shellPath && !shellPath.includes('\n')) return shellPath;
- return process.env.PATH || '';
- })();
+ // Build a user-shell PATH so child can resolve subprocess deps. Cached
- // for the session (shellEnv.userShellPath) — the interactive-shell launch
- // it replaces cost ~1s of main-thread freeze on EVERY spawn.
++ // for the session (shellEnv.userShellPath, fenced against rc-file noise) —
++ // the interactive-shell launch it replaces cost ~1s of main-thread freeze
++ // on EVERY spawn.
+ const userPath = process.platform === 'win32'
+ ? (process.env.PATH || '')
+ : userShellPath();
// On Windows, .cmd/.bat files (and extensionless shims) cannot be executed
// directly by CreateProcess — only .exe/.com can. Route them through cmd.exe.
diff --cc src/main/shellEnv.ts
index 4ac39ed4,4ac39ed4..4542560a
--- a/src/main/shellEnv.ts
+++ b/src/main/shellEnv.ts
@@@ -9,6 -9,6 +9,51 @@@ import { spawnSync } from 'node:child_p
let cachedPath: string | null = null;
++/** script → captured output, memoised for the process lifetime. Every capture
++ * boots a full interactive login shell (rc files and all) — hundreds of ms of
++ * BLOCKING spawnSync on the main process — and shell PATH / binary locations
++ * don't change mid-session. Only successful captures are cached, so a null
++ * (shell failed / fence missing) stays retryable. */
++const shellCapture = new Map<string, string>();
++
++/** Run `script` in the user's INTERACTIVE login shell and return only what the
++ * script itself printed.
++ *
++ * An interactive shell is required to pick up nvm/asdf/brew PATH edits, but it
++ * also runs the user's rc files, which are free to print. Some zsh setups emit
++ * `Restored session: <date>` from a session-save plugin BEFORE the script's
++ * own output, which silently poisons every value read back: a plain `.trim()`
++ * on `echo "$PATH"` yields `"Restored session: …\n/opt/homebrew/bin:…"` and
++ * that whole string gets handed to every agent as its PATH. Fencing the output
++ * between two markers makes rc-file chatter (before, after, or both)
++ * impossible to mistake for a result. Returns null when the shell fails or the
++ * fence never appears. */
++export function captureFromLoginShell(script: string): string | null {
++ const cached = shellCapture.get(script);
++ if (cached !== undefined) return cached;
++ const value = captureFromLoginShellUncached(script);
++ if (value !== null) shellCapture.set(script, value);
++ return value;
++}
++
++function captureFromLoginShellUncached(script: string): string | null {
++ const mark = '__MD_SHELL_FENCE__';
++ try {
++ const res = spawnSync(
++ process.env.SHELL ?? '/bin/zsh',
++ ['-ilc', `printf %s ${mark}; ${script}; printf %s ${mark}`],
++ { encoding: 'utf8', timeout: 3000 }
++ );
++ const out = res.stdout ?? '';
++ const start = out.indexOf(mark);
++ const end = out.lastIndexOf(mark);
++ if (start < 0 || end <= start) return null;
++ return out.slice(start + mark.length, end);
++ } catch {
++ return null;
++ }
++}
++
/** The user's interactive-shell PATH, queried once and cached for the session. */
export function userShellPath(): string {
if (cachedPath !== null) return cachedPath;
@@@ -17,15 -17,15 +62,11 @@@
cachedPath = process.env.PATH || '';
return cachedPath;
}
-- try {
-- const res = spawnSync(process.env.SHELL ?? '/bin/zsh', ['-ilc', 'echo -n "$PATH"'], {
-- encoding: 'utf8',
-- timeout: 3000
-- });
-- cachedPath = res.stdout.trim() || process.env.PATH || '';
-- } catch {
-- cachedPath = process.env.PATH || '';
-- }
++ const shellPath = captureFromLoginShell('printf %s "$PATH"')?.trim();
++ // A PATH is a single colon-joined line. Anything multi-line is rc-file noise
++ // that slipped the fence — fall back rather than hand the agent a corrupt
++ // PATH it would carry into every subprocess it spawns.
++ cachedPath = shellPath && !shellPath.includes('\n') ? shellPath : process.env.PATH || '';
return cachedPath;
}
@@@ -54,14 -54,14 +95,11 @@@ export function resolveCommand(command
for (const c of winCandidates) if (existsSync(c)) return c;
return command;
}
-- try {
-- const res = spawnSync(process.env.SHELL ?? '/bin/zsh', ['-ilc', `which ${command}`], {
-- encoding: 'utf8',
-- timeout: 3000
-- });
-- const path = res.stdout.trim().split('\n').pop();
++ const which = captureFromLoginShell(`which ${command}`);
++ if (which) {
++ const path = which.trim().split('\n').map((l) => l.trim()).filter(Boolean).pop();
if (path && existsSync(path)) return path;
-- } catch { /* fall through */ }
++ }
const candidates = [
`/opt/homebrew/bin/${command}`,
`/usr/local/bin/${command}`,
diff --cc src/preload/index.ts
index a6b4735f,910250c8..3f772fc2
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@@ -64,46 -50,14 +78,51 @@@ export interface HiveRegistry
godId: string | null;
/** `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 }>;
+ agents: Record<string, HiveAgentMeta & {
+ status: string;
+ lastSeen: number;
+ archived?: boolean;
+ sessionId?: string;
+ }>;
}
+/** 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;
@@@ -996,79 -801,18 +1034,91 @@@ const api =
}): Promise<{ ok: boolean; text?: string; error?: string }> =>
ipcRenderer.invoke('freeflow:transcribe', arg),
+ // ─── Integrations registry (Phase 2 — labeled REST endpoints via the secret broker) ──
+ // Bridges the §6 IPC surface for the Settings UI. WRITE-ONLY secret contract end to
+ // end: `integrationsList` returns records with secretRef redacted to `hasSecret`;
+ // `integrationsSetSecret` takes a secret ONE WAY (never echoed); NO method ever
+ // returns a secret value to the renderer. Method names match registryClient's
+ // feature-detection (camelCase ↔ colon-channel), so its real path activates as-is.
+ integrationsList: (): Promise<IntegrationRecordView[]> =>
+ ipcRenderer.invoke('integrations:list'),
+ integrationsTemplates: (): Promise<IntegrationTemplate[]> =>
+ ipcRenderer.invoke('integrations:templates'),
+ integrationsUpsert: (record: IntegrationRecord): Promise<{ ok: true; record: IntegrationRecord } | { ok: false; error: string }> =>
+ ipcRenderer.invoke('integrations:upsert', record),
+ integrationsSetSecret: (req: { id: string; secret: string }): Promise<{ ok: boolean; error?: string }> =>
+ ipcRenderer.invoke('integrations:setSecret', req),
+ integrationsRemove: (req: { id: string }): Promise<{ ok: boolean }> =>
+ ipcRenderer.invoke('integrations:remove', req),
+ integrationsTest: (req: { id: string; path?: string }): Promise<{ ok: boolean; status?: number; error?: string }> =>
+ ipcRenderer.invoke('integrations:test', req),
+ // Per-CLI-provider BYOK keys — WRITE-ONLY. `providerKeySet` stores a backend key one
+ // way (never echoed); `providerKeyHas` returns only a boolean; no method ever returns
+ // the plaintext. Keys are materialized MAIN-ONLY at spawn.
+ providerKeySet: (req: { backend: string; key: string }): Promise<{ ok: boolean; error?: string }> =>
+ ipcRenderer.invoke('providerKey:set', req),
+ providerKeyHas: (backend: string): Promise<boolean> =>
+ ipcRenderer.invoke('providerKey:has', backend),
+ providerKeyClear: (backend: string): Promise<{ ok: boolean; error?: string }> =>
+ ipcRenderer.invoke('providerKey:clear', backend),
+ // Realtime Michael (voice orchestrator) — MAIN mints a short-lived EPHEMERAL token
+ // from the BYOK OpenAI key; the real key NEVER crosses IPC. `realtimeHasOpenAiKey`
+ // is a presence boolean only (gates the voice toggle, like providerKeyHas).
+ realtimeHasOpenAiKey: (): Promise<boolean> =>
+ ipcRenderer.invoke('realtime:hasKey'),
+ realtimeMintToken: (
+ req?: { model?: string }
+ ): Promise<
+ | { ok: true; token: string; expiresAt: number | null; sessionConfig: { model: string } }
+ | { ok: false; error: string; code?: string }
+ > => ipcRenderer.invoke('realtime:mintToken', req ?? {}),
+ // rt-5 voice ACTIONS — the renderer holds NO policy; main (realtimeActions.ts) owns
+ // the tiering, two-step verbal confirm, hard allowlist, and michael-voice
+ // attribution. These just forward {verb,...args} and speak back `spoken`.
+ realtimeAction: (
+ payload: { verb: string } & Record<string, unknown>
+ ): Promise<{ ok: boolean; spoken: string; needsConfirm?: boolean }> =>
+ ipcRenderer.invoke('realtime:action', payload),
+ realtimeActionConfirm: (
+ req: { phrase: string }
+ ): Promise<{ ok: boolean; spoken: string; needsConfirm?: boolean }> =>
+ ipcRenderer.invoke('realtime:action:confirm', req),
+ realtimeActionCancel: (): Promise<{ ok: boolean; spoken: string; needsConfirm?: boolean }> =>
+ ipcRenderer.invoke('realtime:action:cancel'),
+ // rt-12 completion seam — a voice-dispatched task finished. `summary` is the
+ // human-speakable line Michael relays; the rest is context for a toast/log.
+ onRealtimeCompletion: (
+ cb: (evt: { correlationId: string; kind: string; targetAgentId: string; taskId?: string; summary: string; completedAt: number; objective?: string }) => void
+ ): (() => void) => {
+ const listener = (_e: IpcRendererEvent, payload: Parameters<typeof cb>[0]) => cb(payload);
+ ipcRenderer.on('realtime:completion', listener);
+ return () => ipcRenderer.removeListener('realtime:completion', listener);
+ },
+ /** Tell main whether a live voice session is open (drives queue-vs-push for completions). */
+ realtimeSetSessionLive: (live: boolean): Promise<{ ok: boolean }> =>
+ ipcRenderer.invoke('realtime:setSessionLive', live),
+ /** Drain completions that arrived while no session was open (warm-start catch-up). */
+ realtimeDrainCompletions: (): Promise<
+ { correlationId: string; kind: string; targetAgentId: string; taskId?: string; summary: string; completedAt: number; objective?: string }[]
+ > => ipcRenderer.invoke('realtime:drainCompletions'),
+ /** Block until a tracked task completes (or times out) — backs the wait_for tool. */
+ realtimeWaitFor: (
+ taskId: string,
+ timeoutMs?: number
+ ): Promise<{ summary: string; targetAgentId: string; taskId?: string } | { timedOut: true; taskId: string }> =>
- ipcRenderer.invoke('realtime:waitFor', taskId, timeoutMs)
++ ipcRenderer.invoke('realtime:waitFor', taskId, timeoutMs),
+ // ─── Roster mirror (agents + notes + queues, shared dev ↔ packaged) ─────────
+ /** Read the roster file beside the hive. SYNCHRONOUS on purpose: the zustand
+ * store is created at module load, so an async read would arrive after the
+ * first render and the floor would flash empty. One blocking round trip at
+ * boot. `null` = no file (or unreadable) — the caller then uses localStorage. */
+ rosterReadSync: (): RosterSnapshot | null => {
+ try { return ipcRenderer.sendSync('roster:readSync') ?? null; } catch { return null; }
+ },
+ /** Mirror the roster to disk. Debounced by the caller; main keeps the previous
+ * contents as a backup and refuses a first write that would empty a full file. */
+ rosterWrite: (snap: RosterSnapshot): Promise<{ ok: boolean; skipped?: string; error?: string }> =>
+ ipcRenderer.invoke('roster:write', snap)
};
contextBridge.exposeInMainWorld('cth', api);
diff --cc src/renderer/src/App.tsx
index 7c784773,f61aef47..7541a79c
--- a/src/renderer/src/App.tsx
+++ b/src/renderer/src/App.tsx
@@@ -388,9 -303,8 +388,9 @@@ export function App()
/>
)}
- {fullscreenAgentId && <FullscreenTerminal />}
+ {fullscreenAgentId && <FullscreenTerminal config={config} />}
{fullscreenFilePath && <FullscreenFileEditor />}
+ {ideOpen && <IdePanel />}
<TaskDetailOverlay />
</div>
);
diff --cc src/renderer/src/components/AddAgentModal.tsx
index 876732a6,ec508637..9da15bb1
--- a/src/renderer/src/components/AddAgentModal.tsx
+++ b/src/renderer/src/components/AddAgentModal.tsx
@@@ -1,4 -1,4 +1,4 @@@
- import { useState, type CSSProperties } from 'react';
-import { useEffect, useState } from 'react';
++import { useEffect, useState, type CSSProperties } from 'react';
import { PixelPanel } from './PixelPanel';
import { PixelButton } from './PixelButton';
import { SpritePortrait } from './SpritePortrait';
@@@ -190,11 -62,13 +190,16 @@@ export function AddAgentModal({ onClose
// user's typed command rather than blanking it.
const pickProvider = (id: AgentProvider) => {
setProvider(id);
- const nextModel = isClaudeProvider(id) ? config.defaultModel : undefined;
+ // Seed the model: Claude from the global defaultModel; other engines from the
+ // per-engine default set in Settings → AI Engines (providerDefaultModels), else
+ // the CLI default. This is what makes that Settings field live (Dwight NIT-1).
+ const nextModel = isClaudeProvider(id) ? config.defaultModel : config.providerDefaultModels?.[id];
setModel(nextModel);
+ const nextPreset = providerPreset(id);
+ if (!isClaudeProvider(id) && !nextPreset.resumeFlag && !nextPreset.resumeSubcommand) {
+ setResumeSessionId('');
+ setFolderNote(undefined);
+ }
if (id === 'custom') {
setCommand(command.trim() || config.defaultCommand || '');
return;
@@@ -212,19 -86,20 +217,32 @@@
const [folderNote, setFolderNote] = useState<string | undefined>();
const [error, setError] = useState<string | undefined>();
const [busy, setBusy] = useState(false);
+ // Which config section the left sidebar index is showing.
+ const [section, setSection] = useState<SectionKey>('identity');
+ // "Generate a hire with AI" helper — reveals a copy-paste prompt (item 7).
+ const [showHirePrompt, setShowHirePrompt] = useState(false);
+ const [copiedPrompt, setCopiedPrompt] = useState(false);
+ const copyHirePrompt = async () => {
+ try {
+ await navigator.clipboard.writeText(HIRE_PROMPT);
+ setCopiedPrompt(true);
+ setTimeout(() => setCopiedPrompt(false), 1500);
+ } catch { /* clipboard blocked — the textarea below is selectable as a fallback */ }
+ };
+ // Close only the modal on Esc. Capture prevents the fullscreen terminal's
+ // window-level handler from also closing the view underneath.
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key !== 'Escape') return;
+ e.preventDefault();
+ e.stopImmediatePropagation();
+ onClose();
+ };
+ window.addEventListener('keydown', onKey, true);
+ return () => window.removeEventListener('keydown', onKey, true);
+ }, [onClose]);
+
// Zero-step resume: when a session id is entered, look up the cwd it originally
// ran in (from the transcript) and pre-fill the Folder so the user doesn't have
// to find the worktree. They can still override the folder afterwards. Runs on
@@@ -394,14 -201,12 +412,12 @@@
position: 'fixed', inset: 0,
background: 'rgba(26, 19, 32, 0.6)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
- // Dialog tier (matches SettingsModal / QuitWarningModal at 300). Must sit
- // ABOVE FullscreenTerminal (250) and the fullscreen file/kanban overlays
- // (280): the "+ agent" button is reachable from fullscreen, so a lower
- // z-index made this modal open BEHIND the fullscreen view.
- zIndex: 300
+ // Must sit above fullscreen terminal/file overlays (250/280) and their
+ // hover popovers. The fullscreen Add Agent button uses this same modal.
+ zIndex: 500
}}
>
- <div onClick={(e) => e.stopPropagation()} style={{ width: 600, maxWidth: '92vw' }}>
+ <div onClick={(e) => e.stopPropagation()} style={{ width: 940, maxWidth: '95vw' }}>
<PixelPanel
variant="dialog"
title="ADD AGENT"
diff --cc src/renderer/src/components/AgentCard.tsx
index 9b651489,e8010b4b..a4991739
--- a/src/renderer/src/components/AgentCard.tsx
+++ b/src/renderer/src/components/AgentCard.tsx
@@@ -1,9 -1,7 +1,10 @@@
+import { useState } from 'react';
import { PixelPanel } from './PixelPanel';
import { PixelBadge, StatusKind } from './PixelBadge';
+ import { useHasTerminalDraft } from './terminalPool';
import { SpritePortrait } from './SpritePortrait';
+import { RealtimeMichaelToggle } from './RealtimeMichaelToggle';
+import { CostHud } from '@/realtime/CostHud';
import { AccentColorName } from '@/design/tokens';
import { OfficeCharacterName } from '@/scene/office/cast';
@@@ -33,11 -36,11 +39,12 @@@ export interface AgentCardProps
const fmtK = (n: number): string => `${Math.round(n / 1000)}k`;
export function AgentCard({
- name, character, accent, status, project, action, progress = 0,
+ name, character, accent, status, ptyId, project, action, progress = 0,
contextTokens, contextLimit, selected, isGod, onClick,
- doingCount = 0, onTaskNoteClick
+ doingCount = 0, onTaskNoteClick, draggable
}: AgentCardProps) {
+ const [hover, setHover] = useState(false);
+ const typing = useHasTerminalDraft(ptyId);
// The god is always framed (stands out from the row); others only when selected.
const framed = isGod || selected;
@@@ -65,16 -47,12 +72,17 @@@
return (
<button
onClick={onClick}
+ onMouseEnter={() => setHover(true)}
+ onMouseLeave={() => setHover(false)}
+ draggable={draggable}
className="cth-titlebar-nodrag"
style={{
- width: 220, minWidth: 220, height: 96,
+ width, minWidth: width, height,
padding: 0, border: 'none', background: 'transparent', cursor: 'pointer', textAlign: 'left',
- position: 'relative'
+ position: 'relative',
+ transform: lift ? `translateY(${lift}px)` : 'none',
+ boxShadow: dropShadow,
+ transition: 'transform 90ms steps(2, end), box-shadow 90ms steps(2, end)'
}}
>
{/* The taken note, stuck to the card like on the desk: this worker is
@@@ -124,78 -98,62 +132,78 @@@
fontSize: 'var(--cth-text-display-sm)',
lineHeight: 'var(--cth-lh-display-sm)',
color: 'var(--cth-ink-900)',
- whiteSpace: 'nowrap',
- overflow: 'hidden',
- textOverflow: 'ellipsis'
+ background: `var(--cth-${accent})`,
+ padding: '3px 6px 2px',
+ boxShadow: 'inset 0 0 0 1px var(--cth-ink-900)',
+ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', flexShrink: 1
+ } : {
+ fontFamily: 'var(--cth-font-display)',
+ fontSize: 'var(--cth-text-display-sm)',
+ lineHeight: 'var(--cth-lh-display-sm)',
+ color: 'var(--cth-ink-900)',
+ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis'
}}>{name.toUpperCase()}</span>
- <PixelBadge status={status} />
+ <PixelBadge status={typing ? 'typing' : status} />
</div>
- <div style={{
- display: 'flex', alignItems: 'center', gap: 5,
- fontSize: 'var(--cth-text-body-sm)',
- lineHeight: '16px',
- color: 'var(--cth-ink-500)',
- whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis'
- }}>
- {isGod && (
- <span style={{
- fontFamily: 'var(--cth-font-display)', fontSize: 8, lineHeight: '12px',
- background: `var(--cth-${accent})`, color: 'var(--cth-ink-900)',
- padding: '1px 5px 0', boxShadow: 'inset 0 0 0 1px var(--cth-ink-900)', flexShrink: 0
- }}>GOD</span>
- )}
- <span style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>{project}</span>
- </div>
+ {isGod ? (
+ <>
+ {/* Identity line — the GOD tag + which workspace it orchestrates. */}
+ <div style={{
+ display: 'flex', alignItems: 'center', gap: 5,
+ fontSize: 'var(--cth-text-body-sm)', lineHeight: '16px',
+ color: 'var(--cth-ink-500)',
+ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis'
+ }}>
+ <span style={{
+ fontFamily: 'var(--cth-font-display)', fontSize: 8, lineHeight: '12px',
+ background: `var(--cth-${accent})`, color: 'var(--cth-ink-900)',
+ padding: '1px 5px 0', boxShadow: 'inset 0 0 0 1px var(--cth-ink-900)', flexShrink: 0
+ }}>GOD</span>
+ <span style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>{project}</span>
+ </div>
+
+ {/* Voice control gets its OWN line — a clear, labelled "talk" button
+ (not the cramped icon-only form) with the live cost meter beside
+ it. Stops its click so the mic never selects the card. */}
+ <div
+ style={{ display: 'flex', alignItems: 'center', gap: 6, minWidth: 0 }}
+ onClick={(e) => e.stopPropagation()}
+ >
+ <RealtimeMichaelToggle />
+ <CostHud compact />
+ </div>
+ </>
+ ) : (
+ <>
+ {/* Project the worker is checked out into. */}
+ <div style={{
+ fontSize: 'var(--cth-text-body-sm)', lineHeight: '16px',
+ color: 'var(--cth-ink-500)',
+ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis'
+ }}>{project}</div>
- <div style={{
- fontSize: 'var(--cth-text-body-sm)',
- lineHeight: '16px',
- // Reserve the line even when empty (idle has no action text) —
- // otherwise it collapses and the context gauge below jumps up.
- minHeight: 16,
- color: 'var(--cth-ink-900)',
- whiteSpace: 'nowrap',
- overflow: 'hidden',
- textOverflow: 'ellipsis'
- }}>{/* The "idle" badge already conveys idle — don't echo "awaiting". */
- (status === 'idle' ? '' : action) || ' '}</div>
+ {/* What it's doing right now. Reserve the line even when idle (the
+ "idle" badge already says so) so the gauge below never jumps. */}
+ <div style={{
+ fontSize: 'var(--cth-text-body-sm)', lineHeight: '16px', minHeight: 16,
+ color: 'var(--cth-ink-900)',
+ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis'
+ }}>{(status === 'idle' ? '' : action) || ' '}</div>
+ </>
+ )}
- {/* Context gauge: how full the session's context window is. Accent
- while comfortable, lemon from 6/8 (~75%), coral from 7/8 —
- "compaction imminent". Pinned to the card's bottom line so it
- never moves, whatever the lines above do. */}
- <div
- style={{ display: 'flex', gap: 2, marginTop: 'auto' }}
- title={contextTokens !== undefined && contextLimit
- ? `Context: ${fmtK(contextTokens)} / ${fmtK(contextLimit)} tokens (${Math.round((contextTokens / contextLimit) * 100)}%)`
- : 'Context gauge — fills once the agent reports activity'}
- >
- {Array.from({ length: 8 }).map((_, i) => (
- <div key={i} style={{
- width: 14, height: 6,
- background: i < progress
- ? (progress >= 7 ? 'var(--cth-coral)' : progress >= 6 ? 'var(--cth-lemon)' : `var(--cth-${accent})`)
- : 'var(--cth-cream-200)',
- boxShadow: 'inset 0 0 0 1px var(--cth-ink-900)'
- }}/>
- ))}
+ {/* Context gauge — one clean fill bar pinned to the card's bottom edge
+ so it never moves, whatever the lines above do. */}
+ <div style={{ marginTop: 'auto' }} title={gaugeTitle}>
+ <div style={{
+ height: 6, width: '100%',
+ background: 'var(--cth-cream-200)',
+ boxShadow: 'inset 0 0 0 1px var(--cth-ink-900)',
+ overflow: 'hidden'
+ }}>
+ <div style={{ width: `${pct}%`, height: '100%', background: gaugeColor }} />
+ </div>
</div>
</div>
</div>
diff --cc src/renderer/src/components/CommandCenterPanel.tsx
index 1574c533,5ed83cf7..f24fec59
--- a/src/renderer/src/components/CommandCenterPanel.tsx
+++ b/src/renderer/src/components/CommandCenterPanel.tsx
@@@ -8,16 -8,25 +8,29 @@@ import { MessageQueueComposer } from '.
import { TasksKanban } from './TasksKanban';
import { AskMeTab } from './AskMeTab';
import { SchedulesTab } from './SchedulesTab';
+import { WorkersTab } from './WorkersTab';
- import { acquireTerminal, resetTerminal } from './terminalPool';
+ import { acquireTerminal, disposeTerminal, resetTerminal } from './terminalPool';
+ import { terminalInstanceKey } from './terminalRecovery';
import { Icon } from './Icon';
import { MemoryGraphPanel } from './MemoryGraphPanel';
import { useFleetTelemetry } from '@/hooks/useTelemetry';
import { COMMAND_GROUPS } from '@shared/claudeCommands';
import { useStore, type Agent } from '@/store/store';
import { usePtyParser } from '@/hooks/usePtyParser';
- import { buildSpawnCommand, modelsForProvider, tokenizeCommand, inferAgentProvider, isClaudeProvider, AGENT_PROVIDER_PRESETS, type AgentProvider } from '@/store/config';
+ import {
+ buildSpawnCommand,
+ decodeProviderModel,
+ encodeProviderModel,
+ inferAgentProvider,
++ isClaudeProvider,
+ modelProvidersForAgent,
+ modelsForProvider,
+ providerPreset,
+ tokenizeCommand,
++ AGENT_PROVIDER_PRESETS,
+ type AgentProvider
+ } from '@/store/config';
+import { canReceiveInbox } from '@shared/agentProvider';
/** Michael's control surface. Shown instead of the plain terminal/files panel
* when the god agent is selected: terminal + queue, the floor roster (with
@@@ -52,11 -61,14 +65,15 @@@ const TABS: { key: CCTab; label: string
{ key: 'memory', label: 'memory', icon: 'sparkle' },
{ key: 'graph', label: 'graph', icon: 'web' },
{ key: 'activity', label: 'activity', icon: 'bell' },
- { key: 'handbook', label: 'commands', icon: 'code' }
+ { key: 'handbook', label: 'commands', icon: 'code' },
+ { key: 'workers', label: 'workers', icon: 'gear' }
];
- export function CommandCenterPanel({ agent }: { agent: Agent }) {
+ /** @param fullscreen this instance IS the fullscreen overlay, so it owns the pty
+ * and renders the real terminal. The docked instance renders the "open in
+ * fullscreen" placeholder instead — two live xterms on one pty fight over its
+ * cols/rows and corrupt the display. */
+ export function CommandCenterPanel({ agent, fullscreen = false }: { agent: Agent; fullscreen?: boolean }) {
const [tab, setTab] = useState<CCTab>('terminal');
// External tab requests (the office task board → 'tasks', the boss-room
// calendar → 'schedules'). seq-keyed so clicking again re-opens the tab even
@@@ -213,8 -222,11 +231,13 @@@ function FloorTab({ seed }: { seed: { t
// Per-agent token limit (overrides the floor budget for that agent), keyed by id.
const [agentTokenCaps, setAgentTokenCaps] = useState<Record<string, number>>({});
const [restarting, setRestarting] = useState<string | null>(null);
+ const [engineProvider, setEngineProvider] = useState<AgentProvider>('claude');
+ const [engineModel, setEngineModel] = useState<string | undefined>(undefined);
+ const [restartErrors, setRestartErrors] = useState<Record<string, string>>({});
+ // The harness's own default model (Settings → default model). Michael and every
+ // new agent spawn on this, so the picker marks it — otherwise the only entry
+ // reading "default" was the CLI's, which is a different thing entirely.
+ const [defaultModel, setDefaultModel] = useState<string | undefined>(undefined);
const [dispatchTo, setDispatchTo] = useState<string>(''); // '' = Michael decides
const [dispatchText, setDispatchText] = useState('');
const [dispatchMsg, setDispatchMsg] = useState<string | null>(null);
@@@ -229,8 -241,7 +252,9 @@@
setRepos(c.registeredRepos ?? []);
setTokenCap(c.costCapTokens);
setAgentTokenCaps(c.agentTokenCaps ?? {});
+ setEngineProvider(c.godProvider ?? 'claude');
+ setEngineModel(c.godModel);
+ setDefaultModel(c.defaultModel);
}).catch(() => { /* noop */ });
}, []);
@@@ -247,23 -258,77 +271,81 @@@
// hatch for a corrupted/garbled terminal (e.g. xterm reflow after dragging the
// window between displays of different sizes). With `resume` unset it's the
// old behavior: a model change that starts a fresh session.
- const restartWithModel = async (a: Agent, model: string | undefined, opts: { resume?: boolean; provider?: AgentProvider } = {}) => {
+ const restartWithModel = async (
+ a: Agent,
+ model: string | undefined,
+ opts: {
+ resume?: boolean;
+ provider?: AgentProvider;
+ /** Resume if we can, start fresh if we can't, instead of refusing.
+ * "Restart & Continue" wants the hard failure — continuing is the entire
+ * point, so silently starting a blank session would be worse than an
+ * error. A model change wants the soft one: the user asked to change
+ * model, and an agent with no recorded session still has to get one. */
+ resumeOptional?: boolean;
+ } = {}
+ ) => {
if (!a.ptyId) return;
setRestarting(a.id);
+ setRestartErrors((errors) => ({ ...errors, [a.id]: '' }));
try {
const cfg = await window.cth.getConfig();
- await window.cth.killPty(a.ptyId);
- // Soft-reset the pooled terminal in place rather than disposing it: the
- // same ptyId is reused, so its data subscription, opened xterm and keyboard
- // wiring all survive the restart. (Disposing dropped the live terminal while
- // the view — keyed on the unchanged ptyId — never re-attached a replacement,
- // leaving a dead pane that swallowed every keystroke.)
- resetTerminal(a.ptyId);
+ // Respawn on the same CLI this agent already runs on (inferred from its
+ // command if not explicitly tagged) so an Antigravity/Codex worker stays
+ // on its own binary. tokenizeCommand keeps quoted model labels one arg.
+ // opts.provider overrides the inferred provider — used when changing GOD's engine.
- const provider = opts.provider ?? inferAgentProvider(a.command, a.provider);
+ const previousProvider = inferAgentProvider(a.command, a.provider);
+ const provider = opts.provider ?? previousProvider;
+ let resume = opts.resume === true && provider === previousProvider;
+ if (opts.resume && !resume && !opts.resumeOptional) {
+ throw new Error('Cannot resume a session through a different provider.');
+ }
+ let resumeSessionId: string | undefined;
+ if (resume) {
+ // A precondition miss is fatal for an explicit "continue", and merely
+ // means "start fresh" for an opportunistic one (see resumeOptional).
+ const giveUpOnResume = (reason: string) => {
+ if (!opts.resumeOptional) throw new Error(reason);
+ resume = false;
+ resumeSessionId = undefined;
+ };
+ const registry = await window.cth.hiveRegistry();
+ resumeSessionId = registry.agents[a.id]?.sessionId;
+ if (!resumeSessionId) {
+ giveUpOnResume('No recorded session ID; current process was left running.');
+ } else if (provider === 'claude' && !(await window.cth.resolveSessionCwd(resumeSessionId))) {
+ giveUpOnResume('Session transcript not found; current process was left running.');
+ }
+ }
+ // Capture the live grid before replacing anything. Restart & Continue
+ // recreates only this agent's xterm; model changes retain the old
+ // in-place reset behavior.
+ const oldEntry = acquireTerminal(a.ptyId);
+ let cols = oldEntry.term.cols || 100;
+ let rows = oldEntry.term.rows || 30;
+ try {
+ oldEntry.fit.fit();
+ cols = oldEntry.term.cols;
+ rows = oldEntry.term.rows;
+ } catch { /* host not sized yet */ }
+
+ const killed = await window.cth.killPty(a.ptyId);
+ if (!killed.ok) throw new Error(killed.error ?? 'Could not stop the current process.');
+ if (resume) {
+ // A blank xterm can retain corrupt renderer/DOM/subscription state even
+ // after its PTY is healthy. Throw that one terminal away, acquire its
+ // replacement BEFORE spawning (so startup output has a listener), then
+ // bump the key so React remounts only this agent's terminal card.
+ disposeTerminal(a.ptyId);
+ acquireTerminal(a.ptyId);
+ updateAgent(a.id, {
+ terminalGeneration: (a.terminalGeneration ?? 0) + 1,
+ status: 'idle',
+ action: 'recreating terminal…'
+ });
+ } else {
+ resetTerminal(a.ptyId);
+ }
const command = buildSpawnCommand(cfg, model, provider);
const [exe, ...args] = tokenizeCommand(command.trim());
const hive = a.isGod
@@@ -498,17 -600,49 +617,54 @@@
</span>
)}
</div>
- {/* Non-god agents get the per-agent model picker + restart controls here.
- The GOD agent's model lives in the engine row below (provider+model+apply),
- so we DON'T render this second selector for it — one model picker, not two. */}
- {!a.isGod && (isClaudeProvider(inferAgentProvider(a.command, a.provider)) ? <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
++ {/* Non-god agents get the cross-provider model picker + restart controls
++ here. The GOD agent's model lives in the engine row below
++ (provider+model+apply), so we DON'T render this second selector for
++ it — one model picker, not two. */}
++ {!a.isGod && (
++ <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
<Select
- value={a.model ?? ''}
+ value={encodeProviderModel(agentProvider, a.model)}
disabled={restarting === a.id}
- onChange={(v) => restartWithModel(a, v || undefined)}
+ onChange={(value) => {
+ const choice = decodeProviderModel(value);
+ if (!choice) return;
+ // Switching model within the SAME provider continues the
+ // conversation — that's the whole point of switching mid-task
+ // ("this got hard, go up a tier"), and starting fresh threw
+ // away the context that made the switch necessary.
+ // `resume` is best-effort: restartWithModel already refuses it
+ // across providers, and falls back to a fresh session when no
+ // session id or transcript is recorded.
+ void restartWithModel(a, choice.model, {
+ provider: choice.provider,
+ resume: choice.provider === agentProvider,
+ resumeOptional: true
+ });
+ }}
>
- {modelsForProvider(inferAgentProvider(a.command, a.provider)).map((m) => (
- <option key={m.label} value={m.id ?? ''}>{m.label}</option>
+ {(!agentPreset.supportsModel || !currentModelKnown) && (
+ <option value={encodeProviderModel(agentProvider, a.model)}>
+ {agentPreset.label} · {a.model ?? 'current'}
+ </option>
+ )}
+ {modelProvidersForAgent(a.isGod).map((preset) => (
+ <optgroup key={preset.id} label={preset.label}>
+ {modelsForProvider(preset.id).map((model) => {
+ // `defaultModel` is a Claude model id, so it can only mark
+ // an entry in the Claude group.
+ const isHarnessDefault = preset.id === 'claude'
+ && !!defaultModel && model.id === defaultModel;
+ return (
+ <option
+ key={`${preset.id}:${model.id ?? 'cli-default'}`}
+ value={encodeProviderModel(preset.id, model.id)}
+ >
+ {model.label}{isHarnessDefault ? ' · default' : ''}
+ </option>
+ );
+ })}
+ </optgroup>
))}
</Select>
<span style={{ fontSize: 11, color: 'var(--cth-ink-500)' }}>
@@@ -518,79 -654,25 +676,83 @@@
resuming the prior conversation (--resume). Use this to redraw a
garbled TUI (e.g. after dragging the window across displays)
without losing the thread. */}
- <span style={{ flex: 1 }} />
- <PixelButton
- variant="secondary"
- size="sm"
- disabled={restarting === a.id}
- onClick={() => restartWithModel(a, a.model, { resume: true })}
- >
- <span title="Kill and respawn this agent, resuming its current conversation — fixes a corrupted/garbled terminal without losing context">
- restart &amp; continue
- </span>
- </PixelButton>
- </div> : (
- <div style={{ fontSize: 11, color: 'var(--cth-ink-500)' }}>
- provider: {inferAgentProvider(a.command, a.provider)}
+ {(agentProvider === 'claude' || agentPreset.resumeFlag || agentPreset.resumeSubcommand) && <>
+ <span style={{ flex: 1 }} />
+ <PixelButton
+ variant="secondary"
+ size="sm"
+ disabled={restarting === a.id}
+ onClick={() => restartWithModel(a, a.model, { resume: true })}
+ >
+ <span title="Kill and respawn this agent, resuming its current conversation — fixes a corrupted/garbled terminal without losing context">
+ restart &amp; continue
+ </span>
+ </PixelButton>
+ </>}
+ </div>
++ )}
+ {restartErrors[a.id] && (
+ <div style={{ fontSize: 11, color: 'var(--cth-coral)' }}>
+ {restartErrors[a.id]}
</div>
- ))}
+ )}
+ {a.isGod && (
+ <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
+ <span style={{ fontSize: 11, color: 'var(--cth-ink-500)', flexShrink: 0 }}>engine:</span>
+ <Select
+ value={engineProvider}
+ disabled={restarting === a.id}
+ onChange={(v) => {
+ const p = v as AgentProvider;
+ setEngineProvider(p);
+ const preset = AGENT_PROVIDER_PRESETS.find((x) => x.id === p);
+ setEngineModel(preset?.recommendedOrchestratorModel);
+ }}
+ >
+ {AGENT_PROVIDER_PRESETS.filter((p) => canReceiveInbox(p.id)).map((p) => (
+ <option key={p.id} value={p.id}>
+ {p.label}{p.id === 'claude' ? ' ★' : ''}
+ </option>
+ ))}
+ </Select>
+ <Select
+ value={engineModel ?? ''}
+ disabled={restarting === a.id}
+ onChange={(v) => setEngineModel(v || undefined)}
+ >
+ {modelsForProvider(engineProvider).map((m) => (
+ <option key={m.label} value={m.id ?? ''}>{m.label}</option>
+ ))}
+ </Select>
+ <PixelButton
+ variant="secondary"
+ size="sm"
+ disabled={restarting === a.id}
+ onClick={async () => {
+ const currentProvider = inferAgentProvider(a.command, a.provider);
+ if (engineProvider !== currentProvider) {
+ if (!window.confirm("This restarts Michael; a conversation on a different engine can't be resumed.")) return;
+ }
+ await window.cth.updateConfig({ godProvider: engineProvider, godModel: engineModel });
+ await restartWithModel(a, engineModel, { provider: engineProvider, resume: false });
+ }}
+ >
+ {restarting === a.id ? 'restarting…' : 'apply'}
+ </PixelButton>
+ {/* Redraw a garbled terminal without losing the thread (resume the
+ SAME engine+model). Kept here since the god has no per-agent row above. */}
+ <PixelButton
+ variant="secondary"
+ size="sm"
+ disabled={restarting === a.id}
+ onClick={() => restartWithModel(a, a.model, { resume: true })}
+ >
+ <span title="Kill and respawn Michael, resuming the current conversation — fixes a corrupted/garbled terminal without losing context">
+ restart &amp; continue
+ </span>
+ </PixelButton>
+ </div>
+ )}
</div>
);
})}
diff --cc src/renderer/src/components/FullscreenTerminal.tsx
index 60350057,5f5ed250..943ea108
--- a/src/renderer/src/components/FullscreenTerminal.tsx
+++ b/src/renderer/src/components/FullscreenTerminal.tsx
@@@ -2,17 -3,135 +3,137 @@@ import { createPortal } from 'react-dom
import { PixelBadge } from './PixelBadge';
import { PixelButton } from './PixelButton';
import { PtyTerminalView } from './PtyTerminalView';
+ import { terminalInstanceKey } from './terminalRecovery';
import { MessageQueueComposer } from './MessageQueueComposer';
- import { disposeTerminal } from './terminalPool';
+ import { AgentControlStrip } from './AgentControlStrip';
+ import { CommandCenterPanel } from './CommandCenterPanel';
import { Icon } from './Icon';
import { SpritePortrait } from './SpritePortrait';
+import { RealtimeMichaelToggle } from './RealtimeMichaelToggle';
+import { CostHud } from '@/realtime/CostHud';
import { useStore, type Agent } from '@/store/store';
import { usePtyParser } from '@/hooks/usePtyParser';
+ import { useRestoreTeam } from '@/hooks/useRestoreTeam';
+ import { useTerminalFontSize } from './terminalFontSize';
+ import { useHasTerminalDraft } from './terminalPool';
+ import type { HarnessConfig } from '@/store/config';
- export function FullscreenTerminal() {
+ /** Roster rail width. A fixed 232px is right on a 14" laptop but reads as a
+ * sliver on a 27" display, where names truncate for no reason — so it tracks
+ * the viewport between those two ends. */
+ const SIDEBAR_WIDTH = 'clamp(232px, 14vw, 340px)';
+
+ /** Roster type scale, derived from the shared terminal zoom so Cmd +/- resizes
+ * the whole roster along with the terminal — one knob for the whole view
+ * instead of a size that only looked right on the display it was tuned on.
+ * Each is clamped: names are a pixel display face that turns to mush when it
+ * strays too far from its native size, and the bullets have to stay subordinate
+ * to the name however far the terminal is zoomed. */
+ function rosterScale(zoom: number) {
+ const clamp = (n: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, Math.round(n)));
+ return {
+ name: clamp(zoom * 0.48, 7, 14),
+ group: clamp(zoom * 0.45, 7, 13),
+ note: clamp(zoom * 0.68, 10, 20),
+ portrait: clamp(zoom * 1.2, 18, 40)
+ };
+ }
+
+ function basename(path: string): string {
+ // Split on BOTH separators: `git:mainRepo` hands back whatever the platform
+ // uses, and a Windows `C:\work\repo` contains no '/' at all — so a '/'-only
+ // split returned the whole absolute path as the group's "name".
+ return path.split(/[\\/]/).filter(Boolean).pop() ?? path;
+ }
+
+ /** cwd → main-repo basename, resolved once per path and shared by every mount.
+ * An isolated agent's cwd is its own git worktree (`…/worktrees/<agent-id>`),
+ * so naming the group after that path buckets each such agent under its own id
+ * instead of the repository the user actually picked. `git:mainRepo` follows a
+ * linked worktree back to its main checkout. */
+ const repoRootByCwd = new Map<string, string | null>();
+ /** cwds with a lookup in flight, so a re-render can't start a second one. */
+ const repoLookupsInFlight = new Set<string>();
+
+ /** Which repository an agent belongs to — the ABSOLUTE root, so it is a real
+ * identity. Two unrelated checkouts can share a basename (`~/client-a/app` and
+ * `~/client-b/app`); keying groups on the name merged them into one section and
+ * let agents be dragged between two different repositories.
+ *
+ * Falls back to the cwd itself until the async resolution lands, and for
+ * directories that aren't git repos at all. */
+ function repoKeyOf(agent: Agent): string {
+ return repoRootByCwd.get(agent.cwd) || agent.cwd || 'unknown';
+ }
+
+ /** What that group is CALLED — the basename, or the project the user picked. */
+ function repoLabelOf(agent: Agent): string {
+ const root = repoRootByCwd.get(agent.cwd);
+ if (root) return basename(root);
+ const project = agent.project?.trim();
+ if (project) return project;
+ return basename(agent.cwd) || 'unknown';
+ }
+
+ /** Resolve every distinct cwd's repository root, then re-render. Exactly one git
+ * call per distinct path, ever. */
+ function useResolvedRepoNames(agents: Agent[]): number {
+ const [version, setVersion] = useState(0);
+ useEffect(() => {
+ let cancelled = false;
+ const pending = [...new Set(agents.map(a => a.cwd).filter(Boolean))]
+ // `has` (not a truthiness check) so a resolved-to-null path — a cwd that
+ // is not a git repo — counts as answered. Caching only successes meant
+ // every agent outside a repo re-asked on each pass, and this effect
+ // depends on `agents`, which the pty parser replaces on every chunk of
+ // terminal output: one such agent spawned `git rev-parse` continuously
+ // for as long as it was talking. In-flight paths are skipped too, so a
+ // re-render mid-lookup doesn't stack a second round of subprocesses.
+ .filter(cwd => !repoRootByCwd.has(cwd) && !repoLookupsInFlight.has(cwd));
+ if (pending.length === 0) return;
+ pending.forEach(cwd => repoLookupsInFlight.add(cwd));
+ void Promise.all(pending.map(async (cwd) => {
+ try {
+ repoRootByCwd.set(cwd, (await window.cth.gitMainRepo(cwd)) || null);
+ } catch {
+ // Record the failure as answered as well — retrying a path that throws
+ // is what the unbounded-subprocess bug was made of.
+ repoRootByCwd.set(cwd, null);
+ } finally {
+ repoLookupsInFlight.delete(cwd);
+ }
+ })).then(() => { if (!cancelled) setVersion(v => v + 1); });
+ return () => { cancelled = true; };
+ }, [agents]);
+ return version;
+ }
+
+ /** The roster section an agent lives in — god agents share one ungrouped
+ * section, everyone else groups by repository. */
+ function groupKey(agent: Agent): string {
+ return agent.isGod ? '__god__' : repoKeyOf(agent);
+ }
+
+ /** Drag-reorder wiring handed down to each row. */
+ interface RowDrag {
+ dragId: string | null;
+ overId: string | null;
+ start: (id: string) => void;
+ over: (id: string) => void;
+ leave: (id: string) => void;
+ drop: (id: string) => void;
+ end: () => void;
+ }
+
+ export interface FullscreenTerminalProps {
+ /** Only needed to rebuild a spawn command for a restorable agent saved before
+ * the `command` field existed — same role as in AgentStrip. */
+ config?: HarnessConfig | null;
+ }
+
+ export function FullscreenTerminal({ config }: FullscreenTerminalProps) {
const agents = useStore(s => s.agents);
+ const restorableAgents = useStore(s => s.restorableAgents);
const fullscreenAgentId = useStore(s => s.fullscreenAgentId);
const setFullscreen = useStore(s => s.setFullscreen);
const select = useStore(s => s.select);
@@@ -234,8 -718,8 +720,14 @@@ function Header({ agent }: { agent: Age
fontSize: 13, color: 'var(--cth-ink-700)',
fontStyle: 'italic'
}}>“{agent.description}”</span>
-- <div style={{ marginLeft: 'auto' }}>
- <PixelBadge status={agent.status} />
++ <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 6 }}>
++ {/* Voice toggle is ALWAYS reachable in fullscreen — it controls Michael (the
++ god orchestrator) globally, not the agent in view, so users can start a
++ voice session even while a worker's terminal fills the screen. The cost
++ HUD stays Michael-only (it belongs to his card). */}
++ <RealtimeMichaelToggle />
++ {agent.isGod && <CostHud compact />}
+ <PixelBadge status={typing ? 'typing' : agent.status} />
</div>
</div>
);
diff --cc src/renderer/src/hooks/useHive.ts
index 3f9959a9,3184bba3..21d5091d
--- a/src/renderer/src/hooks/useHive.ts
+++ b/src/renderer/src/hooks/useHive.ts
@@@ -4,41 -4,25 +4,45 @@@ import
buildSpawnCommand,
ASSISTANT_MODEL,
inferAgentProvider,
+ isClaudeProvider,
+ tokenizeCommand,
type HarnessConfig
} from '@/store/config';
- import { acquireTerminal, resetTerminal } from '@/components/terminalPool';
-import { shouldAutoCompactContext } from '../../../shared/autoCompact';
+ import {
+ compactionCommandForProvider,
+ remoteControlCommandForProvider,
+ terminalReadyToReceive
+ } from '../../../shared/providerAutomation';
+ import type { AgentProvider } from '../../../shared/agentProvider';
-import { isTerminalAutomationSafe } from '@/components/terminalPool';
++import { acquireTerminal, resetTerminal, isTerminalAutomationSafe } from '@/components/terminalPool';
+ import { deliverWithAcknowledgement } from './queueDelivery';
+import { OFFICE_CAST, DEFAULT_CHARACTER } from '@/scene/office/cast';
const GOD_ID = 'god';
+/** Accent palette for MAIN-spawned (voice-hired) agents — picked deterministically
+ * from the agent id so the same agent always gets the same colour. Mirrors the
+ * AddAgentModal palette. */
+const SPAWN_ACCENTS = ['coral', 'mint', 'sky', 'lemon', 'lilac', 'peach'] as const;
const GOD_PTY = `pty-${GOD_ID}`;
- // How long to let Claude Code's TUI finish booting before we type the first
- // thing into Michael's terminal, and how long to PAUSE after the /remote-control
- // command so the slash command lands + executes on its own line before the
- // orientation prompt follows (otherwise they jam into one line and the TUI shows
- // "Unknown command: /remote-control…").
- const GOD_BOOT_MS = 4000;
const REMOTE_CONTROL_SETTLE_MS = 1500;
+// Provider-agnostic PTY-quiescence idle fallback (#2e). A non-Claude bridge that
+// fires a 'working' event but never its turn-end signal (Stop / session.idle /
+// agent_end) would pin the agent 'working' forever → the idle-only inbox-wake nudge
+// never fires → a god stops draining mail and the floor stalls. So a 'working'
+// agent whose PTY has emitted NOTHING for this window is treated as turn-done and
+// flipped idle. A streaming turn (incl. a long tool) keeps emitting bytes → stays
+// working; only true silence drifts it idle. Hook events still win — a fresh
+// PreToolUse/Stop refreshes status on the next event. Checked on QUIESCE_POLL_MS.
+const QUIESCE_IDLE_MS = 12000;
+const QUIESCE_POLL_MS = 4000;
// After a god/agent spawn, hold off the inbox-wake + queue-drain typers for this
- // long so they can't interleave with the boot sequence (remote-control +
- // orientation) and jam the input line.
- const BOOT_GRACE_MS = GOD_BOOT_MS + REMOTE_CONTROL_SETTLE_MS + 2500;
+ // long while the readiness handshake + provider-specific boot sequence runs.
+ const BOOT_GRACE_MS = 35_000;
++// Delay before typing a one-time TUI protocol seed into a fresh worker (3b) —
++// long enough for the TUI to finish painting and surface any permission prompt.
++// submitToPty additionally waits for the terminal's readiness handshake.
++const SEED_BOOT_MS = 12_000;
// The first thing Michael (god) is told on a fresh spawn — orient him and put
// him to work running the floor. Kept terse and action-oriented.
@@@ -297,21 -277,20 +319,26 @@@ export function useHive(config: Harness
// Michael until he's settled. The live-PTY branch above skips this entirely.
const resumedGod = res.resumed === true;
bootGraceUntil.current[GOD_ID] = Date.now() + BOOT_GRACE_MS;
- timers.push(setTimeout(() => {
- if (cancelled) return;
- // settleMs pauses the chain ~1.5s after /remote-control before the
- // orientation prompt (fresh spawns only) is submitted next.
- submitToPty(GOD_PTY, '/remote-control', REMOTE_CONTROL_SETTLE_MS).catch(() => { /* best-effort */ });
- if (!resumedGod) {
- // A type-into-tui god (Crush) can't ride its hive protocol on argv, so the
- // main process hands it back as seedPrompt — type it FIRST (identity), then
- // the orientation kick. Serialized via writeChains so they can't jam. (ondev-b)
- if (res.seedPrompt) submitToPty(GOD_PTY, res.seedPrompt).catch(() => { /* pty may have died */ });
- submitToPty(GOD_PTY, INITIAL_GOD_PROMPT).catch(() => { /* pty may have died */ });
- }
- }, GOD_BOOT_MS));
+ void (async () => {
+ try {
- const remoteCommand = remoteControlCommandForProvider('claude', 'Michael');
++ const remoteCommand = remoteControlCommandForProvider(godProvider, 'Michael');
+ if (remoteCommand) {
- await submitToPty(GOD_PTY, remoteCommand, 'claude', REMOTE_CONTROL_SETTLE_MS);
++ // settleMs pauses the chain ~1.5s after /remote-control before the
++ // orientation prompt (fresh spawns only) is submitted next.
++ await submitToPty(GOD_PTY, remoteCommand, godProvider, REMOTE_CONTROL_SETTLE_MS);
+ }
+ if (!cancelled && !resumedGod) {
- await submitToPty(GOD_PTY, INITIAL_GOD_PROMPT, 'claude');
++ // A type-into-tui god (Crush) can't ride its hive protocol on argv, so the
++ // main process hands it back as seedPrompt — type it FIRST (identity), then
++ // the orientation kick. Serialized via writeChains so they can't jam. (ondev-b)
++ if (res.seedPrompt) await submitToPty(GOD_PTY, res.seedPrompt, godProvider);
++ await submitToPty(GOD_PTY, INITIAL_GOD_PROMPT, godProvider);
+ }
+ } catch { /* PTY may have died during startup */ }
+ finally { bootGraceUntil.current[GOD_ID] = 0; }
+ })();
}, 1200);
- return () => { cancelled = true; clearTimeout(t); timers.forEach(clearTimeout); };
+ return () => { cancelled = true; clearTimeout(t); };
}, [config?.onboardingComplete, config?.harnessHome]);
// 2) Drive avatars from real hook events emitted by each agent's shim.
@@@ -474,45 -453,18 +501,55 @@@
});
}, [config?.onboardingComplete]);
+ // 2e) PROVIDER-AGNOSTIC PTY-QUIESCENCE IDLE FALLBACK (the linchpin that makes
+ // canReceiveInbox:true safe for the live-unverified OpenCode/Crush/pi bridges).
+ // Hook events are the authoritative status source, but a bridge whose turn-end
+ // signal (Stop/session.idle/agent_end) doesn't fire leaves the agent pinned
+ // 'working' — and BOTH delivery paths (#3 nudge, #4 queue-drain) are idle-gated,
+ // so the agent silently stops draining mail. usePtyParser has a 4s idle drift,
+ // but it's Claude-TUI-tuned AND only runs for the mounted terminal — a
+ // backgrounded god gets none. This is the floor-wide, provider-agnostic backstop:
+ // it reads each live PTY's lastOutputAt (already tracked in the main process) and
+ // flips any 'working' agent quiet for QUIESCE_IDLE_MS to idle so the nudge can
+ // drain it. Safe because a genuinely-working agent (incl. a long streaming tool)
+ // keeps emitting bytes; a false idle self-corrects on the next hook event.
+ useEffect(() => {
+ if (!config?.onboardingComplete) return;
+ const iv = setInterval(async () => {
+ const ptys = await window.cth.listPtys().catch(() => []);
+ if (!ptys.length) return;
+ const lastOut: Record<string, number> = {};
+ for (const p of ptys) lastOut[p.id] = p.lastOutputAt;
+ const now = Date.now();
+ const { agents, updateAgent } = useStore.getState();
+ for (const a of agents) {
+ if (!a.ptyId || a.status !== 'working') continue;
+ // Never fight the breaker pin (a constrained/stopped agent stays 'looping')
+ // or a still-booting agent (its boot sequence is mid-type).
+ const bl = breakerLevel.current[a.id];
+ if (bl === 'constrained' || bl === 'stopped') continue;
+ if ((bootGraceUntil.current[a.id] ?? 0) > now) continue;
+ const last = lastOut[a.ptyId];
+ if (typeof last === 'number' && last > 0 && now - last > QUIESCE_IDLE_MS) {
+ updateAgent(a.id, { status: 'idle', action: 'idle', carrying: undefined });
+ }
+ }
+ }, QUIESCE_POLL_MS);
+ return () => 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.
+ // 3) Wake agents holding unread inbox messages. The assistant is send-only
+ // (it never receives inbox mail), so it's excluded.
+ //
+ // QUEUES the nudge rather than typing it. This loop used to write straight
+ // into the terminal, which made it the one automatic writer that could land
+ // on top of whatever the user was typing — its text fused onto the user's
+ // half-written line and the pair got submitted as one garbled prompt. Going
+ // through the queue means effect #4 owns every decision about when a
+ // terminal may be typed into: idle, off cooldown, past boot grace, delivery
+ // not paused, and no user draft in the way. One gate, one place, and this
+ // loop stops needing prompt logic of its own. /compact (effect #6) has
+ // always worked this way.
useEffect(() => {
if (!config?.onboardingComplete) return;
const iv = setInterval(async () => {
@@@ -554,47 -492,6 +577,48 @@@
return () => clearInterval(iv);
}, [config?.onboardingComplete]);
+ // 3b) Seed a fresh "type-into-tui" worker (Crush) with the hive protocol. Its
+ // bare TUI rejects a positional seed (Cobra reads it as a subcommand →
+ // `Unknown command`), so the main process spawns it bare and hands the
+ // protocol back as `seedPrompt`; we TYPE it as the worker's first turn after a
+ // boot-grace (TUI finished painting), ONCE per agent. Routed through the SAME
+ // per-pty submit chain + boot-grace as the inbox-wake nudge so the seed and a
+ // nudge can never jam onto one line. (god-as-Crush is seeded in its own boot
+ // sequence above; this covers workers.) (ondev-b)
+ useEffect(() => {
+ if (!config?.onboardingComplete) return;
+ const iv = setInterval(() => {
+ const { agents, updateAgent } = useStore.getState();
+ for (const a of agents) {
+ if (!a.ptyId || a.isGod || !a.seedPrompt || seeded.current.has(a.id)) continue;
+ seeded.current.add(a.id);
+ const ptyId = a.ptyId;
+ const seed = a.seedPrompt;
+ // Hold the nudge/quiesce typers off this agent until the seed lands + settles.
+ bootGraceUntil.current[a.id] = Date.now() + BOOT_GRACE_MS;
+ // Clear the record now so it isn't re-seen (the ref also guards) or persisted.
+ updateAgent(a.id, { seedPrompt: undefined });
+ setTimeout(() => {
+ // Permission-prompt safety (#5): if the worker surfaced an approval /
+ // needs-human prompt while its TUI booted ('waiting'/'blocked'), the
+ // seed's trailing Enter would confirm it. Put the seed back and let a
+ // later tick retry once the prompt clears; if the agent vanished
+ // (killed mid-boot), don't type into its orphaned pty at all.
+ const live = useStore.getState().agents.find((x) => x.id === a.id);
+ if (!live) return;
+ if (live.status === 'waiting' || live.status === 'blocked') {
+ seeded.current.delete(a.id);
+ useStore.getState().updateAgent(a.id, { seedPrompt: seed });
+ return;
+ }
- submitToPty(ptyId, seed).catch(() => { /* pty may have died */ });
- }, GOD_BOOT_MS);
++ submitToPty(ptyId, seed, inferAgentProvider(live.command, live.provider))
++ .catch(() => { /* pty may have died */ });
++ }, SEED_BOOT_MS);
+ }
+ }, 1500);
+ return () => clearInterval(iv);
+ }, [config?.onboardingComplete]);
+
// 4) Drain each agent's queued messages to its terminal, one at a time, the
// moment the agent goes idle. This is what lets the user keep sending
// messages while the agent's "cloud terminal" is mid-run: the messages
@@@ -602,66 -499,59 +626,85 @@@
useEffect(() => {
if (!config?.onboardingComplete) return;
const FLUSH_COOLDOWN_MS = 4500;
+ // A message that fails this many PTY writes (dead/crashed pty that the store
+ // still thinks is idle) is dropped WITH a console.warn — bounded so the drain
- // never spins forever on a corpse, loud so the loss is diagnosable.
++ // never spins forever on a corpse, loud so the loss is diagnosable. (#113)
+ const MAX_SEND_ATTEMPTS = 3;
+ const inFlight = new Set<string>();
++ const sendFailures: Record<string, number> = {};
// Send the front of `srcId`'s queue into `target`'s pty (verbatim or wrapped),
- // gated on the target being idle + off cooldown. Keyed cooldown per target so
- // strict one-by-one delivery holds. Returns true if it INITIATED a send (the
- // message is only removed from the queue once the write chain resolves).
- const dispatch = (srcId: string, target: Agent | undefined, wrap?: (m: QueuedMessage) => string): boolean => {
- const { messageQueues } = useStore.getState();
+ // gated on the target being idle, free of interactive menus, and off
+ // cooldown. The queue item is acknowledged only after BOTH PTY writes
- // succeed; failures stay visible and retry automatically.
++ // succeed; failures stay visible and retry automatically (bounded by
++ // MAX_SEND_ATTEMPTS so the drain never spins forever on a corpse).
+ const dispatch = async (
+ srcId: string,
+ target: Agent | undefined,
+ wrap?: (m: QueuedMessage) => string
+ ): Promise<{ sent: boolean; message?: QueuedMessage }> => {
+ const { messageQueues, removeQueuedMessage } = useStore.getState();
const next = messageQueues[srcId]?.[0];
- if (!next || !target?.ptyId || target.status !== 'idle') return false;
- // Already mid-write — the head hasn't been confirmed delivered yet.
- if (inFlightSends.current.has(next.id)) return false;
+ if (!next || !target?.ptyId || target.status !== 'idle') return { sent: false };
const now = Date.now();
+ const control = await window.cth.controlSnapshot(target.id);
+ if (control?.autoDeliveryPaused) return { sent: false };
// Hold queued messages until the target finishes its boot sequence.
- if ((bootGraceUntil.current[target.id] ?? 0) >= now) return false;
- if (now - (lastFlush.current[target.id] ?? 0) < FLUSH_COOLDOWN_MS) return false;
+ if ((bootGraceUntil.current[target.id] ?? 0) >= now) return { sent: false };
+ // The user owns the prompt: a draft they are writing, or a menu they
+ // opened, holds delivery. Both blocks expire after half an hour, and when
+ // one does we simply type after whatever is there — automation never
+ // erases the user's text and never closes the user's menu.
+ if (!isTerminalAutomationSafe(target.ptyId, now)) return { sent: false };
+ if (now - (lastFlush.current[target.id] ?? 0) < FLUSH_COOLDOWN_MS) return { sent: false };
+ const flightKey = `${srcId}:${next.id}`;
+ if (inFlight.has(flightKey)) return { sent: false };
+ inFlight.add(flightKey);
lastFlush.current[target.id] = now;
- // Remove only AFTER the write chain confirms delivery (#36). The old
- // remove-first ordering + writePty's resolve-on-{ok:false} contract meant a
- // message to a crashed-but-'idle' agent was popped, the write failed, and
- // nothing ever heard about it — one message silently destroyed per cooldown.
- // Double-send safety now comes from inFlightSends + the cooldown above.
- inFlightSends.current.add(next.id);
- const ptyId = target.ptyId;
- const targetId = target.id;
- // `instruction` (when present) is the authoritative text to type into the
- // PTY — e.g. Slack-origin work carries the autonomy preamble there while the
- // kanban card keeps `text` (raw) as its readable title. UI/card surfaces
- // never read `instruction`, so this stays invisible to the human board.
- submitToPty(ptyId, wrap ? wrap(next) : (next.instruction ?? next.text))
- .then(() => {
- inFlightSends.current.delete(next.id);
- delete sendFailures.current[next.id];
- useStore.getState().removeQueuedMessage(srcId, next.id);
- // Zero the gauge on a DELIVERED /clear — the new session's context isn't
- // known until statusLine fires after the first post-clear response, so
- // leaving it at the old value shows a stale-full bar during that window.
- if (next.text.trim().toLowerCase() === '/clear') {
- useStore.getState().updateAgent(targetId, { contextTokens: 0, contextLimit: undefined, progress: 0 });
- }
- })
- .catch((err) => {
- inFlightSends.current.delete(next.id);
- const attempts = (sendFailures.current[next.id] ?? 0) + 1;
- sendFailures.current[next.id] = attempts;
- if (attempts >= MAX_SEND_ATTEMPTS) {
- delete sendFailures.current[next.id];
- useStore.getState().removeQueuedMessage(srcId, next.id);
- console.warn(
- `[queue-drain] dropping message ${next.id} for ${targetId} after ${attempts} failed pty writes ` +
- `("${next.text.slice(0, 80)}${next.text.length > 80 ? '…' : ''}")`,
- err
- );
+ try {
+ const sent = await deliverWithAcknowledgement(
+ // `instruction` (when present) is the authoritative text to type into
+ // the PTY; UI/card surfaces continue to show the readable `text`.
+ () => submitToPty(
+ target.ptyId!,
+ wrap ? wrap(next) : (next.instruction ?? next.text),
+ inferAgentProvider(target.command, target.provider)
+ ),
+ () => {
+ removeQueuedMessage(srcId, next.id);
++ // Zero the gauge on a DELIVERED /clear — the new session's context
++ // isn't known until statusLine fires after the first post-clear
++ // response, so leaving it at the old value shows a stale-full bar.
+ if (next.text.trim().toLowerCase() === '/clear') {
+ useStore.getState().updateAgent(target.id, {
+ contextTokens: 0,
+ contextLimit: undefined,
+ progress: 0
+ });
+ }
}
- // else: still queued — the cooldown-spaced flush retries it.
- });
- return true;
+ );
- return sent ? { sent: true, message: next } : { sent: false };
++ if (sent) {
++ delete sendFailures[next.id];
++ return { sent: true, message: next };
++ }
++ // Failed write (dead/crashed pty the store still thinks is idle): retry
++ // on the next cooldown-spaced flush, but only MAX_SEND_ATTEMPTS times —
++ // then drop LOUDLY so the loss is diagnosable. (#113/#36)
++ const attempts = (sendFailures[next.id] ?? 0) + 1;
++ sendFailures[next.id] = attempts;
++ if (attempts >= MAX_SEND_ATTEMPTS) {
++ delete sendFailures[next.id];
++ removeQueuedMessage(srcId, next.id);
++ console.warn(
++ `[queue-drain] dropping message ${next.id} for ${target.id} after ${attempts} failed pty writes ` +
++ `("${next.text.slice(0, 80)}${next.text.length > 80 ? '…' : ''}")`
++ );
++ }
++ return { sent: false };
+ } finally {
+ inFlight.delete(flightKey);
+ }
};
// Promote a genuine Slack-origin work item to a stamped kanban card the first
@@@ -824,12 -671,19 +868,12 @@@
const { agents, messageQueues, enqueueMessage } = useStore.getState();
for (const a of agents) {
if (!a.ptyId) continue;
- // /compact is a Claude Code slash command — non-Claude CLIs (agy, codex)
- // would just receive it as literal prompt text. Skip them.
- if (!isClaudeProvider(inferAgentProvider(a.command, a.provider))) continue;
+ const provider = inferAgentProvider(a.command, a.provider);
+ const compactCommand = compactionCommandForProvider(provider);
+ if (!compactCommand) continue;
- // Only compact agents whose context has actually filled past the
- // threshold. contextLimit is per-model (200k vs the 1M window), so this
- // gate scales to each agent's own window instead of a fixed token count.
- // Unknown telemetry (limit not polled yet) ⇒ skip — never compact blind.
- const limit = a.contextLimit ?? 0;
- const used = a.contextTokens ?? 0;
- if (!shouldAutoCompactContext(used, limit)) continue;
const queued = messageQueues[a.id] ?? [];
if (queued.some((m) => m.text.trimStart().startsWith('/compact'))) continue;
- enqueueMessage(a.id, COMPACT_CMD);
+ enqueueMessage(a.id, compactCommand);
}
});
}, [config?.onboardingComplete]);
diff --cc src/renderer/src/hooks/useRestoreTeam.ts
index 00000000,be506c19..eabf61b6
mode 000000,100644..100644
--- a/src/renderer/src/hooks/useRestoreTeam.ts
+++ b/src/renderer/src/hooks/useRestoreTeam.ts
@@@ -1,0 -1,245 +1,249 @@@
+ import { useEffect, useSyncExternalStore } from 'react';
+ import { useStore, type Agent } from '@/store/store';
+ import { buildSpawnCommand, inferAgentProvider, tokenizeCommand, type HarnessConfig } from '@/store/config';
+
+ /** "Restore team" — respawn every worker from the previous session.
+ *
+ * Lives here rather than inside AgentStrip because the floor strip is hidden in
+ * fullscreen, which used to mean the restore button (and the list of restorable
+ * agents) simply vanished when you went fullscreen. Both mount points share the
+ * progress state below, so a restore kicked off from one view shows as running
+ * in the other and can't be double-started. */
+
+ let restoring = false;
+ let note: string | null = null;
+ /** True only while the AUTOMATIC boot restore is in flight, so the UI can say
+ * "this is happening on its own" rather than looking like a click you don't
+ * remember making. */
+ let autoRestoring = false;
+ /** Latched the moment the automatic restore starts. Module-level, not per
+ * component: `useRestoreTeam` is mounted from both the floor strip and the
+ * fullscreen rail, and without this each of them would kick off its own. */
+ let autoStarted = false;
+ const listeners = new Set<() => void>();
+
+ /** How long to wait after boot before restoring on our own.
+ *
+ * App.tsx reconciles the persisted roster against the PTYs actually alive in
+ * the main process, and that is an async round trip. Firing before it lands
+ * would read a restorable list that still contains agents whose terminals are
+ * already running, and try to spawn duplicates of them. The delay is also the
+ * window in which you can hit a dismiss ✕ if you don't want an agent back. */
+ export const AUTO_RESTORE_DELAY_MS = 2500;
+
+ function emit(): void {
+ for (const l of [...listeners]) l();
+ }
+
+ function subscribe(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => { listeners.delete(listener); };
+ }
+
+ // useSyncExternalStore requires a stable snapshot identity — returning a fresh
+ // object each call would loop forever, so the two fields are read separately.
+ const getRestoring = (): boolean => restoring;
+ const getNote = (): string | null => note;
+ const getAutoRestoring = (): boolean => autoRestoring;
+
+ export interface RestoreTeamState {
+ restoring: boolean;
+ /** True when the run in flight was started automatically at boot, not by a
+ * click. Drives the "restoring your team…" banner. */
+ autoRestoring: boolean;
+ /** Outcome of the last run ("restored 3 · 1 failed — …"), or null. */
+ restoreNote: string | null;
+ restoreTeam: () => Promise<void>;
+ }
+
+ /**
+ * @param config used only to rebuild a spawn command for a restorable agent
+ * persisted before the `command` field existed.
+ */
+ export function useRestoreTeam(config?: HarnessConfig | null): RestoreTeamState {
+ const isRestoring = useSyncExternalStore(subscribe, getRestoring, getRestoring);
+ const restoreNote = useSyncExternalStore(subscribe, getNote, getNote);
+ const isAutoRestoring = useSyncExternalStore(subscribe, getAutoRestoring, getAutoRestoring);
+
+ /** Respawn every worker from the previous session with its ORIGINAL agent id,
+ * cwd, model and command — the hive workspace (memory.md, inbox, registry
+ * entry) reattaches by itself, no memory transplant needed. */
+ const restoreTeam = async (): Promise<void> => {
+ if (restoring) return;
+ restoring = true;
+ note = null;
+ emit();
+ const prevSel = useStore.getState().selectedId;
+ const restorableAgents = useStore.getState().restorableAgents;
+ // Tally every agent's outcome so the run ALWAYS leaves a visible trace — the
+ // original bug was that every failure path was console-only, so a click that
+ // couldn't spawn anything looked like a dead button.
+ let restored = 0;
+ let alreadyLive = 0;
+ const failures: string[] = [];
+ try {
+ // Restore every agent CONCURRENTLY. Each spawn is keyed by its own ptyId and
+ // touches no cross-agent state in the renderer, and in the main process the
+ // whole `pty:spawn` handler (hive registry read-modify-write included) runs
+ // synchronously between awaits, so concurrent handlers can't interleave
+ // mid-update. Serially this cost the sum of every agent's git probe + spawn;
+ // a 6-agent team took ~6× one agent for no reason.
+ // Spawns run concurrently but agents are ADDED in roster order afterwards.
+ // Calling addAgent from inside each spawn made completion timing decide
+ // the roster order — and that order is persisted, so a slow provider or a
+ // slow git probe silently overwrote the sequence the user had dragged the
+ // cards into.
+ const restoredInOrder = await Promise.all([...restorableAgents].map(async (a): Promise<Agent | null> => {
+ // Per-agent guard: one agent's failure (or a rejected IPC call) must NEVER
+ // abort the others — an unhandled rejection here used to make the
+ // entire restore a silent no-op after the first bad agent.
+ try {
+ const provider = inferAgentProvider(a.command, a.provider);
+ const command = (a.command ?? '').trim() || (config ? buildSpawnCommand(config, a.model, provider) : '');
+ if (!command || !a.cwd) {
+ // No spawn recipe (an old entry persisted before `command`, with no
+ // config to rebuild one). Keep it restorable and SAY why rather than
+ // silently dropping it — silent removal read as "nothing happened".
+ failures.push(`${a.name}: no saved command`);
+ return null;
+ }
+ const [exe, ...args] = tokenizeCommand(command);
+ const ptyId = a.ptyId ?? `pty-${a.id}`;
+ // An isolated agent's worktree SURVIVES an app restart on disk (it's only
+ // torn down on per-tab close / mid-session exit, not on quit). So re-enter
+ // that exact worktree as the cwd rather than re-isolating — `git worktree
+ // add` would conflict with the existing path/branch, and re-isolating would
+ // also lose the worktree's uncommitted work. cwd = the worktree means
+ // resume + seedSessionTranscript land in the CORRECT checkout.
+ // But the user may have manually pruned/deleted the worktree between runs —
+ // gitIsRepo (git rev-parse) returns false for a missing/invalid dir, so
+ // fall back to the base repo cwd rather than spawning into a dead path.
+ let cwd = a.cwd;
+ let worktreeGone = false;
+ if (a.worktreePath) {
+ if (await window.cth.gitIsRepo(a.worktreePath)) {
+ cwd = a.worktreePath;
+ } else {
+ worktreeGone = true;
+ console.warn(`[restore] worktree gone for ${a.id} (${a.worktreePath}); falling back to base repo ${a.cwd}`);
+ }
+ }
+ const res = await window.cth.spawnPty({
+ id: ptyId,
+ cwd,
+ command: exe,
+ provider,
+ args,
+ cols: 100,
+ rows: 30,
+ // Worktree (if any) already exists on disk — cd into it, don't create a
+ // new one (re-isolating would conflict on the existing path/branch and
+ // lose its uncommitted work).
+ isolate: false,
+ // Continue the worker's prior CLI session if one was recorded — the
+ // main process picks the provider's resume flag (Claude --resume,
+ // agy --conversation) and for Claude reattaches the transcript. The
+ // agent id is preserved across restart, so its registry entry,
+ // memory.md and inbox reattach by id. No-op without a recorded session.
+ resume: true,
+ hive: { id: a.id, name: a.name, provider, cwd, role: a.description }
+ });
+ if (res.ok) {
+ restored++;
+ return {
+ ...a,
+ provider,
+ ptyId,
+ archived: false,
+ status: 'idle',
+ // Surface the worktree fallback on the floor card; otherwise normal.
+ action: worktreeGone ? 'worktree gone — using base repo' : 'starting up',
+ // The worktree is no longer on disk — drop it so this agent is treated
+ // as a plain base-cwd agent going forward (a future restore won't keep
+ // re-probing a dead path).
+ worktreePath: worktreeGone ? undefined : a.worktreePath,
++ // Crush spawns bare (no positional protocol) and hands the seed back
++ // here; useHive types it after boot. Re-seeding a resumed worker is
++ // idempotent (it just re-reads its inbox per protocol). (ondev-b)
++ seedPrompt: res.seedPrompt,
+ carrying: undefined,
+ currentStation: 'desk',
+ recentTextTs: Date.now()
+ };
+ } else if ((res.error ?? '').includes('already exists')) {
+ // A live PTY with this id is already running (e.g. respawned at boot or
+ // by another path) — the agent isn't actually missing, so retire it from
+ // the restorable list rather than reporting a phantom failure.
+ alreadyLive++;
+ useStore.getState().removeRestorableAgent(a.id);
+ } else {
+ // Leave it restorable so the user can retry — but record WHY so the
+ // outcome is shown on the floor, not buried in the devtools console.
+ failures.push(`${a.name}: ${res.error ?? 'spawn failed'}`);
+ console.error('[restore] spawn failed for', a.id, res.error);
+ }
+ } catch (e) {
+ failures.push(`${a.name}: ${e instanceof Error ? e.message : String(e)}`);
+ console.error('[restore] error for', a.id, e);
+ }
+ return null;
+ }));
+ // Add in the ORIGINAL roster order, not completion order.
+ for (const restoredAgent of restoredInOrder) {
+ if (restoredAgent) useStore.getState().addAgent(restoredAgent);
+ }
+ } finally {
+ // addAgent auto-selects each spawn; put the user back where they were.
+ const sel = useStore.getState();
+ if (prevSel && sel.agents.some((x) => x.id === prevSel)) sel.select(prevSel);
+ restoring = false;
+ // ALWAYS surface a result so the button can never look inert.
+ const parts: string[] = [];
+ if (restored) parts.push(`restored ${restored}`);
+ if (alreadyLive) parts.push(`${alreadyLive} already live`);
+ if (failures.length) parts.push(`${failures.length} failed — ${failures.join('; ')}`);
+ note = parts.length ? parts.join(' · ') : 'nothing to restore';
+ emit();
+ }
+ };
+
+ // Restore the previous session's team on open, without waiting for a click.
+ //
+ // Deliberately driven by a store SUBSCRIPTION rather than a plain timer: the
+ // restorable list is empty on the first render and only fills once App.tsx's
+ // PTY reconcile resolves, so a timer started at mount would look at an empty
+ // list, decide there was nothing to do, and never look again.
+ //
+ // Only ever fires for agents already on the restorable list — i.e. ones that
+ // had a terminal open when the app last quit. Archived agents (closed tabs)
+ // are never touched.
+ useEffect(() => {
+ if (autoStarted || !config?.onboardingComplete) return;
+ let timer: ReturnType<typeof setTimeout> | null = null;
+
+ const check = (): void => {
+ if (autoStarted || restoring || timer) return;
+ if (!useStore.getState().restorableAgents.length) return;
+ timer = setTimeout(() => {
+ timer = null;
+ if (autoStarted || restoring) return;
+ if (!useStore.getState().restorableAgents.length) return;
+ // Latch BEFORE the await so the other mount point's timer, which may
+ // fire in this same tick, sees it.
+ autoStarted = true;
+ autoRestoring = true;
+ emit();
+ void restoreTeam().finally(() => { autoRestoring = false; emit(); });
+ }, AUTO_RESTORE_DELAY_MS);
+ };
+
+ check();
+ const unsub = useStore.subscribe(check);
+ return () => { unsub(); if (timer) clearTimeout(timer); };
+ // restoreTeam is rebuilt every render but only ever called from inside the
+ // timer, so it is read fresh at call time and does not belong in the deps.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [config?.onboardingComplete]);
+
+ return { restoring: isRestoring, autoRestoring: isAutoRestoring, restoreNote, restoreTeam };
+ }
diff --cc src/renderer/src/store/config.ts
index fb866a3d,aef6fb8c..eb6e406b
--- a/src/renderer/src/store/config.ts
+++ b/src/renderer/src/store/config.ts
@@@ -137,20 -114,6 +145,18 @@@ export const AGENT_MODELS: ModelOption[
{ id: 'claude-haiku-4-5-20251001', label: 'Haiku 4.5' }
];
- /** Models offered when an agent runs on the OpenAI Codex CLI (`codex`). Codex's
- * `--model` takes a model slug (e.g. `codex --model o4-mini`). These are the
- * curated suggestions surfaced in the picker — the command field stays editable,
- * and `codex --model <id>` is the source of truth. // TODO-verify the exact live
- * slug list once the codex CLI can be installed to confirm. */
++/** Current OpenAI models offered by Codex for coding agents. The command field
++ * stays editable and `codex --model <id>` is the source of truth. */
+export const CODEX_MODELS: ModelOption[] = [
- { id: undefined, label: 'default' },
- { id: 'gpt-5-codex', label: 'GPT-5 Codex' },
- { id: 'gpt-5', label: 'GPT-5' },
- { id: 'gpt-5-mini', label: 'GPT-5 Mini' },
- { id: 'o4-mini', label: 'o4-mini' },
- { id: 'o3', label: 'o3' }
++ // No `--model` flag at all — whatever the CLI itself defaults to. NOT the
++ // harness's `config.defaultModel`; the pickers mark that one separately, and
++ // labelling both "default" is what made the two impossible to tell apart.
++ { id: undefined, label: 'CLI default' },
++ { id: 'gpt-5.6-sol', label: 'GPT-5.6 Sol' },
++ { id: 'gpt-5.6-terra', label: 'GPT-5.6 Terra' },
++ { id: 'gpt-5.6-luna', label: 'GPT-5.6 Luna' }
+];
+
/** Models offered when an agent runs on the Antigravity CLI (`agy`). agy's
* `--model` takes the DISPLAY-NAME LABEL exactly as `agy models` prints it
* (verified: agy logs `Propagating selected model override … label="…"`), not a
@@@ -169,74 -135,37 +178,94 @@@ export const ANTIGRAVITY_MODELS: ModelO
{ id: 'GPT-OSS 120B (Medium)', label: 'GPT-OSS 120B' }
];
-/** Current OpenAI models offered by Codex for coding agents. */
-export const CODEX_MODELS: ModelOption[] = [
- // No `--model` flag at all — whatever the CLI itself defaults to. NOT the
- // harness's `config.defaultModel`; the pickers mark that one separately, and
- // labelling both "default" is what made the two impossible to tell apart.
- { id: undefined, label: 'CLI default' },
- { id: 'gpt-5.6-sol', label: 'GPT-5.6 Sol' },
- { id: 'gpt-5.6-terra', label: 'GPT-5.6 Terra' },
- { id: 'gpt-5.6-luna', label: 'GPT-5.6 Luna' }
+/** Models offered when an agent runs on qwen-code (`qwen`), the proxy-bridge CLI
+ * driving an OpenAI-compatible endpoint. Starting suggestions only (editable
+ * command field). // TODO-verify the live list (`qwen` model ids). */
+export const QWEN_MODELS: ModelOption[] = [
+ { id: undefined, label: 'default' },
+ { id: 'qwen3-coder-plus', label: 'Qwen3 Coder Plus' },
+ { id: 'qwen3-coder', label: 'Qwen3 Coder' },
+ { id: 'qwen-max', label: 'Qwen Max' }
+];
+
+/** Models offered when an agent runs on OpenCode (`opencode`). OpenCode's `--model`
+ * takes a `provider/model` slug; these are curated BYOK suggestions (the command
+ * field stays editable; `opencode models` / models.dev is the source of truth).
+ * // TODO-verify exact live slugs (humanQA — they drift). */
+export const OPENCODE_MODELS: ModelOption[] = [
+ { id: undefined, label: 'default' },
+ { id: 'anthropic/claude-sonnet-4-5', label: 'Claude Sonnet 4.5 (Anthropic)' },
+ { id: 'anthropic/claude-haiku-4-5', label: 'Claude Haiku 4.5 (Anthropic)' },
+ { id: 'openai/gpt-5', label: 'GPT-5 (OpenAI)' },
+ { id: 'openai/gpt-5-mini', label: 'GPT-5 mini (OpenAI)' },
+ { id: 'openrouter/anthropic/claude-sonnet-4.5', label: 'Claude Sonnet 4.5 (OpenRouter)' },
+ { id: 'google/gemini-2.5-pro', label: 'Gemini 2.5 Pro (Google)' },
+ { id: 'local/llama3', label: 'Local · OpenAI-compatible (set base-URL)' }
+];
+
+/** Models offered when an agent runs on Crush (`crush`). Crush's `--model` takes a
+ * `provider/model-id` slug; free-text editable (Crush accepts arbitrary slugs).
+ * // TODO-verify exact live ids (humanQA). */
+export const CRUSH_MODELS: ModelOption[] = [
+ { id: undefined, label: 'Crush default (config)' },
+ { id: 'anthropic/claude-sonnet-4-5', label: 'Claude Sonnet 4.5 (Anthropic)' },
+ { id: 'anthropic/claude-opus-4-1', label: 'Claude Opus (Anthropic)' },
+ { id: 'openai/gpt-4o', label: 'GPT-4o (OpenAI)' },
+ { id: 'openai/o3', label: 'o3 (OpenAI)' },
+ { id: 'gemini/gemini-2.5-pro', label: 'Gemini 2.5 Pro' },
+ { id: 'openrouter/auto', label: 'OpenRouter (auto)' },
+ // OpenAI-wire local slug so traffic routes through the proxy (the harness overrides
+ // the `openai` provider's base_url → loopback → your configured Crush base-URL).
+ // An `ollama/*` slug would bypass the proxy (Dwight verify-crush NIT-2).
+ { id: 'openai/local', label: 'Local · OpenAI-compatible (set base-URL)' }
+];
+
+/** Models offered when an agent runs on Pi (`pi`). Pi's `--model` takes a
+ * `provider/model` slug (thinking via a `:high` suffix). Curated BYOK suggestions;
+ * free-text editable. // TODO-verify exact live slugs (humanQA). */
+export const PI_MODELS: ModelOption[] = [
+ { id: undefined, label: 'default' },
+ { id: 'anthropic/claude-sonnet-4-5', label: 'Claude Sonnet 4.5 (Anthropic)' },
+ { id: 'anthropic/claude-opus-4-1', label: 'Claude Opus (Anthropic)' },
+ { id: 'openai/gpt-5', label: 'GPT-5 (OpenAI)' },
+ { id: 'google/gemini-2.5-pro', label: 'Gemini 2.5 Pro (Google)' },
+ { id: 'groq/llama-3.3-70b', label: 'Llama 3.3 70B (Groq)' },
+ { id: 'local/llama3', label: 'Local · OpenAI-compatible (set base-URL)' }
+];
+
+/** Models offered when an agent runs on GitHub Copilot (`copilot`). Copilot's
+ * `--model` takes a plain model id ('auto' lets Copilot pick); these are curated
+ * suggestions and the command field stays editable. // TODO-verify exact live ids
+ * (the /model picker is the source of truth; they drift). */
+export const COPILOT_MODELS: ModelOption[] = [
+ { id: undefined, label: 'default (Claude Sonnet 4.5)' },
+ { id: 'auto', label: 'Auto (Copilot picks)' },
+ { id: 'claude-sonnet-4.5', label: 'Claude Sonnet 4.5' },
+ { id: 'claude-sonnet-4', label: 'Claude Sonnet 4' },
+ { id: 'gpt-5.4', label: 'GPT-5.4' },
+ { id: 'gpt-5', label: 'GPT-5' }
];
+ /** Models reported by the installed Grok CLI (`grok models`). */
+ export const GROK_MODELS: ModelOption[] = [
+ // No `--model` flag at all — whatever the CLI itself defaults to. NOT the
+ // harness's `config.defaultModel`; the pickers mark that one separately, and
+ // labelling both "default" is what made the two impossible to tell apart.
+ { id: undefined, label: 'CLI default' },
+ { id: 'grok-4.5', label: 'Grok 4.5' }
+ ];
+
+ /** Managed Kimi Code aliases accepted by `kimi --model <alias>`. */
+ export const KIMI_MODELS: ModelOption[] = [
+ // No `--model` flag at all — whatever the CLI itself defaults to. NOT the
+ // harness's `config.defaultModel`; the pickers mark that one separately, and
+ // labelling both "default" is what made the two impossible to tell apart.
+ { id: undefined, label: 'CLI default' },
+ { id: 'kimi-code/k3', label: 'Kimi K3' },
+ { id: 'kimi-code/kimi-for-coding', label: 'Kimi K2.7 Code' },
+ { id: 'kimi-code/kimi-for-coding-highspeed', label: 'Kimi K2.7 · HighSpeed' }
+ ];
+
/** Split a command string into argv, respecting double/single quotes so a model
* value with spaces (agy's `--model "Gemini 3.1 Pro (High)"`) stays one token.
* Quotes are stripped from the result. */
@@@ -250,16 -179,47 +279,50 @@@ export function tokenizeCommand(command
/** The model preset list for a given provider's picker. */
export function modelsForProvider(provider: AgentProvider): ModelOption[] {
- switch (provider) {
- case 'codex': return CODEX_MODELS;
- case 'grok': return GROK_MODELS;
- case 'kimi': return KIMI_MODELS;
- case 'antigravity': return ANTIGRAVITY_MODELS;
- case 'claude': return AGENT_MODELS;
- case 'custom': return [];
- }
+ if (provider === 'codex') return CODEX_MODELS;
++ if (provider === 'grok') return GROK_MODELS;
++ if (provider === 'kimi') return KIMI_MODELS;
+ if (provider === 'antigravity') return ANTIGRAVITY_MODELS;
+ if (provider === 'qwen') return QWEN_MODELS;
+ if (provider === 'opencode') return OPENCODE_MODELS;
+ if (provider === 'crush') return CRUSH_MODELS;
+ if (provider === 'pi') return PI_MODELS;
+ if (provider === 'copilot') return COPILOT_MODELS;
++ if (provider === 'custom') return [];
+ return AGENT_MODELS;
}
+ /** Providers shown in the Command Center's cross-provider model picker.
+ * God must remain on a provider with a working inbox drain; otherwise switching
+ * to a terminal-only provider would silently disable orchestration. */
+ export function modelProvidersForAgent(isGod = false) {
+ return AGENT_PROVIDER_PRESETS.filter((preset) =>
+ preset.supportsModel && (!isGod || preset.canReceiveInbox)
+ );
+ }
+
+ /** Native <select> values must carry both provider and model because each
+ * provider has its own "default" option and model namespace. */
+ export function encodeProviderModel(provider: AgentProvider, model?: string): string {
+ return `${provider}:${encodeURIComponent(model ?? '')}`;
+ }
+
+ export function decodeProviderModel(value: string): {
+ provider: AgentProvider;
+ model?: string;
+ } | null {
+ const split = value.indexOf(':');
+ if (split < 1) return null;
+ const provider = value.slice(0, split);
+ if (!AGENT_PROVIDER_PRESETS.some((preset) => preset.id === provider)) return null;
+ try {
+ const model = decodeURIComponent(value.slice(split + 1));
+ return { provider: provider as AgentProvider, model: model || undefined };
+ } catch {
+ return null;
+ }
+ }
+
/** Build the command line to feed into spawnPty, honoring the provider's flags,
* autoMode, and an optional per-agent model override. Claude keeps the user's
* configured `defaultCommand`; other providers use their preset binary so the
diff --cc src/renderer/src/store/store.ts
index aebebf3f,715c9267..595c3844
--- a/src/renderer/src/store/store.ts
+++ b/src/renderer/src/store/store.ts
@@@ -239,14 -220,86 +246,86 @@@ const LS_QUEUES = 'cth.messageQueues'
// Fields that are large or transient — not worth persisting across reloads.
// contextTokens/contextLimit describe a LIVE session; persisting them showed a
// dead session's context gauge after a restart until the poll caught up.
-type PersistedAgent = Omit<Agent, 'recentAssistantText' | 'recentTextTs' | 'blockReason' | 'contextTokens' | 'contextLimit'>;
+type PersistedAgent = Omit<Agent, 'recentAssistantText' | 'recentTextTs' | 'blockReason' | 'contextTokens' | 'contextLimit' | 'seedPrompt'>;
- function persistAgents(agents: Agent[], selectedId: string | null): void {
+ // ─── The roster mirror ──────────────────────────────────────────────────────
+ //
+ // localStorage is partitioned by ORIGIN, and the two ways this app runs do not
+ // share one: `npm run dev` serves the renderer from http://localhost:5173, a
+ // packaged build loads it from file://. So the roster — agents, their private
+ // notes, worktree paths, archived entries, parked queues — was invisible to
+ // whichever of the two you were not currently in, even though the hive on disk
+ // (sessions, memory, inboxes, tasks) was shared and intact the whole time.
+ //
+ // So we also mirror it to <harnessHome>/roster.json, which both sides reach by
+ // path. localStorage keeps being written byte-for-byte as before: it is the
+ // fallback when there is no file yet, and a standing backup afterwards. Main
+ // keeps every previous version of the file under roster-backups/.
+ const fileRoster = (() => {
+ try { return window.cth?.rosterReadSync?.() ?? null; } catch { return null; }
+ })();
+
+ /** Prefer the shared file, but only when it actually holds a roster. An empty
+ * file must never win over a populated localStorage — that is exactly the
+ * "opened the build once and my floor went blank" failure this is here to
+ * prevent. A genuine delete-all clears both stores, so nothing resurrects. */
+ const useFileRoster = !!fileRoster
+ && fileRoster.agents.length + fileRoster.archived.length + fileRoster.restorable.length > 0;
+
+ /** The renderer's running copy of what should be on disk. Kept as a mutable
+ * mirror updated slice-by-slice rather than read back out of the store, because
+ * every persist* call happens INSIDE a zustand `set()` — `getState()` there
+ * still returns the pre-update state, so a snapshot built that way would
+ * reliably be one edit stale. */
+ const rosterMirror: {
+ agents: PersistedAgent[];
+ archived: PersistedAgent[];
+ restorable: PersistedAgent[];
+ queues: Record<string, QueuedMessage[]>;
+ selectedId: string | null;
+ } = { agents: [], archived: [], restorable: [], queues: {}, selectedId: null };
+
+ let rosterFlush: ReturnType<typeof setTimeout> | null = null;
+
+ function flushRosterNow(): void {
+ if (rosterFlush) { clearTimeout(rosterFlush); rosterFlush = null; }
try {
- const slim: PersistedAgent[] = agents.map(({ recentAssistantText, recentTextTs, blockReason, contextTokens, contextLimit, seedPrompt, ...rest }) => {
- void recentAssistantText; void recentTextTs; void blockReason; void contextTokens; void contextLimit; void seedPrompt;
- return rest;
+ void window.cth?.rosterWrite?.({
+ version: 1,
+ savedAt: new Date().toISOString(),
+ agents: rosterMirror.agents,
+ archived: rosterMirror.archived,
+ restorable: rosterMirror.restorable,
+ queues: rosterMirror.queues,
+ selectedId: rosterMirror.selectedId
});
+ } catch { /* the file is a mirror — localStorage already took the write */ }
+ }
+
+ /** Coalesce a burst of persist* calls into one disk write. Agent edits arrive in
+ * clusters (spawn writes agents + selection + queues in the same tick). */
+ function scheduleRosterFlush(): void {
+ if (rosterFlush) return;
+ rosterFlush = setTimeout(flushRosterNow, 500);
+ }
+
+ // Don't let a quit inside the debounce window drop the last edit. localStorage
+ // would still have it, but only for THIS origin — and the whole point is that
+ // the other origin can read it too.
+ try {
+ window.addEventListener('beforeunload', flushRosterNow);
+ } catch { /* not a browser context (unit tests) */ }
+
+ function slimAgents(agents: Agent[]): PersistedAgent[] {
- return agents.map(({ recentAssistantText, recentTextTs, blockReason, contextTokens, contextLimit, ...rest }) => {
- void recentAssistantText; void recentTextTs; void blockReason; void contextTokens; void contextLimit;
++ return agents.map(({ recentAssistantText, recentTextTs, blockReason, contextTokens, contextLimit, seedPrompt, ...rest }) => {
++ void recentAssistantText; void recentTextTs; void blockReason; void contextTokens; void contextLimit; void seedPrompt;
+ return rest;
+ });
+ }
+
+ function persistAgents(agents: Agent[], selectedId: string | null): void {
+ const slim = slimAgents(agents);
+ try {
window.localStorage.setItem(LS_AGENTS, JSON.stringify(slim));
window.localStorage.setItem(LS_SELECTED, selectedId ?? '');
} catch { /* noop */ }
@@@ -304,13 -386,18 +412,18 @@@ function loadPersistedArchived(): Agent
}
function persistRestorable(restorable: Agent[]): void {
+ // Keeps contextTokens/contextLimit, unlike the other two: a restorable entry
+ // is a spawn recipe for a session that has not been re-entered yet, so its
+ // last known context size is still meaningful.
- const slim: PersistedAgent[] = restorable.map(({ recentAssistantText, recentTextTs, blockReason, ...rest }) => {
- void recentAssistantText; void recentTextTs; void blockReason;
++ const slim: PersistedAgent[] = restorable.map(({ recentAssistantText, recentTextTs, blockReason, seedPrompt, ...rest }) => {
++ void recentAssistantText; void recentTextTs; void blockReason; void seedPrompt;
+ return rest;
+ });
try {
- const slim: PersistedAgent[] = restorable.map(({ recentAssistantText, recentTextTs, blockReason, seedPrompt, ...rest }) => {
- void recentAssistantText; void recentTextTs; void blockReason; void seedPrompt;
- return rest;
- });
window.localStorage.setItem(LS_RESTORABLE, JSON.stringify(slim));
} catch { /* noop */ }
+ rosterMirror.restorable = slim;
+ scheduleRosterFlush();
}
function loadPersistedRestorable(): Agent[] {
diff --cc src/shared/agentProvider.ts
index 337be912,e3e837bc..75d7816d
--- a/src/shared/agentProvider.ts
+++ b/src/shared/agentProvider.ts
@@@ -14,44 -15,9 +15,47 @@@
import type { CmdGroup } from './claudeCommands';
import { COMMAND_GROUPS as CLAUDE_COMMAND_GROUPS } from './claudeCommands';
import { CODEX_COMMAND_GROUPS } from './codexCommands';
+ import { GROK_COMMAND_GROUPS } from './grokCommands';
-export type AgentProvider = 'claude' | 'codex' | 'grok' | 'kimi' | 'antigravity' | 'custom';
+// NOTE: 'claw' (claw-code) was removed as a selectable provider — its upstream is
+// an unmaintained "museum exhibit" repo, not a production CLI. Re-add a supported
+// fork here (plus its preset/models/logo) after review. The proxy-bridge tier it
+// shared with qwen stays in place for qwen.
+export type AgentProvider =
+ | 'claude'
+ | 'codex'
++ | 'grok'
++ | 'kimi'
+ | 'antigravity'
+ | 'qwen'
+ | 'opencode'
+ | 'crush'
+ | 'pi'
+ | 'copilot'
+ | 'custom';
+
+/** Structured descriptor for how a NON-hiveAware provider gets hive lifecycle
+ * events (live status + Stop→inbox-drain + cost), introduced alongside the legacy
+ * `hookBridge` so call sites can switch on `bridge.kind` without a big-bang
+ * rewrite. Two kinds:
+ * - 'hooks' → a config-file hook shim is installed (agy/codex). Derived from the
+ * legacy `hookBridge` by `bridgeOf`, so agy/codex keep working with no
+ * preset change.
+ * - 'proxy' → the CLI has NO hook surface (qwen), so a loopback reverse-proxy
+ * sidecar observes its LLM traffic and SYNTHESIZES the same HIVE_SOCK
+ * payloads the shims emit. `api` selects the usage/tool-call shape
+ * (OpenAI vs Anthropic), `baseUrlEnv` is the env var the CLI reads for
+ * its upstream base URL (the sidecar's loopback URL is injected there),
+ * and `inboxDelivery` is how mail reaches it ('terminal' work-order
+ * handoff today; 'serve' reserved for a future HTTP push path). */
+export type BridgeDescriptor =
- | { kind: 'hooks'; shim: 'agy' | 'codex' | 'pi' | 'opencode' }
++ | { kind: 'hooks'; shim: 'agy' | 'codex' | 'pi' | 'opencode' | 'grok' }
+ | {
+ kind: 'proxy';
+ api: 'openai' | 'anthropic';
+ baseUrlEnv: string;
+ inboxDelivery: 'terminal' | 'serve';
+ };
export interface AgentProviderPreset {
id: AgentProvider;
@@@ -90,24 -58,12 +96,24 @@@
* 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';
+ hookBridge?: 'agy' | 'codex' | 'grok';
+ /** Structured bridge descriptor (the forward-looking replacement for the legacy
+ * `hookBridge`). Set explicitly only for PROXY-tier providers (qwen) that
+ * have no hook file to install; agy/codex leave it undefined and `bridgeOf`
+ * derives `{kind:'hooks'}` from their `hookBridge`. claude/custom leave it
+ * undefined (no bridge). Prefer `bridgeOf(provider)` over reading this directly. */
+ bridge?: BridgeDescriptor;
+ /** The model the GOD orchestrator ("Michael") defaults to when this provider
+ * powers it — surfaced as the picker default and the advisory "give Michael a
+ * longer-context, higher-capability model". `modelForRole` resolves the GOD
+ * model as `config.godModel ?? preset.recommendedOrchestratorModel ?? MODEL_GOD`.
+ * Advisory + user-overridable. */
+ recommendedOrchestratorModel?: string;
/** 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, 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)
+ * to the god). Requires lifecycle status so the renderer can deliver only at a
+ * safe idle prompt: Claude natively, Antigravity/Codex/Grok via hook bridges.
+ * A hookless custom provider cannot expose safe-idle state, so mail bounces.
+ * Distinct from hiveAware: agy/codex/grok are NOT hiveAware (no Claude injection)
* but CAN receive inbox via their bridge. */
canReceiveInbox: boolean;
/** For non-hive-aware CLIs that still take an INITIAL prompt to orient the
@@@ -117,27 -73,15 +123,32 @@@
* takes its initial prompt POSITIONALLY (Codex: `codex "<prompt>"`) and the
* injection branch appends it as a quoted trailing arg instead of a flag. */
initialPromptFlag?: string;
+ /** How the hive protocol seed is delivered for a CLI that takes NEITHER a flag
+ * nor a positional seed. `'type-into-tui'` = the CLI is a bare interactive TUI
+ * that rejects a positional initial prompt (Crush: its first positional is read
+ * as a Cobra SUBCOMMAND → `Unknown command "You are…"`), so the harness must NOT
+ * append the protocol to argv — it spawns the bare TUI and hands the protocol
+ * back as `seedPrompt`, which the renderer types into the TUI's editor after boot
+ * (through the SAME per-pty write-chain as the inbox-wake nudge, so they can't
+ * collide). Absent/undefined = today's flag-or-positional behavior. (ondev-b) */
+ seedDelivery?: 'type-into-tui';
+ /** This CLI accepts the initial hive prompt as a trailing positional argument.
+ * Codex does; Kimi/custom do not, so they must spawn bare when no prompt flag
+ * exists instead of receiving an invalid positional argument. */
+ positionalInitialPrompt?: boolean;
/** Flag to resume a prior session on respawn, given the recorded session id
* (Claude `--resume <sid>`, Antigravity `--conversation <id>`). undefined = no
* resume support, spawn fresh. */
resumeFlag?: string;
+ /** Shell command that installs this provider's engine CLI when it's missing,
+ * e.g. `npm install -g @anthropic-ai/claude-code`. When set, the missing-CLI
+ * path may RUN it visibly in the agent terminal (after pre-spawn detection);
+ * when undefined, the user is shown a manual instruction only and nothing is
+ * auto-run. MUST be a trusted, hardcoded constant — never user/manifest input. */
+ installCommand?: string;
+ /** Optional docs URL surfaced as a manual-setup hint in the missing-CLI banner. */
+ docsUrl?: string;
+ resumeSubcommand?: string; // CLIs that resume via a subcommand instead of a flag (Codex: `codex resume [OPTIONS] [SESSION_ID]`)
}
export const AGENT_PROVIDER_PRESETS: AgentProviderPreset[] = [
@@@ -162,18 -100,12 +173,18 @@@
},
{
id: 'codex',
- label: 'Codex',
+ label: 'Codex · GPT',
defaultCommand: 'codex',
commandGroups: CODEX_COMMAND_GROUPS,
- // Exact Codex equivalent of Claude's bypassPermissions: no approvals and no
- // Codex sandbox. Munder Difflin's global AUTO MODE is intentionally explicit
- // about this trust level; users can edit the per-agent command to remove it.
+ // Full claude-parity auto mode: skip ALL approval prompts AND drop the sandbox,
+ // exactly like Claude's `bypassPermissions` / agy's `--dangerously-skip-permissions`.
+ // The earlier `-a never -s workspace-write` confined writes to the PTY cwd
+ // (the user's project), but a hive worker must also write to its agent folder
+ // at <harnessHome>/hive/agents/<id>/ (inbox→.done, memory.md, outbox JSON,
+ // deliverables) — a DIFFERENT path tree from cwd, which workspace-write blocked,
+ // so codex workers couldn't do HIVE PROTOCOL housekeeping. The single bypass flag
+ // is codex's documented equivalent of `--dangerously-skip-permissions` (no -a/-s
+ // alongside it). The app already runs claude/agy in this same full-access posture.
autoModeFlag: '--dangerously-bypass-approvals-and-sandbox',
autoFlag: '--dangerously-bypass-approvals-and-sandbox',
// Suppresses first-run interactive prompts (directory-trust gate, installer).
@@@ -195,16 -127,51 +206,57 @@@
// inbox-wake nudge remains as a harmless fallback for an idle worker).
canReceiveInbox: true,
initialPromptFlag: undefined,
+ positionalInitialPrompt: true,
+ // Codex's long-context coding model for the orchestrator role. // TODO-verify
+ // the exact codex CLI model id (couldn't install the codex CLI to confirm).
+ recommendedOrchestratorModel: 'gpt-5-codex',
- // Codex has no stable session-resume CLI flag in the curated reference; spawn
- // fresh on respawn (the protocol is re-injected as the initial prompt anyway).
+ // Codex resumes via a SUBCOMMAND, not a flag: `codex resume [OPTIONS]
+ // [SESSION_ID]`. A `--resume <id>` flag does not exist, which is why restarts
+ // used to silently start a brand-new session instead of continuing.
resumeFlag: undefined,
- resumeSubcommand: 'resume'
++ resumeSubcommand: 'resume',
+ // Official OpenAI Codex CLI install (npm global). Used by the missing-CLI auto-install.
+ installCommand: 'npm install -g @openai/codex',
+ docsUrl: 'https://github.com/openai/codex'
},
+ {
+ id: 'grok',
+ label: 'Grok · xAI',
+ defaultCommand: 'grok',
+ commandGroups: GROK_COMMAND_GROUPS,
+ // Grok documents bypassPermissions as the CLI/config spelling of its
+ // always-approve mode. Deny rules and lifecycle gates still take precedence.
+ autoModeFlag: '--permission-mode bypassPermissions',
+ autoFlag: '--permission-mode bypassPermissions',
+ supportsModel: true,
+ modelFlag: '--model',
+ hiveAware: false,
+ // Grok supports Claude-compatible lifecycle events but sends camelCase
+ // payloads. The bridge normalizes them before forwarding to HookServer.
+ hookBridge: 'grok',
+ canReceiveInbox: true,
+ // `grok [PROMPT]` accepts the initial hive protocol as a positional prompt.
+ positionalInitialPrompt: true,
+ // Grok resumes interactively with `grok --resume <session-id-or-title>`.
+ resumeFlag: '--resume'
+ },
+ {
+ id: 'kimi',
+ label: 'Kimi Code',
+ defaultCommand: 'kimi',
+ commandGroups: [],
+ // Kimi --auto handles every approval and does not stop to ask questions,
+ // matching Munder Difflin's autonomous Claude/Codex default.
+ autoModeFlag: '--auto',
+ autoFlag: '--auto',
+ supportsModel: true,
+ modelFlag: '--model',
+ hiveAware: false,
+ // Kimi's interactive TUI has no positional initial-prompt form. It supports
+ // lifecycle hooks, but Munder Difflin does not yet install a Kimi hook bridge,
+ // so mail must bounce rather than being delivered with no drain path.
+ canReceiveInbox: false
+ },
{
id: 'antigravity',
label: 'Antigravity · Gemini',
@@@ -413,12 -204,9 +465,14 @@@ export function isAgentProvider(value:
return (
value === 'claude' ||
value === 'codex' ||
+ value === 'grok' ||
+ value === 'kimi' ||
value === 'antigravity' ||
+ value === 'qwen' ||
+ value === 'opencode' ||
+ value === 'crush' ||
+ value === 'pi' ||
+ value === 'copilot' ||
value === 'custom'
);
}
@@@ -462,12 -249,9 +515,14 @@@ export function inferAgentProvider(comm
if (normalized) return normalized;
const bin = commandBinary(command);
if (bin === 'codex') return 'codex';
+ if (bin === 'grok') return 'grok';
+ if (bin === 'kimi') return 'kimi';
if (bin === 'agy' || bin === 'antigravity') return 'antigravity';
+ if (bin === 'qwen') return 'qwen';
+ if (bin === 'opencode') return 'opencode';
+ if (bin === 'crush') return 'crush';
+ if (bin === 'pi') return 'pi';
+ if (bin === 'copilot') return 'copilot';
if (bin === 'claude' || !bin) return 'claude';
return 'custom';
}
diff --cc test/agent-provider.test.cjs
index b8053e7b,00000000..aa82d5ed
mode 100644,000000..100644
--- a/test/agent-provider.test.cjs
+++ b/test/agent-provider.test.cjs
@@@ -1,74 -1,0 +1,74 @@@
+'use strict';
+/**
+ * Agent-provider registry tests. Self-contained, no test framework — run with
+ * `node test/agent-provider.test.cjs` (mirrors test/kg-core.test.cjs). The
+ * registry lives in TypeScript (src/shared/agentProvider.ts), so we transpile it
+ * and its two dependency-free command-group siblings with the bundled `typescript`
+ * compiler into a temp dir and require the result. Exercises the copilot preset
+ * (GitHub Copilot CLI) end to end: registration, command inference, the print-mode
+ * flag shape, and the model/resume passthrough — alongside the pre-existing codex
+ * preset as a guard against regressions.
+ */
+
+const assert = require('node:assert');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const ts = require('typescript');
+
+const SHARED = path.join(__dirname, '..', 'src', 'shared');
+const out = fs.mkdtempSync(path.join(os.tmpdir(), 'agentprov-'));
- for (const name of ['claudeCommands', 'codexCommands', 'agentProvider']) {
++for (const name of ['claudeCommands', 'codexCommands', 'grokCommands', 'agentProvider']) {
+ const src = fs.readFileSync(path.join(SHARED, `${name}.ts`), 'utf8');
+ const js = ts.transpileModule(src, {
+ compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 }
+ }).outputText;
+ fs.writeFileSync(path.join(out, `${name}.js`), js, 'utf8');
+}
+const ap = require(path.join(out, 'agentProvider.js'));
+
+let failures = 0;
+function test(name, fn) {
+ try { fn(); console.log(` ✓ ${name}`); }
+ catch (err) { failures++; console.log(` ✗ ${name}\n ${err && err.message}`); }
+}
+
+console.log('agent-provider registry tests');
+
+test('copilot is a recognized, selectable provider', () => {
+ assert.ok(ap.isAgentProvider('copilot'), 'isAgentProvider("copilot")');
+ assert.ok(ap.AGENT_PROVIDER_PRESETS.some((p) => p.id === 'copilot'), 'preset registered');
+});
+
+test('inferAgentProvider maps the copilot binary (with path/flags) to copilot', () => {
+ assert.strictEqual(ap.inferAgentProvider('copilot'), 'copilot');
+ assert.strictEqual(ap.inferAgentProvider('/usr/local/bin/copilot --model gpt-5.4'), 'copilot');
+});
+
+test('copilot preset builds the documented non-interactive print-mode shape', () => {
+ const p = ap.providerPreset('copilot');
+ assert.strictEqual(p.defaultCommand, 'copilot', 'default command binary');
+ assert.strictEqual(p.initialPromptFlag, '-p', 'prompt rides in via -p');
+ assert.strictEqual(ap.autoModeFlagForProvider('copilot'), '-s --allow-all-tools --no-ask-user');
+ assert.strictEqual(p.autoFlag, '-s --allow-all-tools --no-ask-user', 'autoFlag mirrors autoModeFlag');
+});
+
+test('copilot passes model + resume through, non-hiveAware, never auto-receives inbox', () => {
+ const p = ap.providerPreset('copilot');
+ assert.ok(p.supportsModel && p.modelFlag === '--model', 'model picker + --model');
+ assert.strictEqual(p.resumeFlag, '--resume', 'session resume flag');
+ assert.strictEqual(p.hiveAware, false, 'no Claude-only identity injection');
+ assert.strictEqual(ap.canReceiveInbox('copilot'), false, 'print mode exits, no drain → bounces');
+ assert.strictEqual(ap.bridgeOf('copilot'), undefined, 'no hook/proxy bridge');
+});
+
+test('codex preset still resolves (no regression)', () => {
+ assert.strictEqual(ap.inferAgentProvider('codex'), 'codex');
+ assert.strictEqual(ap.providerPreset('codex').defaultCommand, 'codex');
+});
+
+if (failures > 0) {
+ console.log(`\n${failures} test(s) failed`);
+ process.exit(1);
+}
+console.log('\nAll agent-provider tests passed');
diff --cc test/provider-config.test.cjs
index 00000000,a0aaaf06..3448145b
mode 000000,100644..100644
--- a/test/provider-config.test.cjs
+++ b/test/provider-config.test.cjs
@@@ -1,0 -1,112 +1,114 @@@
+ 'use strict';
+
+ const test = require('node:test');
+ const assert = require('node:assert/strict');
+ const loadTs = require('./load-ts.cjs');
+
+ const {
+ inferAgentProvider,
+ isAgentProvider,
+ providerPreset
+ } = loadTs('src/shared/agentProvider.ts');
+ const {
+ buildSpawnCommand,
+ decodeProviderModel,
+ encodeProviderModel,
+ modelProvidersForAgent,
+ modelsForProvider
+ } = loadTs('src/renderer/src/store/config.ts');
+
+ const autoConfig = { defaultCommand: 'claude', autoMode: true };
+
+ test('Kimi is a first-class inferred provider with autonomous defaults', () => {
+ assert.equal(isAgentProvider('kimi'), true);
+ assert.equal(inferAgentProvider('kimi --auto'), 'kimi');
+ const preset = providerPreset('kimi');
+ assert.equal(preset.defaultCommand, 'kimi');
+ assert.equal(preset.autoFlag, '--auto');
+ assert.equal(preset.supportsModel, true);
+ assert.equal(preset.canReceiveInbox, false);
+ assert.equal(preset.positionalInitialPrompt, undefined);
+ });
+
+ test('Grok is a first-class inferred provider with hooks, resume, and always-approve', () => {
+ assert.equal(isAgentProvider('grok'), true);
+ assert.equal(inferAgentProvider('/Users/test/.local/bin/grok --model grok-4.5'), 'grok');
+ const preset = providerPreset('grok');
+ assert.equal(preset.defaultCommand, 'grok');
+ assert.equal(preset.autoFlag, '--permission-mode bypassPermissions');
+ assert.equal(preset.supportsModel, true);
+ assert.equal(preset.canReceiveInbox, true);
+ assert.equal(preset.hookBridge, 'grok');
+ assert.equal(preset.positionalInitialPrompt, true);
+ assert.equal(preset.resumeFlag, '--resume');
+ });
+
+ test('provider commands use matching models and equivalent bypass modes', () => {
+ assert.equal(
+ buildSpawnCommand(autoConfig, 'claude-sonnet-5', 'claude'),
+ 'claude --model claude-sonnet-5 --permission-mode bypassPermissions'
+ );
+ assert.equal(
+ buildSpawnCommand(autoConfig, 'gpt-5.6-sol', 'codex'),
+ 'codex --model gpt-5.6-sol --dangerously-bypass-approvals-and-sandbox'
+ );
+ assert.equal(
+ buildSpawnCommand(autoConfig, 'grok-4.5', 'grok'),
+ 'grok --model grok-4.5 --permission-mode bypassPermissions'
+ );
+ assert.equal(
+ buildSpawnCommand(autoConfig, 'kimi-code/k3', 'kimi'),
+ 'kimi --model kimi-code/k3 --auto'
+ );
+ });
+
+ test('model picker options stay provider-specific', () => {
+ assert.equal(
+ modelsForProvider('claude').find((model) => model.id === 'claude-opus-5')?.label,
+ 'Opus 5 · 1M'
+ );
+ assert.deepEqual(
+ modelsForProvider('codex').map((model) => model.id),
+ [undefined, 'gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna']
+ );
+ assert.deepEqual(
+ modelsForProvider('grok').map((model) => model.id),
+ [undefined, 'grok-4.5']
+ );
+ assert.deepEqual(
+ modelsForProvider('kimi').map((model) => model.id),
+ [
+ undefined,
+ 'kimi-code/k3',
+ 'kimi-code/kimi-for-coding',
+ 'kimi-code/kimi-for-coding-highspeed'
+ ]
+ );
+ assert.deepEqual(modelsForProvider('custom'), []);
+ });
+
+ test('Command Center model choices round-trip provider and model', () => {
+ const encoded = encodeProviderModel('antigravity', 'Gemini 3.1 Pro (High)');
+ assert.deepEqual(
+ decodeProviderModel(encoded),
+ { provider: 'antigravity', model: 'Gemini 3.1 Pro (High)' }
+ );
+ assert.deepEqual(
+ decodeProviderModel(encodeProviderModel('kimi')),
+ { provider: 'kimi', model: undefined }
+ );
+ assert.equal(decodeProviderModel('unknown:model'), null);
+ });
+
+ test('God only sees providers that can drain hive inbox messages', () => {
++ // God-eligible = supportsModel && canReceiveInbox: kimi and copilot are
++ // excluded (no inbox drain path), custom is excluded (no model picker).
+ assert.deepEqual(
+ modelProvidersForAgent(true).map((preset) => preset.id),
- ['claude', 'codex', 'grok', 'antigravity']
++ ['claude', 'codex', 'grok', 'antigravity', 'qwen', 'opencode', 'crush', 'pi']
+ );
+ assert.deepEqual(
+ modelProvidersForAgent(false).map((preset) => preset.id),
- ['claude', 'codex', 'grok', 'kimi', 'antigravity']
++ ['claude', 'codex', 'grok', 'kimi', 'antigravity', 'qwen', 'opencode', 'crush', 'pi', 'copilot']
+ );
+ });