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

fix(cli-agents): pre-PR QA round — idle backstop + OpenCode/Crush wire fixes

Chaitanya Giri832bbbc03b81
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9c7ed911..9d619115 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,11 +10,22 @@ Three more coding CLIs join the floor — **OpenCode**, **Crush**, and **pi.dev*
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 new engines are wired end-to-end and selectable as god, but
-> their bridges' *runtime* behavior (real model calls → tool gating → turn-end drain) is **pending
-> BYOK keys / a local LLM** — verify on-device. Their architecture (preset + bridge + payload
-> contract) was reviewed line-by-line; the guaranteed mail-drain path (the renderer idle inbox-wake
-> nudge) is provider-agnostic and already proven.
+> **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
@@ -34,6 +45,12 @@ sleep-frozen message router and Codex workers' filesystem permissions.
(`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.
diff --git a/RELEASE.md b/RELEASE.md
index 2e1841ca..03d05452 100644
--- a/RELEASE.md
+++ b/RELEASE.md
@@ -24,7 +24,9 @@ encrypted, never shown again) and **local base-URLs** (Ollama / LM Studio / vLLM
> **Heads-up:** these engines are integrated and selectable as god, but **live end-to-end
> verification with real model calls is pending your BYOK keys / a local LLM** — verify on-device.
-> The guaranteed inbox-drain path (the idle wake-nudge) is provider-agnostic and already proven.
+> Mail delivery doesn't wait on that: a new **provider-agnostic PTY-quiescence idle fallback** flips
+> any silent-but-busy agent back to idle, so the idle wake-nudge drains a god even if a bridge's
+> turn-end signal never fires.
Plus two reliability fixes: the **message router now survives system sleep** (it re-arms and drains
the backlog on wake, so god→worker and agent↔agent mail keeps flowing after the laptop's been
diff --git a/src/main/hive.ts b/src/main/hive.ts
index 6ddf97c9..de024dfb 100644
--- a/src/main/hive.ts
+++ b/src/main/hive.ts
@@ -1252,20 +1252,25 @@ export class HiveManager {
* 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 } {
+ 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 for the common provider ids → loopback, so any selected
- // model's traffic routes through the proxy. Crush merges config (later sources
- // override conflicting keys), so this only rewrites base_url and leaves the
- // user's keys/models intact. Literal loopback (Dwight's option b1 — no ${VAR}
- // expansion edge cases).
- const providers: Record<string, { base_url: string }> = {};
- for (const id of ['anthropic', 'openai', 'openrouter', 'gemini', 'groq']) {
- providers[id] = { base_url: loopbackUrl };
- }
+ // 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 };
diff --git a/src/main/index.ts b/src/main/index.ts
index 7cbdabcd..441b97a1 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1933,11 +1933,25 @@ async function spawnAgentCore(opts: AgentSpawnOptions, owner: Electron.WebConten
if (opts.hive && (provider === 'opencode' || provider === 'crush' || provider === 'pi' || provider === 'qwen')) {
const cfg = readConfig();
const extra: Record<string, string> = {};
- // 1) Inject every backend key the user has stored, so whichever model the CLI
- // picks, the matching key is present (unused keys are harmless).
- for (const [backend, envVar] of Object.entries(BACKEND_KEY_ENV)) {
+ // 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) extra[envVar] = key;
+ 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).
@@ -1949,8 +1963,13 @@ async function spawnAgentCore(opts: AgentSpawnOptions, owner: Electron.WebConten
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: { local: { name: 'local' } } }
+ local: { npm: '@ai-sdk/openai-compatible', name: 'Local (self-hosted)', options: { baseURL: baseUrl }, models: { [localModel]: { name: localModel } } }
};
}
extra.OPENCODE_CONFIG_CONTENT = JSON.stringify(oc);
diff --git a/src/preload/index.ts b/src/preload/index.ts
index d8f37cfb..26cfe625 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -438,7 +438,7 @@ const api = {
ipcRenderer.invoke('pty:resize', id, cols, rows),
killPty: (id: string): Promise<{ ok: boolean; error?: string }> =>
ipcRenderer.invoke('pty:kill', id),
- listPtys: (): Promise<Array<{ id: string; cwd: string; command: string; pid: number }>> =>
+ listPtys: (): Promise<Array<{ id: string; cwd: string; command: string; pid: number; lastOutputAt: number }>> =>
ipcRenderer.invoke('pty:list'),
/** Resolve a Claude session id to the cwd it originally ran in (Add Agent
* resume auto-fill), or null if the id is invalid/unknown. */
diff --git a/src/renderer/src/components/AddAgentModal.tsx b/src/renderer/src/components/AddAgentModal.tsx
index 2c0f5675..c339caaa 100644
--- a/src/renderer/src/components/AddAgentModal.tsx
+++ b/src/renderer/src/components/AddAgentModal.tsx
@@ -169,7 +169,10 @@ export function AddAgentModal({ onClose, config, onConfigChange }: AddAgentModal
// 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);
if (id === 'custom') {
setCommand(command.trim() || config.defaultCommand || '');
diff --git a/src/renderer/src/hooks/useHive.ts b/src/renderer/src/hooks/useHive.ts
index adfca4d1..fadb39f6 100644
--- a/src/renderer/src/hooks/useHive.ts
+++ b/src/renderer/src/hooks/useHive.ts
@@ -20,6 +20,16 @@ const GOD_PTY = `pty-${GOD_ID}`;
// "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.
@@ -438,6 +448,43 @@ export function useHive(config: HarnessConfig | null): void {
});
}, [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.
useEffect(() => {
diff --git a/src/renderer/src/store/config.ts b/src/renderer/src/store/config.ts
index 9407d6c3..92b88c32 100644
--- a/src/renderer/src/store/config.ts
+++ b/src/renderer/src/store/config.ts
@@ -199,7 +199,10 @@ export const CRUSH_MODELS: ModelOption[] = [
{ id: 'openai/o3', label: 'o3 (OpenAI)' },
{ id: 'gemini/gemini-2.5-pro', label: 'Gemini 2.5 Pro' },
{ id: 'openrouter/auto', label: 'OpenRouter (auto)' },
- { id: 'ollama/llama3.1', label: 'Local · Ollama (llama3.1)' }
+ // 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
diff --git a/src/shared/agentProvider.ts b/src/shared/agentProvider.ts
index 30436e43..7356640e 100644
--- a/src/shared/agentProvider.ts
+++ b/src/shared/agentProvider.ts
@@ -300,7 +300,11 @@ export const AGENT_PROVIDER_PRESETS: AgentProviderPreset[] = [
// points at the loopback (installCrushConfig, special-cased in the proxy arm).
// Do NOT "fix" this to a real env var — it would have no effect.
bridge: { kind: 'proxy', api: 'openai', baseUrlEnv: 'CRUSH_PROXY_BASE_URL', inboxDelivery: 'terminal' },
- recommendedOrchestratorModel: 'anthropic/claude-sonnet-4-5', // advisory/editable; exact long-context id UNKNOWN — humanQA
+ // OpenAI-WIRE default so the out-of-box Crush god routes through the proxy
+ // cleanly (the proxy serves one wire-shape; an anthropic/* default would route to
+ // the wrong upstream — Dwight verify-crush MF1). Advisory/editable; non-OpenAI-wire
+ // Crush-via-proxy is on-device live-verify. // exact long-context id humanQA
+ recommendedOrchestratorModel: 'openai/gpt-4o',
// god-eligible via the proxy bridge (terminal inbox delivery on synthesized idle).
// Live runtime (proxy parse of Crush traffic + synthesized Stop) is UNVERIFIED
// pending keys; the renderer idle nudge is the guaranteed drain fallback.