Skip to content

An agentic browser harness: an AI side panel & orb in your own logged-in Chrome, Edge, Arc, Brave or even Firefox run by the agent/subscription you already use (Claude Code, Codex, Antigravity). Free, open source, no API key. Also an MCP server.

fix(agents): start every agent CLI through one helper that sees through npm and pnpm .cmd shims on Windows without cmd.exe, hides its console and stops it with everything it started, and hand Claude Code its message on stdin and its prompt from a file, so no turn outgrows a Windows command line

Shahriardbec077d34d4
diff --git a/src/daemon/agent/runners/claude.test.ts b/src/daemon/agent/runners/claude.test.ts
index 05b0a7f..7df3773 100644
--- a/src/daemon/agent/runners/claude.test.ts
+++ b/src/daemon/agent/runners/claude.test.ts
@@ -17,7 +17,6 @@ describe('a streamed run', () => {
{
"args": [
"-p",
- "what does this page cost",
"--output-format",
"stream-json",
"--include-partial-messages",
@@ -58,8 +57,8 @@ describe('a streamed run', () => {
"ExitWorktree",
"WebSearch",
"WebFetch",
- "--append-system-prompt",
- "You are Browsentic.",
+ "--append-system-prompt-file",
+ "<state>/agents/claude/prompts/run-1.md",
"--session-id",
"<uuid>",
],
@@ -67,6 +66,13 @@ describe('a streamed run', () => {
"env": {
"BROWSENTIC_AGENT_RUN": "run-1",
},
+ "files": [
+ {
+ "content": "You are Browsentic.",
+ "path": "agents/claude/prompts/run-1.md",
+ },
+ ],
+ "input": "what does this page cost",
}
`);
});
diff --git a/src/daemon/agent/runners/claude.ts b/src/daemon/agent/runners/claude.ts
index dbc5f2d..b2b9702 100644
--- a/src/daemon/agent/runners/claude.ts
+++ b/src/daemon/agent/runners/claude.ts
@@ -1,9 +1,9 @@
import { randomUUID } from 'node:crypto';
import { homedir } from 'node:os';
-import { join } from 'node:path';
+import { join, relative } from 'node:path';
import { stateDir } from '../../lockfile';
import { log } from '../../log';
-import { browserToolsDidNotStart, effortOf, parseJsonLine } from './util';
+import { browserToolsDidNotStart, conversationDir, effortOf, parseJsonLine, sweepRunDirs } from './util';
import type { JsonContext, Plan, Runner, StreamContext, StreamReader, StreamSink } from './types';
export const MCP_SERVER_NAME = 'browsentic';
@@ -99,15 +99,22 @@ export const claudeRunner: Runner = {
skillDirs: () => [join(homedir(), '.claude', 'skills')],
+ // The message goes in on stdin and the system prompt from a file of its own: argv is capped on
+ // Windows at a length a follow-up with site notes and file reports can pass, and anyone can read it.
stream(context: StreamContext): Plan {
const { settings, research } = context;
const effort = effortOf(settings, this.efforts);
+ const cwd = this.workspace('run');
+ const prompts = join(stateDir, 'agents', 'claude', 'prompts');
+ sweepRunDirs(prompts);
+ const prompt = `${conversationDir(prompts, context.runId)}.md`;
return {
- cwd: this.workspace('run'),
+ cwd,
env: { BROWSENTIC_AGENT_RUN: context.runId },
+ input: context.instruction,
+ files: [{ path: relative(cwd, prompt), content: context.systemPrompt }],
args: [
'-p',
- context.instruction,
'--output-format',
'stream-json',
'--include-partial-messages',
@@ -123,8 +130,8 @@ export const claudeRunner: Runner = {
'--disallowedTools',
...BUILTIN_DENIED,
...(research ? [] : WEB_TOOLS),
- '--append-system-prompt',
- context.systemPrompt,
+ '--append-system-prompt-file',
+ prompt,
...(context.sessionId ? ['--resume', context.sessionId] : ['--session-id', randomUUID()]),
...(settings.model ? ['--model', settings.model] : []),
...(effort ? ['--effort', effort] : []),
diff --git a/src/daemon/agent/runners/command.test.ts b/src/daemon/agent/runners/command.test.ts
new file mode 100644
index 0000000..b27af3d
--- /dev/null
+++ b/src/daemon/agent/runners/command.test.ts
@@ -0,0 +1,211 @@
+import { once } from 'node:events';
+import { describe, expect, test } from 'vitest';
+import { commandLineLength, resolveCommand, spawnCli, stopTree, WINDOWS_COMMAND_LINE_MAX } from './command';
+import { RunError } from './types';
+
+const NPM = 'C:\\Users\\sam\\AppData\\Roaming\\npm';
+const PNPM = 'C:\\Users\\sam\\AppData\\Local\\pnpm';
+
+/** What npm's cmd-shim writes for a package whose bin is a Node script. */
+const npmScriptShim = (script: string) => `@ECHO off
+GOTO start
+:find_dp0
+SET dp0=%~dp0
+EXIT /b
+:start
+SETLOCAL
+CALL :find_dp0
+
+IF EXIST "%dp0%\\node.exe" (
+ SET "_prog=%dp0%\\node.exe"
+) ELSE (
+ SET "_prog=node"
+ SET PATHEXT=%PATHEXT:;.JS;=;%
+)
+
+endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\\${script}" %*
+`;
+
+/** What it writes for a bin that is already a program. */
+const npmProgramShim = (program: string) => `@ECHO off
+GOTO start
+:find_dp0
+SET dp0=%~dp0
+EXIT /b
+:start
+SETLOCAL
+CALL :find_dp0
+"%dp0%\\${program}" %*
+`;
+
+/** And for a script whose shebang names another interpreter. */
+const npmShellShim = `@ECHO off
+SETLOCAL
+CALL :find_dp0
+IF EXIST "%dp0%\\/bin/sh.exe" (
+ SET "_prog=%dp0%\\/bin/sh.exe"
+) ELSE (
+ SET "_prog=/bin/sh"
+)
+endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\\node_modules\\tool\\bin\\tool" %*
+`;
+
+const pnpmShim = `@SETLOCAL
+@IF NOT DEFINED NODE_PATH (
+ @SET "NODE_PATH=${PNPM}\\global\\5\\node_modules\\.pnpm\\node_modules"
+)
+@IF EXIST "%~dp0\\node.exe" (
+ "%~dp0\\node.exe" "%~dp0\\global\\5\\node_modules\\@qwen-code\\qwen-code\\cli.js" %*
+) ELSE (
+ @SET PATHEXT=%PATHEXT:;.JS;=;%
+ node "%~dp0\\global\\5\\node_modules\\@qwen-code\\qwen-code\\cli.js" %*
+)
+`;
+
+/** A Windows machine where only `files` exist, with `path` as its PATH. */
+const windows = (files: Record<string, string>, env: NodeJS.ProcessEnv = { Path: `C:\\Windows\\System32;${NPM}` }) => ({
+ platform: 'win32' as const,
+ env,
+ exists: (path: string) => Object.keys(files).some((file) => file.toLowerCase() === path.toLowerCase()),
+ read: (path: string) => {
+ const file = Object.keys(files).find((name) => name.toLowerCase() === path.toLowerCase());
+ if (file === undefined) throw new Error(`ENOENT: ${path}`);
+ return files[file];
+ },
+});
+
+const refusal = (run: () => unknown) => {
+ try {
+ run();
+ } catch (error) {
+ return error instanceof RunError ? { code: error.code, message: error.message } : error;
+ }
+ throw new Error('expected it to be refused');
+};
+
+describe('the program an agent command runs', () => {
+ test('macOS and Linux run the command as it is written', () => {
+ expect(resolveCommand('codex', ['exec', '--json'], { platform: 'darwin' })).toEqual({ file: 'codex', args: ['exec', '--json'] });
+ expect(resolveCommand('/opt/homebrew/bin/claude', ['-p'], { platform: 'linux' })).toEqual({
+ file: '/opt/homebrew/bin/claude',
+ args: ['-p'],
+ });
+ });
+
+ test('an npm install on Windows is its Node script, run by the Node the daemon runs on', () => {
+ const machine = windows({ [`${NPM}\\codex.cmd`]: npmScriptShim('node_modules\\@openai\\codex\\bin\\codex.js') });
+ expect(resolveCommand('codex', ['app-server', '-c', 'x=1'], machine)).toEqual({
+ file: process.execPath,
+ args: [`${NPM}\\node_modules\\@openai\\codex\\bin\\codex.js`, 'app-server', '-c', 'x=1'],
+ });
+ });
+
+ test('an npm shim for a program starts that program', () => {
+ const machine = windows({ [`${NPM}\\claude.cmd`]: npmProgramShim('node_modules\\@anthropic-ai\\claude-code\\bin\\claude.exe') });
+ expect(resolveCommand('claude', ['-p'], machine)).toEqual({
+ file: `${NPM}\\node_modules\\@anthropic-ai\\claude-code\\bin\\claude.exe`,
+ args: ['-p'],
+ });
+ });
+
+ test('a pnpm shim is seen through the same way', () => {
+ const machine = windows({ [`${PNPM}\\qwen.cmd`]: pnpmShim }, { PATH: PNPM });
+ expect(resolveCommand('qwen', ['--safe-mode'], machine)).toEqual({
+ file: process.execPath,
+ args: [`${PNPM}\\global\\5\\node_modules\\@qwen-code\\qwen-code\\cli.js`, '--safe-mode'],
+ });
+ });
+
+ test('a program on PATH wins over a batch file of the same name, as Windows orders them', () => {
+ const machine = windows({
+ [`${NPM}\\claude.cmd`]: npmScriptShim('node_modules\\@anthropic-ai\\claude-code\\cli.js'),
+ 'C:\\Users\\sam\\.local\\bin\\claude.exe': '',
+ }, { Path: `C:\\Users\\sam\\.local\\bin;${NPM}` });
+ expect(resolveCommand('claude', [], machine).file).toBe('C:\\Users\\sam\\.local\\bin\\claude.exe');
+ });
+
+ test('a bin set to an absolute path with no extension finds the shim beside it', () => {
+ const machine = windows({ [`${NPM}\\opencode.cmd`]: npmScriptShim('node_modules\\opencode-ai\\bin\\opencode') });
+ expect(resolveCommand(`${NPM}\\opencode`, ['run'], machine)).toEqual({
+ file: process.execPath,
+ args: [`${NPM}\\node_modules\\opencode-ai\\bin\\opencode`, 'run'],
+ });
+ });
+
+ test('a bin set to the .cmd itself is seen through too, rather than refused by Node', () => {
+ const machine = windows({ [`${NPM}\\codex.cmd`]: npmScriptShim('node_modules\\@openai\\codex\\bin\\codex.js') });
+ expect(resolveCommand(`${NPM}\\codex.cmd`, [], machine).file).toBe(process.execPath);
+ });
+
+ test('PATH is found however the environment spells it, and a quoted entry is unquoted', () => {
+ const shim = { [`${NPM}\\codex.cmd`]: npmScriptShim('node_modules\\@openai\\codex\\bin\\codex.js') };
+ expect(resolveCommand('codex', [], windows(shim, { path: NPM })).file).toBe(process.execPath);
+ expect(resolveCommand('codex', [], windows(shim, { PATH: `"${NPM}"` })).file).toBe(process.execPath);
+ });
+
+ test('a command Windows cannot find is left as written, so the spawn says it is not installed', () => {
+ expect(resolveCommand('grok', ['-p'], windows({}))).toEqual({ file: 'grok', args: ['-p'] });
+ });
+
+ test('a batch file with no Node script or program in it is refused, naming the setting to change', () => {
+ const machine = windows({ [`${NPM}\\agy.bat`]: '@echo off\r\ncall "%~dp0\\launch.bat" %*\r\n' });
+ const refused = refusal(() => resolveCommand('agy', [], machine)) as { code: string; message: string };
+ expect(refused.code).toBe('AGENT_UNUSABLE');
+ expect(refused.message).toContain(`${NPM}\\agy.bat`);
+ expect(refused.message).toContain('"bin"');
+ });
+
+ test('a shim for a script another interpreter runs is refused, not handed to Node', () => {
+ const machine = windows({ [`${NPM}\\tool.cmd`]: npmShellShim });
+ expect(refusal(() => resolveCommand('tool', [], machine))).toMatchObject({ code: 'AGENT_UNUSABLE' });
+ });
+});
+
+describe('a command line Windows could not start', () => {
+ test('each argument is counted as Windows quotes it', () => {
+ expect(commandLineLength({ file: 'claude', args: ['-p'] })).toBe('"claude" "-p" '.length);
+ expect(commandLineLength({ file: 'x', args: ['say "hi"'] })).toBe('"x" '.length + '"say \\"hi\\"" '.length);
+ });
+
+ test('a turn past the limit fails before anything is started, saying what to leave out', () => {
+ const prompt = 'x'.repeat(WINDOWS_COMMAND_LINE_MAX);
+ const refused = refusal(() => spawnCli('no-such-agent-cli', ['--rules', prompt], {}, 'win32')) as { code: string; message: string };
+ expect(refused.code).toBe('AGENT_FAILED');
+ expect(refused.message).toContain('site notes');
+ });
+
+ test.skipIf(process.platform === 'win32')('macOS and Linux are not held to it', async () => {
+ const child = spawnCli(process.execPath, ['-e', 'process.stdout.write(String(process.argv[1].length))', 'x'.repeat(WINDOWS_COMMAND_LINE_MAX)]);
+ let said = '';
+ child.stdout.on('data', (chunk: Buffer) => (said += chunk.toString()));
+ await once(child, 'close');
+ expect(said).toBe(String(WINDOWS_COMMAND_LINE_MAX));
+ });
+});
+
+describe('starting and stopping an agent CLI', () => {
+ test('stdin is closed unless it is asked for, and then what is written reaches the CLI', async () => {
+ const echo = "let t='';process.stdin.on('data',c=>t+=c).on('end',()=>process.stdout.write('got:'+t))";
+ const closed = spawnCli(process.execPath, ['-e', echo]);
+ expect(closed.stdin).toBeNull();
+
+ const held = spawnCli(process.execPath, ['-e', echo], { stdin: 'pipe' });
+ let said = '';
+ held.stdout.on('data', (chunk: Buffer) => (said += chunk.toString()));
+ held.stdin?.end('hello');
+ await once(held, 'close');
+ expect(said).toBe('got:hello');
+ });
+
+ test('a spawn Node refuses outright fails as a CLI that cannot be started', () => {
+ expect(refusal(() => spawnCli(process.execPath, ['bad\0argument']))).toMatchObject({ code: 'AGENT_UNUSABLE' });
+ });
+
+ test('stopping one ends it', async () => {
+ const child = spawnCli(process.execPath, ['-e', 'setInterval(() => {}, 1000)']);
+ const closed = once(child, 'close');
+ stopTree(child, 'SIGTERM');
+ await closed;
+ expect(child.exitCode === 0).toBe(false);
+ });
+});
diff --git a/src/daemon/agent/runners/command.ts b/src/daemon/agent/runners/command.ts
new file mode 100644
index 0000000..7c59c21
--- /dev/null
+++ b/src/daemon/agent/runners/command.ts
@@ -0,0 +1,144 @@
+import { execFile, spawn, type ChildProcess, type ChildProcessByStdio, type SpawnOptions } from 'node:child_process';
+import { existsSync, readFileSync } from 'node:fs';
+import { win32 } from 'node:path';
+import type { Readable, Writable } from 'node:stream';
+import { configPath } from '../config';
+import { RunError } from './types';
+
+/**
+ * How the daemon starts an agent CLI, and stops one. On macOS and Linux that is `spawn` and a
+ * signal. Windows needs three things spawn does not do on its own:
+ *
+ * - **An npm install is a batch file.** `codex` is `codex.cmd`, which spawn will not find on
+ * PATH, and will not run without a shell when named. A shell is no answer: a prompt runs to
+ * many lines, which cmd.exe cannot pass as one argument, and it carries page text, which cmd.exe
+ * would interpret. So the shim is read, and the program it names is started instead.
+ * - **No console window.** The daemon has none, so each console program it starts would get one.
+ * - **No signals.** A kill ends the one process, and whatever it started lives on.
+ */
+
+export type CliProcess = ChildProcessByStdio<Writable | null, Readable, Readable>;
+
+export interface Command {
+ file: string;
+ args: string[];
+}
+
+/** What Windows allows a whole command line, the program's own name included. */
+export const WINDOWS_COMMAND_LINE_MAX = 32_767;
+
+const WINDOWS_EXTENSIONS = '.COM;.EXE;.BAT;.CMD';
+
+/** The last line of an npm or pnpm shim: the program, quoted and relative to the shim, then `%*`. */
+const SHIM_TARGET = /"%~?dp0%?\\([^"]+)"\s+%\*/gi;
+
+interface Lookup {
+ platform?: NodeJS.Platform;
+ env?: NodeJS.ProcessEnv;
+ exists?: (path: string) => boolean;
+ read?: (path: string) => string;
+}
+
+/**
+ * The program `bin` runs and the arguments to start it with. Unchanged everywhere but Windows, and
+ * unchanged there too when `bin` is not found — spawn's own ENOENT is what says it is not installed.
+ */
+export function resolveCommand(
+ bin: string,
+ args: readonly string[],
+ { platform = process.platform, env = process.env, exists = existsSync, read = (path) => readFileSync(path, 'utf8') }: Lookup = {},
+): Command {
+ if (platform !== 'win32') return { file: bin, args: [...args] };
+ const found = onPath(bin, env, exists);
+ if (!found) return { file: bin, args: [...args] };
+ return /\.(cmd|bat)$/i.test(found) ? throughShim(found, args, read) : { file: found, args: [...args] };
+}
+
+function onPath(bin: string, env: NodeJS.ProcessEnv, exists: (path: string) => boolean): string | null {
+ const extensions = (variable(env, 'PATHEXT') ?? WINDOWS_EXTENSIONS).split(';').filter(Boolean);
+ const names = [...(win32.extname(bin) ? [bin] : []), ...extensions.map((extension) => `${bin}${extension.toLowerCase()}`)];
+ const placed = win32.dirname(bin) !== '.';
+ const dirs = placed ? [''] : (variable(env, 'PATH') ?? '').split(';').map((dir) => dir.replace(/^"|"$/g, '')).filter(Boolean);
+ for (const dir of dirs) {
+ for (const name of names) {
+ const candidate = dir ? win32.join(dir, name) : name;
+ if (exists(candidate)) return candidate;
+ }
+ }
+ return null;
+}
+
+/** Windows spells a variable any way it likes, and a plain copy of the environment keeps that spelling. */
+function variable(env: NodeJS.ProcessEnv, name: string): string | undefined {
+ return Object.entries(env).find(([key]) => key.toUpperCase() === name)?.[1];
+}
+
+function throughShim(shim: string, args: readonly string[], read: (path: string) => string): Command {
+ let text = '';
+ try {
+ text = read(shim);
+ } catch {
+ // Unreadable reads as unrecognized, which is refused below.
+ }
+ const target = [...text.matchAll(SHIM_TARGET)].map(([, path]) => path).find((path) => !/(^|\\)node\.exe$/i.test(path));
+ if (target) {
+ const file = win32.join(win32.dirname(shim), target);
+ if (/\.(exe|com)$/i.test(file)) return { file, args: [...args] };
+ // A shim for a script names the interpreter it looks for beside itself; only Node's is ours to stand in for.
+ if (/\\node\.exe"/i.test(text)) return { file: process.execPath, args: [file, ...args] };
+ }
+ throw new RunError(
+ 'AGENT_UNUSABLE',
+ `"${shim}" is a batch file Browsentic cannot see through, and it starts no batch file itself, because a prompt ` +
+ `cannot cross cmd.exe intact. Set this agent's "bin" in ${configPath} to the program that file runs.`,
+ );
+}
+
+/** How long Windows will find this command line: each argument quoted, its quotes and backslashes escaped. */
+export function commandLineLength({ file, args }: Command): number {
+ const quoted = (arg: string) => arg.length + 2 + (arg.match(/["\\]/g)?.length ?? 0);
+ return [file, ...args].reduce((total, arg) => total + quoted(arg) + 1, 0);
+}
+
+/**
+ * Starts an agent CLI: stdout and stderr piped, stdin closed unless it is to be written to. Refuses
+ * a batch file it cannot see through, and a command line too long for Windows to start.
+ */
+export function spawnCli(
+ bin: string,
+ args: readonly string[],
+ { stdin = 'ignore', ...options }: Omit<SpawnOptions, 'stdio'> & { stdin?: 'ignore' | 'pipe' } = {},
+ platform: NodeJS.Platform = process.platform,
+): CliProcess {
+ const command = resolveCommand(bin, args, { platform, env: options.env ?? process.env });
+ if (platform === 'win32') {
+ const length = commandLineLength(command);
+ if (length >= WINDOWS_COMMAND_LINE_MAX) {
+ throw new RunError(
+ 'AGENT_FAILED',
+ `This turn is too long for Windows to start: its command line would be ${length} characters, past the ${WINDOWS_COMMAND_LINE_MAX} ` +
+ 'Windows allows. Start a new conversation, or leave out site notes, attached files or fetched data.',
+ );
+ }
+ }
+ try {
+ return spawn(command.file, command.args, { ...options, stdio: [stdin, 'pipe', 'pipe'], windowsHide: true }) as CliProcess;
+ } catch (error) {
+ throw new RunError('AGENT_UNUSABLE', `Could not start "${command.file}": ${(error as Error).message}`);
+ }
+}
+
+/**
+ * Stops a CLI. On Windows that ends it and everything it started, at once, since there is no signal
+ * it could pass on; a process already gone is left alone, so its id cannot reach whatever reused it.
+ */
+export function stopTree(child: ChildProcess, signal: NodeJS.Signals, platform: NodeJS.Platform = process.platform): void {
+ if (platform !== 'win32') {
+ child.kill(signal);
+ return;
+ }
+ if (child.pid === undefined || child.exitCode !== null || child.signalCode !== null) return;
+ execFile('taskkill', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true }, (error) => {
+ if (error) child.kill(signal);
+ });
+}
diff --git a/src/daemon/agent/runners/cursor.ts b/src/daemon/agent/runners/cursor.ts
index 7d3650c..3b4bbca 100644
--- a/src/daemon/agent/runners/cursor.ts
+++ b/src/daemon/agent/runners/cursor.ts
@@ -1,4 +1,3 @@
-import { spawn } from 'node:child_process';
import { readFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
@@ -6,6 +5,7 @@ import type { AgentProblem } from '@/lib/agents/catalog';
import { stateDir } from '../../lockfile';
import type { AgentSettings } from '../config';
import { MCP_SERVER_NAME } from './claude';
+import { spawnCli, stopTree, type CliProcess } from './command';
import { conversationDir, parseJsonLine, sweepRunDirs } from './util';
import type { JsonContext, Listing, Plan, Runner, RunMode, StreamContext, StreamReader, StreamSink } from './types';
@@ -219,6 +219,12 @@ export const cursorRunner: Runner = {
* the opposite case.
*/
function signedIn(bin: string): Promise<boolean> {
+ let child: CliProcess;
+ try {
+ child = spawnCli(bin, ['status']);
+ } catch {
+ return Promise.resolve(true);
+ }
return new Promise((resolve) => {
let output = '';
let settled = false;
@@ -229,9 +235,8 @@ function signedIn(bin: string): Promise<boolean> {
resolve(value);
};
- const child = spawn(bin, ['status'], { stdio: ['ignore', 'pipe', 'pipe'] });
const timer = setTimeout(() => {
- child.kill('SIGKILL');
+ stopTree(child, 'SIGKILL');
done(true);
}, STATUS_TIMEOUT_MS);
timer.unref();
diff --git a/src/daemon/agent/runners/drive.test.ts b/src/daemon/agent/runners/drive.test.ts
index 634391d..4a11e38 100644
--- a/src/daemon/agent/runners/drive.test.ts
+++ b/src/daemon/agent/runners/drive.test.ts
@@ -12,6 +12,7 @@ import { codexRunner } from './codex';
import { launch, runJson, runStream } from './drive';
import { jsonContext, streamContext } from './fixtures/support';
import { RunError, type Plan, type Runner, type StreamReader, type StreamSink } from './types';
+import { bits, modeOf } from '../../test/modes';
/** Each line the stand-in prints is one sink call, as JSON: ["text", "hello"]. */
const replay: StreamReader = (line, sink) => {
@@ -88,6 +89,21 @@ describe('a streamed run', () => {
});
});
+ test("a plan's input reaches the agent on stdin, which is then closed, and never on its command line", async () => {
+ const script = `let heard = ''; process.stdin.on('data', (chunk) => (heard += chunk)).on('end', () => {
+ console.log(JSON.stringify(['text', heard + ' | argv:' + process.argv.slice(1).join(' ')]));
+ console.log('["done","end_turn"]');
+ });`;
+ const { said } = await run(standIn(script, (real) => ({ ...real, input: 'what does "this" page cost?\nand the next one' })));
+ expect(said).toBe('what does "this" page cost?\nand the next one | argv:');
+ });
+
+ test('an agent gone before it reads its input fails the run as usual, and the daemon carries on', async () => {
+ const script = 'process.exit(3)';
+ const refused = await failure(run(standIn(script, (real) => ({ ...real, input: 'x'.repeat(1 << 20) }))));
+ expect(refused).toMatchObject({ code: 'AGENT_FAILED' });
+ });
+
test('a run that never names a session reports none, so a stale one is not resumed', async () => {
expect((await run(standIn(printing(['done', 'end_turn'])))).outcome).toEqual({ stopReason: 'end_turn', sessionId: null });
});
@@ -110,10 +126,10 @@ describe('a streamed run', () => {
const cwd = join(antigravityRunner.workspace('run'), 'files-conversation');
expect({
said,
- directory: statSync(cwd).mode & 0o777,
- instructions: statSync(join(cwd, 'AGENTS.md')).mode & 0o777,
- mcpConfig: statSync(join(cwd, '.agents', 'mcp_config.json')).mode & 0o777,
- }).toEqual({ said: expect.stringMatching(/^You are Browsentic\.\n/), directory: 0o700, instructions: 0o600, mcpConfig: 0o600 });
+ directory: modeOf(cwd),
+ instructions: modeOf(join(cwd, 'AGENTS.md')),
+ mcpConfig: modeOf(join(cwd, '.agents', 'mcp_config.json')),
+ }).toEqual({ said: expect.stringMatching(/^You are Browsentic\.\n/), directory: bits(0o700), instructions: bits(0o600), mcpConfig: bits(0o600) });
});
test("a folder a conversation keeps is new again on every turn, so the sweep ages it from its last", async () => {
diff --git a/src/daemon/agent/runners/drive.ts b/src/daemon/agent/runners/drive.ts
index 078e68d..6c611ef 100644
--- a/src/daemon/agent/runners/drive.ts
+++ b/src/daemon/agent/runners/drive.ts
@@ -1,14 +1,14 @@
-import { spawn, type ChildProcessByStdio } from 'node:child_process';
import { mkdirSync, utimesSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { createInterface } from 'node:readline';
-import type { Readable, Writable } from 'node:stream';
import type { RunEvent } from '@/lib/actions/protocol';
import { AGENTS, type AgentKind } from '@/lib/agents/catalog';
import { describeContainment, sealEnv, sealedAway, sealingStream, vetPlan, type SpawnMode } from '../../guardrails';
import { configPath, type AgentSettings } from '../config';
import { stateDir } from '../../lockfile';
import { log } from '../../log';
+import { spawnCli, stopTree, type CliProcess } from './command';
+import { installHint } from './util';
import {
CONVERSATION_REFUSED,
RunError,
@@ -26,8 +26,6 @@ const KILL_GRACE_MS = 5_000;
const STRIPPED = ['CLAUDECODE', 'CLAUDE_CODE_ENTRYPOINT', 'BROWSENTIC_AGENT_RUN'];
-type Child = ChildProcessByStdio<Writable | null, Readable, Readable>;
-
/** What a plan is spawned with: stdin stays closed unless the CLI is held in a conversation over it. */
type Stdin = 'ignore' | 'pipe';
@@ -43,7 +41,7 @@ export function launch(
plan: Plan,
signal: AbortSignal,
stdin: Stdin = 'ignore',
-): { child: Child; release: () => void; stop: () => void } {
+): { child: CliProcess; release: () => void; stop: () => void } {
const problems = vetPlan(kind, mode, plan, stateDir);
if (problems.length) {
throw new RunError(
@@ -68,15 +66,14 @@ export function launch(
if (dropped.length) log(`sealed ${dropped.length} credential-shaped variables out of the ${kind} environment`);
const env = { ...childEnv(kind), ...plan.env };
- const child = spawn(settings.bin, plan.args, {
- cwd: plan.cwd,
- env,
- stdio: [stdin, 'pipe', 'pipe'],
- }) as Child;
+ const child = spawnCli(settings.bin, plan.args, { cwd: plan.cwd, env, stdin: plan.input === undefined ? stdin : 'pipe' });
+ // A CLI that is gone before it has read its stdin fails the write, and that must not take the daemon with it.
+ child.stdin?.on('error', (error) => log(`${kind} stopped reading its stdin: ${error.message}`));
+ if (plan.input !== undefined) child.stdin?.end(plan.input);
const kill = () => {
- child.kill('SIGTERM');
- const hardKill = setTimeout(() => child.kill('SIGKILL'), KILL_GRACE_MS);
+ stopTree(child, 'SIGTERM');
+ const hardKill = setTimeout(() => stopTree(child, 'SIGKILL'), KILL_GRACE_MS);
hardKill.unref();
};
if (signal.aborted) kill();
@@ -96,7 +93,7 @@ function notInstalled(runner: Runner, settings: AgentSettings): RunError {
return new RunError(
'AGENT_MISSING',
`Could not run "${settings.bin}" — ${agent.label} is not installed, or not on the daemon's PATH. ` +
- `Install it (${agent.install}), or set {"agents":{"${runner.kind}":{"bin":"/absolute/path/to/${agent.bin}"}}} ` +
+ `Install it (${installHint(runner.kind)}), or set {"agents":{"${runner.kind}":{"bin":"/absolute/path/to/${agent.bin}"}}} ` +
`in ${configPath}.`,
);
}
@@ -154,7 +151,7 @@ function drive(
// A conversation ends when its stdin does; the CLI is asked to go, and stopped if it lingers.
const hangUp = () => {
- if (!child.stdin) return;
+ if (!conversation || !child.stdin) return;
child.stdin.end();
const lingering = setTimeout(stop, KILL_GRACE_MS);
lingering.unref();
diff --git a/src/daemon/agent/runners/index.test.ts b/src/daemon/agent/runners/index.test.ts
index c7fd231..dca6562 100644
--- a/src/daemon/agent/runners/index.test.ts
+++ b/src/daemon/agent/runners/index.test.ts
@@ -1,4 +1,4 @@
-import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { basename, dirname, join } from 'node:path';
import { afterEach, beforeAll, beforeEach, describe, expect, test, vi } from 'vitest';
@@ -6,6 +6,7 @@ import { AGENT_KINDS, AGENTS, type AgentKind } from '@/lib/agents/catalog';
import { stateDir } from '../../lockfile';
import type { AgentConfig, AgentSettings } from '../config';
import { MCP_RULE, settingsPath } from './antigravity';
+import { stubCli } from './fixtures/support';
import { agentState, grantRunner, mcpServerFor, refreshModelLists, RUNNERS, runnerFor } from './index';
const bin = join(stateDir, 'stub-bin');
@@ -16,15 +17,13 @@ const probes = join(stateDir, 'probes.log');
* version probe is recorded: a runner's `check()` may call the binary again — Cursor asks it
* whether it is signed in — and those are not what `rounds()` is counting.
*/
-const stub = (name: string, { prints = `${name} 1.0.0`, exit = 0 } = {}) => {
- const path = join(bin, name);
- writeFileSync(
- path,
- `#!/bin/sh\ncase "$1" in --version) echo ${name} >> "${probes}" ;; esac\necho "${prints}" >&2\nexit ${exit}\n`,
+const stub = (name: string, { prints = `${name} 1.0.0`, exit = 0 } = {}) =>
+ stubCli(
+ join(bin, name),
+ `if (process.argv[2] === '--version') require('node:fs').appendFileSync(${JSON.stringify(probes)}, ${JSON.stringify(`${name}\n`)});
+console.error(${JSON.stringify(prints)});
+process.exit(${exit});`,
);
- chmodSync(path, 0o755);
- return path;
-};
/** The stubs probed so far, a round at a time. Every agent is probed at once, so each round is sorted. */
const rounds = () => {
@@ -113,6 +112,15 @@ describe('readiness probes', () => {
});
});
+ test('an agent that cannot be started at all is unusable on its own, and the rest still answer', async () => {
+ const state = await agentState(configWith({ codex: { bin: `${join(bin, 'codex')}\0` } }), { refresh: true });
+ expect(state.runners.find((status) => status.kind === 'codex')).toMatchObject({
+ ready: false,
+ problem: { code: 'AGENT_UNUSABLE', fix: expect.stringContaining('"codex":{"bin"') },
+ });
+ expect(state.runners.find((status) => status.kind === 'claude')).toMatchObject({ ready: true });
+ });
+
test('an installed agent that still needs setting up is not ready, and says why', async () => {
expect(await runner('antigravity', configWith({}))).toMatchObject({
ready: false,
diff --git a/src/daemon/agent/runners/index.ts b/src/daemon/agent/runners/index.ts
index 3c9d831..af1da29 100644
--- a/src/daemon/agent/runners/index.ts
+++ b/src/daemon/agent/runners/index.ts
@@ -1,4 +1,3 @@
-import { spawn } from 'node:child_process';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import {
@@ -9,17 +8,19 @@ import {
type AgentState,
type RunnerStatus,
} from '@/lib/agents/catalog';
-import { activeAgent, type AgentConfig, type AgentSettings } from '../config';
+import { activeAgent, configPath, type AgentConfig, type AgentSettings } from '../config';
import { log } from '../../log';
import { antigravityRunner } from './antigravity';
import { claudeRunner } from './claude';
import { codexRunner } from './codex';
+import { spawnCli, stopTree, type CliProcess } from './command';
import { cursorRunner } from './cursor';
import { grokRunner } from './grok';
import { modelsFor, refreshModels } from './models';
import { opencodeRunner } from './opencode';
import { qwenRunner } from './qwen';
import type { McpServer, Runner } from './types';
+import { installHint } from './util';
import { vibeRunner } from './vibe';
export const RUNNERS: Record<AgentKind, Runner> = {
@@ -117,7 +118,20 @@ async function probe(runner: Runner, settings: AgentSettings): Promise<RunnerSta
problem: {
code: 'AGENT_MISSING',
message: `${agent.label} is not installed, or "${settings.bin}" is not on the daemon's PATH.`,
- fix: agent.install,
+ fix: installHint(runner.kind),
+ },
+ };
+ }
+ if (found.code === 'AGENT_UNUSABLE') {
+ return {
+ kind: runner.kind,
+ bin: settings.bin,
+ model: settings.model,
+ ready: false,
+ problem: {
+ code: 'AGENT_UNUSABLE',
+ message: found.detail ?? `"${settings.bin}" could not be started.`,
+ fix: `{"agents":{"${runner.kind}":{"bin":"<the program itself>"}}} in ${configPath}`,
},
};
}
@@ -130,7 +144,7 @@ async function probe(runner: Runner, settings: AgentSettings): Promise<RunnerSta
problem: {
code: 'AGENT_UNUSABLE',
message: `"${settings.bin} ${runner.versionArgs.join(' ')}" failed${found.detail ? `: ${found.detail}` : ''}.`,
- fix: agent.install,
+ fix: installHint(runner.kind),
},
};
}
@@ -147,20 +161,32 @@ async function probe(runner: Runner, settings: AgentSettings): Promise<RunnerSta
};
}
-function version(bin: string, args: string[]): Promise<{ ok: boolean; code?: string; detail?: string }> {
+interface Found {
+ ok: boolean;
+ code?: string;
+ detail?: string;
+}
+
+function version(bin: string, args: string[]): Promise<Found> {
+ let child: CliProcess;
+ try {
+ child = spawnCli(bin, args);
+ } catch (error) {
+ // One agent that cannot be started must not take the others' answers down with it.
+ return Promise.resolve({ ok: false, code: (error as { code?: string }).code, detail: (error as Error).message });
+ }
return new Promise((resolve) => {
let output = '';
let settled = false;
- const done = (result: { ok: boolean; code?: string; detail?: string }) => {
+ const done = (result: Found) => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve(result);
};
- const child = spawn(bin, args, { stdio: ['ignore', 'pipe', 'pipe'] });
const timer = setTimeout(() => {
- child.kill('SIGKILL');
+ stopTree(child, 'SIGKILL');
done({ ok: false, detail: 'timed out' });
}, PROBE_TIMEOUT_MS);
timer.unref();
diff --git a/src/daemon/agent/runners/models.ts b/src/daemon/agent/runners/models.ts
index 6d3cf15..3565190 100644
--- a/src/daemon/agent/runners/models.ts
+++ b/src/daemon/agent/runners/models.ts
@@ -1,10 +1,10 @@
-import { spawn } from 'node:child_process';
import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
import { basename, join } from 'node:path';
import { AGENTS, isModelId, type AgentKind, type ModelList } from '@/lib/agents/catalog';
import { stateDir } from '../../lockfile';
import { log } from '../../log';
import type { AgentSettings } from '../config';
+import { spawnCli, stopTree, type CliProcess } from './command';
import { childEnv } from './drive';
import type { Listing, ModelLister, Runner } from './types';
@@ -121,6 +121,13 @@ function list(kind: AgentKind, bin: string, args: string[]): Promise<Listing | {
const command = `"${[basename(bin), ...args].join(' ')}"`;
const group = process.platform !== 'win32';
+ let child: CliProcess;
+ try {
+ child = spawnCli(bin, args, { cwd, env: { ...childEnv(kind), NO_COLOR: '1' }, detached: group });
+ } catch (error) {
+ return Promise.resolve({ error: (error as Error).message });
+ }
+
return new Promise((resolve) => {
let stdout = '';
let stderr = '';
@@ -133,17 +140,11 @@ function list(kind: AgentKind, bin: string, args: string[]): Promise<Listing | {
resolve(result);
};
- const child = spawn(bin, args, {
- cwd,
- env: { ...childEnv(kind), NO_COLOR: '1' },
- stdio: ['ignore', 'pipe', 'pipe'],
- detached: group,
- });
// The whole group, so a wrapper script's own children go with it.
const stop = (error: string) => {
try {
if (group && child.pid) process.kill(-child.pid, 'SIGKILL');
- else child.kill('SIGKILL');
+ else stopTree(child, 'SIGKILL');
} catch {
child.kill('SIGKILL');
}
diff --git a/src/daemon/agent/runners/types.ts b/src/daemon/agent/runners/types.ts
index 8d3402b..1504825 100644
--- a/src/daemon/agent/runners/types.ts
+++ b/src/daemon/agent/runners/types.ts
@@ -24,6 +24,8 @@ export interface Plan {
cwd: string;
env?: Record<string, string>;
files?: WorkspaceFile[];
+ /** Written to the CLI's stdin, which is then closed: what is too long, or too page-made, for argv. */
+ input?: string;
}
export interface StreamContext {
diff --git a/src/daemon/agent/runners/util.test.ts b/src/daemon/agent/runners/util.test.ts
index 6ec8343..103291c 100644
--- a/src/daemon/agent/runners/util.test.ts
+++ b/src/daemon/agent/runners/util.test.ts
@@ -2,7 +2,8 @@ import { existsSync, mkdirSync, readFileSync, utimesSync } from 'node:fs';
import { join } from 'node:path';
import { describe, expect, test } from 'vitest';
import { logPath, stateDir } from '../../lockfile';
-import { effortOf, parseJsonBlob, parseJsonLine, sweepRunDirs } from './util';
+import { AGENTS } from '@/lib/agents/catalog';
+import { effortOf, installHint, parseJsonBlob, parseJsonLine, sweepRunDirs } from './util';
describe('sweeping run directories', () => {
const base = join(stateDir, 'sweep-test');
@@ -63,3 +64,14 @@ describe('reading JSON a CLI printed', () => {
expect([parseJsonBlob('no braces here'), parseJsonBlob('} backwards {'), parseJsonBlob('{"broken": }')]).toEqual([null, null, null]);
});
});
+
+describe('how to install an agent', () => {
+ test('an npm or uv install is the same command everywhere', () => {
+ expect([installHint('codex', 'win32'), installHint('vibe', 'win32')]).toEqual([AGENTS.codex.install, AGENTS.vibe.install]);
+ });
+
+ test('a line piped into a POSIX shell is the docs on Windows, and the line itself elsewhere', () => {
+ expect([installHint('grok', 'win32'), installHint('cursor', 'win32')]).toEqual([AGENTS.grok.docs, AGENTS.cursor.docs]);
+ expect([installHint('grok', 'darwin'), installHint('cursor', 'linux')]).toEqual([AGENTS.grok.install, AGENTS.cursor.install]);
+ });
+});
diff --git a/src/daemon/agent/runners/util.ts b/src/daemon/agent/runners/util.ts
index 5cc04cd..6d9c20d 100644
--- a/src/daemon/agent/runners/util.ts
+++ b/src/daemon/agent/runners/util.ts
@@ -1,5 +1,6 @@
import { readdirSync, rmSync, statSync } from 'node:fs';
import { join } from 'node:path';
+import { AGENTS, type AgentKind } from '@/lib/agents/catalog';
import { log } from '../../log';
import type { AgentSettings } from '../config';
@@ -17,6 +18,12 @@ export const browserToolsDidNotStart = (label: string): string =>
`${label} could not start Browsentic's browser tools, so this run could not reach the page. ` +
'Run "browsentic restart", then send the message again.';
+/** How to install an agent here. A line piped into a POSIX shell means nothing on Windows, so there it is the docs. */
+export function installHint(kind: AgentKind, platform: NodeJS.Platform = process.platform): string {
+ const { install, docs } = AGENTS[kind];
+ return platform === 'win32' && /\|\s*(ba)?sh\b/.test(install) ? docs : install;
+}
+
/** Concurrent runs each get their own workspace; yesterday's are nobody's. */
export function sweepRunDirs(base: string, ttlMs = RUN_DIR_TTL_MS): void {
let entries: string[];
diff --git a/src/daemon/agent/service.test.ts b/src/daemon/agent/service.test.ts
index 4e5d370..8f969b3 100644
--- a/src/daemon/agent/service.test.ts
+++ b/src/daemon/agent/service.test.ts
@@ -1,10 +1,11 @@
import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
-import { dirname } from 'node:path';
+import { dirname, join } from 'node:path';
import { beforeEach, describe, expect, test, vi } from 'vitest';
import { FOCUS_SHOT_ACTION } from '@/lib/actions/reserved';
import type { RunEvent } from '@/lib/actions/protocol';
import { failure } from '@/lib/actions/protocol';
import { configPath } from './config';
+import { stubCli } from './runners/fixtures/support';
import { AgentSession } from './service';
const CODE_TOOLS = ['page.injectCode', 'page.runCode'];
@@ -55,8 +56,7 @@ describe("what a run's tool list holds", () => {
describe('answering a captcha', () => {
test('asks once, then lets the rest of that run’s rounds through without asking again', async () => {
- const agent = `${dirname(configPath)}/agent-that-waits.sh`;
- writeFileSync(agent, '#!/bin/sh\nsleep 30\n', { mode: 0o755 });
+ const agent = stubCli(join(dirname(configPath), 'agent-that-waits'), 'setTimeout(() => {}, 30_000);');
writeFileSync(configPath, JSON.stringify({ claudeBin: agent }));
const events: RunEvent[] = [];
const invoked: string[] = [];
@@ -94,17 +94,20 @@ describe('a follow-up in a conversation whose agent keeps its first prompt', ()
const dir = `${dirname(configPath)}/prompt-turns`;
rmSync(dir, { recursive: true, force: true });
mkdirSync(dir, { recursive: true });
- const agent = `${dir}/claude.sh`;
- writeFileSync(
- agent,
- [
- '#!/bin/sh',
- 'if [ "$1" = "--version" ]; then echo "2.1.283 (Claude Code)"; exit 0; fi',
- `n=$(ls "${dir}" | grep -c '^turn-'); printf '%s' "$2" > "${dir}/turn-$n"`,
- 'echo \'{"type":"system","subtype":"init","session_id":"sess-1","mcp_servers":[{"name":"browsentic","status":"connected"}]}\'',
- 'echo \'{"type":"result","subtype":"success","is_error":false,"stop_reason":"end_turn","result":"ok"}\'',
- ].join('\n'),
- { mode: 0o755 },
+ const agent = stubCli(
+ join(dir, 'claude'),
+ `const fs = require('node:fs');
+if (process.argv[2] === '--version') {
+ console.log('2.1.283 (Claude Code)');
+ process.exit(0);
+}
+const turn = ${JSON.stringify(dir)} + '/turn-' + fs.readdirSync(${JSON.stringify(dir)}).filter((name) => name.startsWith('turn-')).length;
+let heard = '';
+process.stdin.on('data', (chunk) => (heard += chunk)).on('end', () => {
+ fs.writeFileSync(turn, heard);
+ console.log(JSON.stringify({ type: 'system', subtype: 'init', session_id: 'sess-1', mcp_servers: [{ name: 'browsentic', status: 'connected' }] }));
+ console.log(JSON.stringify({ type: 'result', subtype: 'success', is_error: false, stop_reason: 'end_turn', result: 'ok' }));
+});`,
);
writeFileSync(configPath, JSON.stringify({ claudeBin: agent }));
const done: string[] = [];
diff --git a/src/daemon/agent/service.ts b/src/daemon/agent/service.ts
index 400afbe..788322b 100644
--- a/src/daemon/agent/service.ts
+++ b/src/daemon/agent/service.ts
@@ -1,4 +1,5 @@
import { randomUUID } from 'node:crypto';
+import { basename } from 'node:path';
import {
failure,
success,
@@ -707,7 +708,7 @@ function summarize(input: unknown, result: ActionResult): string {
const shot = result.data as { dataUrl?: unknown; width?: unknown; height?: unknown; savedTo?: unknown } | null;
if (shot && typeof shot.dataUrl === 'string') {
- const saved = typeof shot.savedTo === 'string' ? ` → ${shot.savedTo.split('/').pop()}` : '';
+ const saved = typeof shot.savedTo === 'string' ? ` → ${basename(shot.savedTo)}` : '';
return clip(`image ${shot.width ?? '?'}×${shot.height ?? '?'}${saved}`);
}
diff --git a/src/daemon/cli.ts b/src/daemon/cli.ts
index 4dba904..b5cf9af 100644
--- a/src/daemon/cli.ts
+++ b/src/daemon/cli.ts
@@ -168,12 +168,17 @@ async function serve(): Promise<void> {
await server.connect(new StdioServerTransport());
log(`stdio MCP server attached to daemon on port ${lock.port}`);
- const shutdown = async () => {
- await bridge.close();
- await server.close();
- process.exit(0);
- };
+ let stopping: Promise<void> | undefined;
+ const shutdown = () =>
+ (stopping ??= (async () => {
+ await bridge.close();
+ await server.close();
+ process.exit(0);
+ })());
for (const signal of ['SIGINT', 'SIGTERM'] as const) process.on(signal, () => void shutdown());
+ // A client that is gone closes stdin. On Windows that is often all it does, since a CLI ended there
+ // takes nothing with it, and a server that waited on would hold its socket to the daemon for good.
+ for (const event of ['end', 'close'] as const) process.stdin.once(event, () => void shutdown());
}
function printTools(): void {
diff --git a/src/daemon/ensure-daemon.ts b/src/daemon/ensure-daemon.ts
index 8c9530e..506759c 100644
--- a/src/daemon/ensure-daemon.ts
+++ b/src/daemon/ensure-daemon.ts
@@ -1,4 +1,4 @@
-import { spawn } from 'node:child_process';
+import { spawn, spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { clearLockfile, holdWake, isRunning, readLockfile, type Lockfile } from './lockfile';
@@ -23,6 +23,7 @@ export async function ensureDaemon(): Promise<Lockfile> {
detached: true,
stdio: 'ignore',
env,
+ windowsHide: true,
});
child.unref();
@@ -79,7 +80,11 @@ export interface StopResult {
stubborn: RunningDaemon[];
}
-/** SIGTERM every daemon, then SIGKILL whatever is still standing, and drop the lockfile. */
+/**
+ * SIGTERM every daemon, then SIGKILL whatever is still standing, and drop the lockfile. Windows has no
+ * SIGTERM to catch — a kill there ends the daemon alone, and the agent CLIs it started run on — so each
+ * one is ended there with everything it started.
+ */
export async function stopDaemons(graceMs = 5_000): Promise<StopResult> {
holdWake();
const daemons = await runningDaemons();
@@ -94,6 +99,10 @@ export async function stopDaemons(graceMs = 5_000): Promise<StopResult> {
}
function kill(pid: number, signal: NodeJS.Signals): void {
+ if (process.platform === 'win32') {
+ spawnSync('taskkill', ['/PID', String(pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true });
+ return;
+ }
try {
process.kill(pid, signal);
} catch {