an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions
HTML agent-harnessagent-orchestrationagentsai-agentsautonomous-agentsclaude-codecodexcoding-agentsdesktop-appdeveloper-toolselectrongemini-cliharnessharness-engineeringlocal-firstmemorymulti-agentopencodeorchestrationtypescript
fix(workers): reliable spawn and teardown for god-hired ephemeral workers
Gastón Péchieu51332abd2e3c
diff --git a/package.json b/package.jsonindex 97bb375a..e470cd09 100644--- a/package.json+++ b/package.json@@ -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/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/terminal-selection.test.cjs test/roster.test.cjs test/proc-kill.test.cjs test/expand-tilde.test.cjs test/hive-cwd.test.cjs test/hive-task-mutation.test.cjs test/hive-hook-node.test.cjs test/hive-roster-injection.test.cjs test/hive-runtime-path.test.cjs test/cli-install-ladder.test.cjs test/node-install.test.cjs test/office-gl-recovery.test.cjs test/update-state.test.cjs test/release-notes.test.cjs test/transcript-project-dir.test.cjs test/commit-graph.test.cjs test/ide-image.test.cjs test/win-cmd-shim.test.cjs test/hive-windows-prompt.test.cjs test/release-drop.test.cjs test/skills.test.cjs test/skills-install.test.cjs test/hero-payload.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/terminal-selection.test.cjs test/roster.test.cjs test/proc-kill.test.cjs test/expand-tilde.test.cjs test/hive-cwd.test.cjs test/hive-task-mutation.test.cjs test/hive-hook-node.test.cjs test/hive-roster-injection.test.cjs test/hive-runtime-path.test.cjs test/cli-install-ladder.test.cjs test/node-install.test.cjs test/office-gl-recovery.test.cjs test/update-state.test.cjs test/release-notes.test.cjs test/transcript-project-dir.test.cjs test/commit-graph.test.cjs test/ide-image.test.cjs test/win-cmd-shim.test.cjs test/hive-windows-prompt.test.cjs test/release-drop.test.cjs test/skills.test.cjs test/skills-install.test.cjs test/hero-payload.test.cjs test/worker-launch.test.cjs","check:links": "node tools/check-release-links.cjs","dist": "npm run build && electron-builder","dist:mac": "npm run build && electron-builder --mac",diff --git a/src/main/index.ts b/src/main/index.tsindex 45d288e4..f94192c5 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -58,6 +58,7 @@ import { IntegrationBroker } from './integrationBroker';import * as integrations from './integrations';import { validateBaseUrl, buildAuthHeaders, resolveUpstreamUrl, secretRefFor, INTEGRATION_TEMPLATES } from '../shared/integrations';import { RosterStore } from './roster';+import { buildWorkerLaunch } from './workerLaunch';import { ControlRegistry } from './control';import { fetchHireManifest, readHireManifestFile } from './hire';import { parseHireDeepLink, type HireManifest } from '../shared/hire';@@ -386,9 +387,13 @@ const preservedWorktrees = new Map<string, PreservedWorktree>();* per dead PTY.** Idempotent: guarded on map presence and the already-idempotent- * `hive.setArchived`, so the second call (kill() also makes node-pty fire- * onExit) is a harmless no-op. Best-effort — every step is wrapped so a teardown- * error can never crash the caller (an IPC handler or node-pty's onExit).+ * `hive.setArchived`, so a double call is a harmless no-op. NOTE: an explicit+ * `ptyManager.kill()` does NOT reach here via onExit — kill() deletes the+ * session synchronously, so node-pty's later async exit callback fails the+ * session-identity guard and is swallowed. Every kill site must therefore call+ * teardownPty itself right after the kill (all of them do). Best-effort — every+ * step is wrapped so a teardown error can never crash the caller (an IPC+ * handler or node-pty's onExit).*/function teardownPty(id: string): void {// 0) Revoke this id's broker capability (if any). Idempotent + harmless for a@@ -4298,8 +4303,18 @@ async function processSpawnRequest(filePath: string): Promise<void> {const cwd = typeof raw.cwd === 'string' && raw.cwd.trim() ? expandTilde(raw.cwd) : '';if (!cwd || !existsSync(cwd)) { fail(`"cwd" missing or not found (${cwd || 'unset'})`); return; }- const command = typeof raw.command === 'string' && raw.command.trim() ? raw.command.trim() : (readConfig().defaultCommand ?? 'claude');- const bin = command.split(/\s+/)[0] || command;+ // Request line → executable + argv (auto-mode inheritance, tokenization,+ // model-flag dedupe). Pure and unit-tested — see workerLaunch.ts for why this+ // translation earned a test.+ const cfgSpawn = readConfig();+ const launch = buildWorkerLaunch({+ requestCommand: raw.command,+ requestProvider: raw.provider,+ requestModel: raw.model,+ defaultCommand: cfgSpawn.defaultCommand,+ autoMode: !!cfgSpawn.autoMode+ });+ const bin = launch.bin;// Missing-CLI → FAIL FAST. A headless worker has no human to watch an installer,// so we never run the cc49e1e install banner here — we reject and tell god.if (!ptyManager.isCommandAvailable(bin)) { fail(`engine CLI "${bin}" is not installed`); return; }@@ -4328,8 +4343,8 @@ async function processSpawnRequest(filePath: string): Promise<void> {brokerEnv.MD_BROKER_TOKEN = token;}const spawnOpts: AgentSpawnOptions = {- id: workerId, cwd, command, cols: 120, rows: 32,- args: raw.model ? ['--model', raw.model] : [],+ id: workerId, cwd, command: bin, cols: 120, rows: 32,+ args: launch.args,hive: meta, isolate, provider: raw.provider, env: brokerEnv};@@ -4438,8 +4453,14 @@ async function ephemeralWorkerTick(): Promise<void> {const defaultTokenCap = typeof cfg.defaultWorkerTokenCap === 'number' && cfg.defaultWorkerTokenCap > 0? cfg.defaultWorkerTokenCap : 0;- // (1) Finish or reap. ptyManager.kill → teardownPty → gated worktree + archive- // + liveWorkers.delete. `releasing` guards the gap before onExit fires.+ // (1) Finish or reap. Each release calls teardownPty EXPLICITLY after the+ // kill, like every other kill site: ptyManager.kill() deletes the session+ // synchronously, so when node-pty's async onExit later fires it fails the+ // session-identity guard and the global exit handler (→ teardownPty)+ // never runs. Relying on onExit here left released workers un-torn-down:+ // no hive archive, no hive:agentArchived, frozen floor cards, and god+ // kept mailing dead agents (seen live 2026-08-16 with worker-business/+ // worker-qa/worker-bizreview). A double teardown is a harmless no-op.for (const [workerId, rec] of [...liveWorkers]) {if (rec.releasing) continue;if (workerSignaledDone(workerId, rec.spawnedAt)) {@@ -4447,6 +4468,7 @@ async function ephemeralWorkerTick(): Promise<void> {rec.releasing = true;console.log(`[worker] ${workerId} signaled done — releasing`);ptyManager.kill(workerId);+ teardownPty(workerId);continue;}// Token-cap reap (default-off plumbing). An effective cap > 0 → reap when the@@ -4463,6 +4485,7 @@ async function ephemeralWorkerTick(): Promise<void> {rec.slack);ptyManager.kill(workerId);+ teardownPty(workerId);continue;}}@@ -4477,6 +4500,7 @@ async function ephemeralWorkerTick(): Promise<void> {rec.slack);ptyManager.kill(workerId);+ teardownPty(workerId);}}@@ -4571,8 +4595,12 @@ ipcMain.handle('workers:list', (): { live: WorkerSnapshot[]; preserved: Preserve});/** Manually stop a live ephemeral worker. Mirrors the done-release path: mark- * releasing, then kill → teardownPty runs the SAFETY-GATED worktree teardown- * (committed work is preserved, never force-discarded). Idempotent. */+ * releasing, then kill + EXPLICIT teardownPty — kill() deletes the session+ * synchronously, so node-pty's later onExit fails the identity guard and the+ * global exit handler never runs; relying on it here left manually-stopped+ * workers un-torn-down exactly like the release/reap paths. teardownPty runs+ * the SAFETY-GATED worktree teardown (committed work is preserved, never+ * force-discarded). Idempotent. */ipcMain.handle('workers:stop', (_evt, workerId: string): { ok: boolean; error?: string } => {if (typeof workerId !== 'string' || !workerId) return { ok: false, error: 'invalid worker id' };const rec = liveWorkers.get(workerId);@@ -4581,6 +4609,7 @@ ipcMain.handle('workers:stop', (_evt, workerId: string): { ok: boolean; error?:rec.releasing = true;console.log(`[worker] manual stop requested for ${workerId}`);try { ptyManager.kill(workerId); } catch (e) { return { ok: false, error: String(e) }; }+ teardownPty(workerId);return { ok: true };});diff --git a/src/main/workerLaunch.ts b/src/main/workerLaunch.tsnew file mode 100644index 00000000..e6e0ff7b--- /dev/null+++ b/src/main/workerLaunch.ts@@ -0,0 +1,61 @@+/**+ * How a god-hired worker's spawn request becomes an executable + argv, as a+ * pure function: this exact translation silently killed real workers for days+ * while reporting success, which is what earned it a unit test.+ */+import { inferAgentProvider } from '../shared/agentProvider';+import { tokenizeCommand } from '../shared/commandLine';++export interface WorkerLaunch {+ /** The executable name alone — what the PTY layer resolves and spawns. */+ bin: string;+ /** Everything else, in argv form, model flag included when applicable. */+ args: string[];+ /** The full effective command line, for display and floor cards. */+ command: string;+}++export function buildWorkerLaunch(opts: {+ /** `command` from the spawn request — god authors a full command LINE. */+ requestCommand?: unknown;+ requestProvider?: unknown;+ /** Separate `model` field from the request, if any. */+ requestModel?: unknown;+ defaultCommand?: string;+ /** The app's auto (skip-permissions) setting. */+ autoMode: boolean;+}): WorkerLaunch {+ let command =+ typeof opts.requestCommand === 'string' && opts.requestCommand.trim()+ ? opts.requestCommand.trim()+ : (opts.defaultCommand ?? 'claude');+ // Inherit the app's auto (skip-permissions) mode when the request takes no+ // stance of its own: a headless worker has no human to click through tool+ // prompts, so without the flag it stalls at the first ask until the idle+ // reaper kills it. An explicit --permission-mode in the request always wins,+ // and non-claude commands are left untouched.+ if (+ opts.autoMode &&+ inferAgentProvider(command, opts.requestProvider) === 'claude' &&+ !command.includes('--permission-mode')+ ) {+ command += ' --permission-mode bypassPermissions';+ }+ // god authors `command` as a full command LINE ("claude --model … --permission-mode …"),+ // but the PTY layer takes ONE executable name (resolveCommand) plus argv — the+ // unsplit line made node-pty exec a binary literally named like the whole+ // string → ENOENT → the worker died within ~1s of spawning while its request+ // archived as .done (this killed both flag-carrying Ryan spawns on 2026-08-16;+ // only the bare-`claude` one lived). Split with the SAME tokenizer the+ // renderer's spawn flows use, and hand the flags over as argv.+ const tokens = tokenizeCommand(command);+ const bin = tokens[0] || command;+ const flags = tokens.slice(1);+ // A separate `model` field only applies when the command line didn't pick a+ // model itself (spawnAgentCore likewise skips its default-model injection+ // when argv already carries --model).+ const model =+ typeof opts.requestModel === 'string' && opts.requestModel.trim() ? opts.requestModel.trim() : '';+ const args = [...flags, ...(model && !flags.includes('--model') ? ['--model', model] : [])];+ return { bin, args, command };+}diff --git a/src/renderer/src/store/config.ts b/src/renderer/src/store/config.tsindex a019f7a4..a13e55f7 100644--- a/src/renderer/src/store/config.ts+++ b/src/renderer/src/store/config.ts@@ -303,16 +303,11 @@ export const KIMI_MODELS: ModelOption[] = [{ 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. */-export function tokenizeCommand(command: string): string[] {- const out: string[] = [];- const re = /"([^"]*)"|'([^']*)'|(\S+)/g;- let m: RegExpExecArray | null;- while ((m = re.exec(command)) !== null) out.push(m[1] ?? m[2] ?? m[3]);- return out;-}+// tokenizeCommand moved to src/shared/commandLine.ts so main's spawn-request+// path splits command lines with the SAME rules as the renderer's spawn flows+// (they used to carry byte-identical copies). Re-exported here so existing+// importers keep their path.+export { tokenizeCommand } from '@shared/commandLine';/** The model preset list for a given provider's picker. */export function modelsForProvider(provider: AgentProvider): ModelOption[] {diff --git a/src/shared/commandLine.ts b/src/shared/commandLine.tsnew file mode 100644index 00000000..7b60271f--- /dev/null+++ b/src/shared/commandLine.ts@@ -0,0 +1,17 @@+/** 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.+ *+ * Shared because BOTH sides split command lines: the renderer's spawn flows+ * (AddAgentModal, restore, command center) and main's god-hired-worker path+ * (processSpawnRequest). They used to carry byte-identical copies, which is an+ * invitation for the two to drift — and a worker whose command line splits+ * differently from the renderer's is exactly the class of silent breakage the+ * spawn-request fix exists to prevent. */+export function tokenizeCommand(command: string): string[] {+ const out: string[] = [];+ const re = /"([^"]*)"|'([^']*)'|(\S+)/g;+ let m: RegExpExecArray | null;+ while ((m = re.exec(command)) !== null) out.push(m[1] ?? m[2] ?? m[3]);+ return out;+}diff --git a/test/worker-launch.test.cjs b/test/worker-launch.test.cjsnew file mode 100644index 00000000..9b0e09e3--- /dev/null+++ b/test/worker-launch.test.cjs@@ -0,0 +1,72 @@+'use strict';++/**+ * god authors a spawn request's `command` as a full command LINE, but the PTY+ * layer takes one executable plus argv. The unsplit line made node-pty exec a+ * binary literally named `claude --model … --permission-mode …` → ENOENT → the+ * worker died in under a second WHILE its request archived as `.done`. A+ * failure that presents as success is exactly what a unit test is for.+ */++const test = require('node:test');+const assert = require('node:assert/strict');+const loadTs = require('./load-ts.cjs');++const { buildWorkerLaunch } = loadTs('src/main/workerLaunch.ts');+const { tokenizeCommand } = loadTs('src/shared/commandLine.ts');++const launch = (over = {}) => buildWorkerLaunch({ autoMode: false, ...over });++test('a bare command spawns as itself, no argv', () => {+ const l = launch({ requestCommand: 'claude' });+ assert.equal(l.bin, 'claude');+ assert.deepEqual(l.args, []);+});++test('a flag-carrying command line splits into executable + argv', () => {+ const l = launch({ requestCommand: 'claude --permission-mode plan --verbose' });+ assert.equal(l.bin, 'claude');+ assert.deepEqual(l.args, ['--permission-mode', 'plan', '--verbose']);+});++test('a quoted model value with spaces stays one token', () => {+ const l = launch({ requestCommand: 'agy --model "Gemini 3.1 Pro (High)"' });+ assert.equal(l.bin, 'agy');+ assert.deepEqual(l.args, ['--model', 'Gemini 3.1 Pro (High)']);+});++test('the separate model field applies only when the line did not pick a model', () => {+ const applied = launch({ requestCommand: 'claude', requestModel: 'opus' });+ assert.deepEqual(applied.args, ['--model', 'opus']);+ const deduped = launch({ requestCommand: 'claude --model sonnet', requestModel: 'opus' });+ assert.deepEqual(deduped.args, ['--model', 'sonnet'], 'the command line wins over raw.model');+});++test('auto-mode ON appends bypassPermissions for a claude worker with no stance', () => {+ const l = launch({ requestCommand: 'claude', autoMode: true });+ assert.deepEqual(l.args, ['--permission-mode', 'bypassPermissions']);+ assert.ok(l.command.includes('--permission-mode bypassPermissions'));+});++test('an explicit --permission-mode in the request always wins over auto-mode', () => {+ const l = launch({ requestCommand: 'claude --permission-mode plan', autoMode: true });+ assert.deepEqual(l.args, ['--permission-mode', 'plan']);+});++test('auto-mode leaves non-claude commands untouched, and OFF appends nothing', () => {+ const codex = launch({ requestCommand: 'codex', autoMode: true });+ assert.deepEqual(codex.args, []);+ const off = launch({ requestCommand: 'claude', autoMode: false });+ assert.deepEqual(off.args, []);+});++test('a missing command falls back to the default, then to claude', () => {+ assert.equal(launch({ defaultCommand: 'codex --full-auto' }).bin, 'codex');+ assert.equal(launch({}).bin, 'claude');+});++test('main and renderer split with the SAME tokenizer (shared module)', () => {+ // The old inline copy was byte-identical to the renderer's; now it IS the+ // renderer's. One example locks the routing through the shared function.+ assert.deepEqual(tokenizeCommand(`a "b c" 'd e' f`), ['a', 'b c', 'd e', 'f']);+});