Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix(issue-2243): tree-kill cmd.exe-wrapped CoS agents on Windows (review)
Adam Eivyc435eda792e2
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex d97ffa0633..6493ecd7dd 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -8,7 +8,7 @@- **A live agent TUI no longer gets reaped mid-paste.** The idle-timeout reaper only tracked `lastOutputAt` (PTY output), not client input, so pasting a large multi-line command into a running agent's session could sit in a silent reflow/commit window with no echo yet — indistinguishable from "idle" to the 5s poll. If the session happened to already be near its idle threshold, the reaper killed the PTY mid-paste, showing "[Session removed externally]" in the Shell page. The idle timer in `agentTuiSpawning.js` now also checks a new `shell.js` export, `getLastInputAt()`, and skips the reap while input arrived within the last 15s. This is deliberately keyed on input *recency*, not "is a Shell viewer attached": a regular (non-external) session's socket stays bound after its viewer navigates away — only external one-shot `tuiPromptRunner.js` runs get released via `shell:release-views` — so an attachment-based guard would have permanently suppressed idle-complete for any agent glanced at once in the Shell UI. (`server/services/shell.js`, `server/services/agentTuiSpawning.js`)- **Swarm claim-issue runs now write the completion sentinel so the task actually finishes.** In `/do:next --swarm` mode the orchestrator ships every issue via a PR and never touches the working tree, so it was skipping the `.agent-done` completion sentinel — leaving the CoS task hanging with no summary as if the run never ended. Phase C of the swarm directive now explicitly instructs the orchestrator to write the sentinel (with a run summary of the issues claimed, their PRs, and merge outcomes) after the serialized merges, while still skipping the per-agent `/simplify`/push steps. (`server/services/cosTaskGenerator.js`)- **[issue-2190] OpenCode Ollama providers now accept any --model flag.** The static `OPENCODE_CONFIG_CONTENT` lacked a models map, so OpenCode rejected every model with "not valid" and the agent sat idle. The config is now built dynamically at spawn time, declaring the provider's configured models (plus the model being run) under `provider.ollama.models` with bare ids — the exact shape OpenCode's `@ai-sdk/openai-compatible` provider validates `--model ollama/<id>` against. Applied across every OpenCode spawn path (CoS CLI/TUI agents, the toolkit CLI/TUI runners, and the light fire-and-collect CLI run), and a migration backfills existing installs' `data/providers.json` so a configured model's map is persisted too. Fixes the TUI eval path for local Ollama models.-- **[issue-2243] OpenCode Ollama (and every other CLI provider) now starts under Chief of Staff on Windows.** A CoS task using OpenCode Ollama — or any npm-installed CLI provider — failed instantly with a `startup-failure` (exit code -4058) while the same provider ran fine from the Settings "Run Prompt" button. The CoS agent spawners launched the bare command (`opencode`) directly, so on Windows the `opencode.cmd` shim couldn't be found and the process never started; the "Run Prompt" path already resolved the real shim and launched it through `cmd.exe`. Both CoS spawn paths (the runner process and direct mode) now use that same resolve-and-wrap step, so the agent starts correctly. The runner path additionally now injects the OpenCode models config (the #2190 fix), so the model is accepted there too. Non-Windows installs are unaffected.+- **[issue-2243] OpenCode Ollama (and every other CLI provider) now starts — and stops cleanly — under Chief of Staff on Windows.** A CoS task using OpenCode Ollama — or any npm-installed CLI provider — failed instantly with a `startup-failure` (exit code -4058) while the same provider ran fine from the Settings "Run Prompt" button. The CoS agent spawners launched the bare command (`opencode`) directly, so on Windows the `opencode.cmd` shim couldn't be found and the process never started; the "Run Prompt" path already resolved the real shim and launched it through `cmd.exe`. Both CoS spawn paths (the runner process and direct mode) now use that same resolve-and-wrap step, so the agent starts correctly. The runner path additionally now injects the OpenCode models config (the #2190 fix), so the model is accepted there too. And because a launched agent is now a `cmd.exe`-wrapped process on Windows, stopping, pausing, or terminating it routes through a process-tree kill so the real CLI child is taken down too instead of being orphaned. Non-Windows installs are unaffected.- **A busy-but-stuck TUI agent can no longer run unbounded — a wall-clock ceiling now backstops the idle reaper.** The idle-timeout reaper resets on every PTY chunk, but Claude Code repaints its `(Ns · esc to interrupt)` working counter roughly once a second while *any* tool/API call is in flight — including one stuck retrying a stalled Bedrock/network operation. A "busy-but-stuck" agent therefore keeps `lastOutputAt` advancing forever, so idle-reap never fires and the run had no ceiling at all: a real `/do:next --swarm` claim-issue orchestration churned its counter for 98 minutes (2026-07-06, agent-b1c56083) before Claude Code's *own* internal "Operation timed out" finally stopped it — had the CLI not self-terminated, the agent would have run unbounded, holding its lane, blocking the app's cooldown, and leaking a shell session. The long-running agent TUI path now arms an absolute wall-clock backstop from prompt submission (default 3h, provider-configurable via `tuiMaxRuntimeMs`), mirroring the one-shot runner's existing `hardTimeoutTimer`. If it fires with no `.agent-done` sentinel present, the run finalizes as a needs-manual-finish FAILURE (`max-runtime-timeout`) with the same "check for open or merged-but-uncleaned PRs" guidance as the merge-queue/review-loop idle-timeout paths, capturing any uncommitted worktree diff for post-mortem first; if the sentinel *is* present the run is salvaged as success. (`server/services/agentTuiSpawning.js`, `server/lib/tuiHandshake.js`, `server/lib/aiToolkit/providers.js`, `server/lib/aiToolkit/validation.js`, `server/lib/validation.js`)- **[issue-2191] TUI agents with zero file changes are now marked failed instead of silently succeeding.** A TUI agent that idled out after showing working indicators but made no uncommitted file changes was previously finalized as `success: idle-complete` — deleting the worktree and any evidence of what happened. Now the idle-complete path checks `git status` in the worktree: if the tree is clean, it finalizes as `failure: idle-no-changes` with the TUI buffer tail as error context. Any uncommitted diff is also captured to `worktree-diff.txt` in the agent archive dir before cleanup, so post-mortems can see what (if anything) was left behind.- **[issue-2193] Concurrent agent spawns no longer race on git worktree creation.** When two tasks for the same app spawned in the same evaluation tick, the first `git worktree add` grabbed git's per-repo worktree lock and the second failed with a lock error — blocking that task with `blockedCategory: worktree-failed` and leaving an orphan branch (`cos/task-…/agent-…`) with no worktree. Worktree creation now serializes per source repo through a single promise tail (the `issueWriteTail` pattern), so same-tick adds queue instead of colliding; `git worktree add` also retries a few times with backoff on lock errors to absorb residual external contention; and on final failure the partially-created branch is deleted (`git branch -D` + `git worktree prune`) so orphan branches stop accumulating. (`server/services/worktreeManager.js`)diff --git a/server/cos-runner/index.js b/server/cos-runner/index.jsindex b73c93a0c5..3aa0baaec7 100644--- a/server/cos-runner/index.js+++ b/server/cos-runner/index.js@@ -16,7 +16,7 @@ import { existsSync } from 'fs';import http from 'http';import { Server as SocketServer } from 'socket.io';import { ensureDir, PATHS } from '../lib/fileUtils.js';-import { prepareCliSpawn } from '../lib/bufferedSpawn.js';+import { prepareCliSpawn, killProcessTree } from '../lib/bufferedSpawn.js';import { createCodexStderrFormatter } from '../lib/codexCliOutput.js';import { createStreamJsonParser } from './streamJsonParser.js';import { loadState, saveState, withState } from './runnerState.js';@@ -417,13 +417,15 @@ app.post('/terminate/:agentId', (req, res) => {console.log(`🔪 Terminating agent ${agentId}`);- agent.process.kill('SIGTERM');+ // killProcessTree (not .kill) so a Windows cmd.exe-wrapped CLI shim's real+ // child is taken down too, not orphaned (#2243). No-op difference on POSIX.+ killProcessTree(agent.process, 'SIGTERM');// Force kill after timeout; store handle so it can be cancelled if the// process exits cleanly before the grace window expires.agent.killTimer = setTimeout(() => {if (activeAgents.has(agentId)) {- agent.process.kill('SIGKILL');+ killProcessTree(agent.process, 'SIGKILL');activeAgents.delete(agentId);}}, SIGKILL_GRACE_MS);@@ -444,8 +446,9 @@ app.post('/kill/:agentId', async (req, res) => {console.log(`💀 Force killing agent ${agentId} (PID: ${agent.pid})`);- // Use SIGKILL for immediate termination- agent.process.kill('SIGKILL');+ // Use SIGKILL for immediate termination — killProcessTree so a Windows+ // cmd.exe-wrapped shim's real child isn't orphaned (#2243). POSIX unchanged.+ killProcessTree(agent.process, 'SIGKILL');// Clean up immediatelyactiveAgents.delete(agentId);@@ -479,11 +482,12 @@ app.post('/pause/:agentId', async (req, res) => {agent.pausedAt = pausedAt;agent.pauseReason = reason;- agent.process.kill('SIGTERM');+ // killProcessTree so a Windows cmd.exe-wrapped shim's child isn't orphaned (#2243).+ killProcessTree(agent.process, 'SIGTERM');// Store handle so the close handler can clear it when the process exits first.agent.killTimer = setTimeout(() => {const current = activeAgents.get(agentId);- if (current?.paused) current.process.kill('SIGKILL');+ if (current?.paused) killProcessTree(current.process, 'SIGKILL');}, SIGKILL_GRACE_MS);res.json({ success: true, agentId, pid: agent.pid, pausedAt });@@ -502,10 +506,11 @@ app.post('/terminate-all', async (req, res) => {for (const agentId of agentIds) {const agent = activeAgents.get(agentId);if (agent) {- agent.process.kill('SIGTERM');+ // killProcessTree so a Windows cmd.exe-wrapped shim's child isn't orphaned (#2243).+ killProcessTree(agent.process, 'SIGTERM');agent.killTimer = setTimeout(() => {if (activeAgents.has(agentId)) {- agent.process.kill('SIGKILL');+ killProcessTree(agent.process, 'SIGKILL');activeAgents.delete(agentId);}}, SIGKILL_GRACE_MS);@@ -855,7 +860,7 @@ process.on('SIGTERM', async () => {// Terminate all agentsfor (const [agentId, agent] of activeAgents) {console.log(`🔪 Terminating agent ${agentId}`);- agent.process.kill('SIGTERM');+ killProcessTree(agent.process, 'SIGTERM'); // tree-kill so Windows cmd.exe shims aren't orphaned (#2243)}// Wait for agents to terminatediff --git a/server/cos-runner/index.test.js b/server/cos-runner/index.test.jsindex b4800bc230..b59c37dc39 100644--- a/server/cos-runner/index.test.js+++ b/server/cos-runner/index.test.js@@ -15,7 +15,7 @@ const RUNNER_SRC = readFileSync(join(__dirname, 'index.js'), 'utf-8');describe('cos-runner spawn — Windows CLI shim resolve+wrap (#2243)', () => {it('imports prepareCliSpawn from the shared bufferedSpawn helper', () => {expect(RUNNER_SRC).toMatch(- /import\s*\{\s*prepareCliSpawn\s*\}\s*from\s*'\.\.\/lib\/bufferedSpawn\.js';/+ /import\s*\{[^}]*\bprepareCliSpawn\b[^}]*\}\s*from\s*'\.\.\/lib\/bufferedSpawn\.js';/);});@@ -41,3 +41,22 @@ describe('cos-runner spawn — Windows CLI shim resolve+wrap (#2243)', () => {expect(childEnvIdx, 'childEnv must be built before the resolve').toBeLessThan(prepareIdx);});});++describe('cos-runner termination — Windows tree-kill for cmd.exe-wrapped shims (#2243)', () => {+ it('imports killProcessTree from the shared bufferedSpawn helper', () => {+ expect(RUNNER_SRC).toMatch(+ /import\s*\{[^}]*\bkillProcessTree\b[^}]*\}\s*from\s*'\.\.\/lib\/bufferedSpawn\.js';/+ );+ });++ it('terminates agent processes via killProcessTree, not a bare .kill(), so the wrapped child is not orphaned', () => {+ // Once an agent is spawned as `cmd.exe /c opencode.cmd …` on Windows, a+ // plain agent.process.kill() signals only cmd.exe and orphans the real CLI.+ // Every agent-process termination must route through killProcessTree.+ expect(RUNNER_SRC).toMatch(/killProcessTree\(agent\.process,\s*'SIGTERM'\)/);+ expect(RUNNER_SRC).toMatch(/killProcessTree\(agent\.process,\s*'SIGKILL'\)/);+ // Guard against a regression that reverts an agent-process kill to bare .kill().+ expect(RUNNER_SRC).not.toMatch(/agent\.process\.kill\(/);+ expect(RUNNER_SRC).not.toMatch(/current\.process\.kill\(/);+ });+});diff --git a/server/lib/bufferedSpawn.js b/server/lib/bufferedSpawn.jsindex c458b778e2..58eb5defa6 100644--- a/server/lib/bufferedSpawn.js+++ b/server/lib/bufferedSpawn.js@@ -214,16 +214,25 @@ export const MAX_OUTPUT_BYTES = 64 * 1024;* ConPTY handle), leaking it — so any non-ChildProcess killable always uses* its own `.kill()` instead, on every platform.*+ * `signal` applies to the **POSIX** branch only (`SIGTERM` default → the+ * graceful-then-`SIGKILL`-escalation pattern callers expect). On Windows there+ * is no real POSIX signal — `taskkill /T /F` force-kills the whole tree+ * regardless — so the arg is ignored there. A caller that wraps a `.cmd`/`.bat`+ * shim via `prepareCliSpawn` (its child is a `cmd.exe /c …` parent) MUST use+ * this rather than `child.kill()`, or on Windows only the `cmd.exe` shim dies+ * and the real CLI child is orphaned.+ ** @param {import('child_process').ChildProcess} child+ * @param {NodeJS.Signals} [signal] - POSIX signal to send (default `SIGTERM`); ignored on Windows*/-export function killProcessTree(child) {+export function killProcessTree(child, signal = 'SIGTERM') {if (IS_WIN32 && child.pid && child instanceof ChildProcess) {child.killed = true;spawn('taskkill', ['/T', '/F', '/PID', String(child.pid)], { stdio: 'ignore', windowsHide: true }).on('error', () => {}).unref();} else {- child.kill('SIGTERM');+ child.kill(signal);}}diff --git a/server/lib/bufferedSpawn.test.js b/server/lib/bufferedSpawn.test.jsindex 82d73010f6..0ce5e7539c 100644--- a/server/lib/bufferedSpawn.test.js+++ b/server/lib/bufferedSpawn.test.js@@ -86,6 +86,16 @@ describe('killProcessTree', () => {expect(spawnMock).not.toHaveBeenCalled();});+ it('on non-Windows forwards an explicit signal to the child (e.g. SIGKILL escalation) — #2243', () => {+ if (IS_WIN32) return; // platform-gated behavior+ const child = makeFakeChild();+ killProcessTree(child, 'SIGKILL');+ // POSIX callers keep their SIGTERM→SIGKILL escalation semantics — the+ // signal arg must reach child.kill, not be hardcoded to SIGTERM.+ expect(child.kill).toHaveBeenCalledWith('SIGKILL');+ expect(spawnMock).not.toHaveBeenCalled();+ });+it('on Windows spawns taskkill /T /F against the pid and marks the child killed', () => {if (!IS_WIN32) return; // can't simulate platform branch from outsideconst child = makeFakeChild({ pid: 999 });diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex e8d1a6d960..06ffbbeaa7 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -29,7 +29,7 @@ import { ensureAntigravityPrintArgs, isAntigravityCliProvider } from '../lib/antimport { resolveBedrockCliModel, prefixOpencodeModel, hasModelFlag, isOpencodeCommand, applyLeanClaudeArgs } from '../lib/providerModels.js';import { agentGuardEnv } from '../lib/agentGuard/index.js';import { buildOpencodeEnvVars } from '../lib/opencodeConfig.js';-import { prepareCliSpawn } from '../lib/bufferedSpawn.js';+import { prepareCliSpawn, killProcessTree } from '../lib/bufferedSpawn.js';const AGENTS_DIR = PATHS.cosAgents;@@ -507,7 +507,8 @@ export async function spawnDirectly({providerId: provider.id,category: analysis.category});- claudeProcess.kill('SIGTERM');+ // killProcessTree so a Windows cmd.exe-wrapped shim's real child isn't orphaned (#2243).+ killProcessTree(claudeProcess, 'SIGTERM');};// If no output after 3 seconds, transition from initializing to working to show progressdiff --git a/server/services/agentManagement.js b/server/services/agentManagement.jsindex 14df8edb65..37147d8eae 100644--- a/server/services/agentManagement.js+++ b/server/services/agentManagement.js@@ -17,6 +17,7 @@ import { activeAgents, runnerAgents, userTerminatedAgents, pausedAgents, useRunnimport { cleanupAgentWorktree, syncRunnerAgents } from './agentLifecycle.js';import { checkForTaskCommit } from './agentRunTracking.js';import { PATHS } from '../lib/fileUtils.js';+import { killProcessTree } from '../lib/bufferedSpawn.js';import { release } from './executionLanes.js';import { completeExecution, errorExecution } from './toolStateMachine.js';import * as shellService from './shell.js';@@ -152,10 +153,12 @@ export async function pauseAgent(agentId, reason = null) {if (activeAgents.has(agentId)) shellService.killSession(agent.tuiSessionId);}, 250);} else {- agent.process.kill('SIGTERM');+ // killProcessTree so a Windows cmd.exe-wrapped CLI shim's real child is+ // taken down, not orphaned (#2243). No behavior change on POSIX.+ killProcessTree(agent.process, 'SIGTERM');const killTimer = setTimeout(() => {if (activeAgents.has(agentId)) {- agent.process.kill('SIGKILL');+ killProcessTree(agent.process, 'SIGKILL');}}, 5000);const agentEntry = activeAgents.get(agentId);@@ -208,13 +211,14 @@ export async function terminateAgent(agentId) {}}- // Kill the process- agent.process.kill('SIGTERM');+ // Kill the process — killProcessTree so a Windows cmd.exe-wrapped shim's+ // real child isn't orphaned (#2243). POSIX behavior unchanged.+ killProcessTree(agent.process, 'SIGTERM');// Give it a moment, then force kill if still runningconst killTimer = setTimeout(() => {if (activeAgents.has(agentId)) {- agent.process.kill('SIGKILL');+ killProcessTree(agent.process, 'SIGKILL');unregisterSpawnedAgent(agent.pid);activeAgents.delete(agentId);}@@ -300,8 +304,9 @@ export async function killAgent(agentId) {}}- // Kill the process immediately with SIGKILL- agent.process.kill('SIGKILL');+ // Kill the process immediately with SIGKILL — killProcessTree so a Windows+ // cmd.exe-wrapped shim's real child isn't orphaned (#2243). POSIX unchanged.+ killProcessTree(agent.process, 'SIGKILL');unregisterSpawnedAgent(agent.pid);activeAgents.delete(agentId);