From 441891fcb1987ab0ffb50a43dec54ccd8a4e6a4e Mon Sep 17 00:00:00 2001 From: default-cybe <201046277+default-cybe@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:23:20 -0800 Subject: [PATCH 1/8] Windows: run commands in cmd.exe when Git Bash is missing, tell the agent the shell The hub's Bash tool sent its bash wrapper (exec, trap, eval) to every device, so a Windows PC without Git Bash failed every command with "'exec' is not recognized". A cmd.exe device now gets a cmd wrapper that reports the final folder and keeps the exit code. Windows picks Git Bash over the WSL launcher, kills with taskkill /T, and reports the shell exec uses. The Environment block names the OS and shell, and Devices suggests Git for Windows on a cmd-only PC. Committed-by: Conclave (cliproxy/claude-opus-5-5) --- CHANGELOG.md | 7 ++ packages/core/src/engine/engine.ts | 1 + packages/core/src/machine/local.ts | 54 +++++++- packages/core/src/session/prompt.ts | 13 ++ packages/core/src/session/runner.ts | 2 +- packages/core/src/tools/bash.ts | 41 +++++- packages/core/test/session/project.test.ts | 8 ++ packages/core/test/tools/bash.test.ts | 50 +++++++- .../core/test/tools/local-machine.test.ts | 26 +++- packages/daemon-rs/src/info.rs | 3 +- packages/daemon-rs/src/procs.rs | 119 ++++++++++++++++-- .../web/src/features/devices/DevicesPage.tsx | 8 ++ 12 files changed, 306 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a99b38ddf..1402ffab9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,13 @@ from the section of its version (`scripts/releases/notes.ts`); a release without one fails. At tag time, rename `[Unreleased]` to the version and date, like `## [0.4.16] - 2026-10-24`. +## [Unreleased] + +### Fixed + +- Windows: commands run on PCs without Git Bash (cmd.exe), and Git Bash is used instead of WSL when installed +- The agent is told the device's OS and shell, so it uses Windows commands there + ## [0.4.102] - 2026-11-17 ### Added diff --git a/packages/core/src/engine/engine.ts b/packages/core/src/engine/engine.ts index 31c280bec..57c351347 100644 --- a/packages/core/src/engine/engine.ts +++ b/packages/core/src/engine/engine.ts @@ -2735,6 +2735,7 @@ export class Engine implements EngineApi { session, agent, modelRef, mode, toolNames, platform: info?.platform ?? process.platform, hostname: info?.hostname, + shell: info?.shell, isGitRepo: isGit, deviceName: this.devices.list().find((d) => d.id === session.device)?.name ?? session.device, projectInstructions, profile, skills, firstMessage, diff --git a/packages/core/src/machine/local.ts b/packages/core/src/machine/local.ts index 8cb609452..fe39a1bad 100644 --- a/packages/core/src/machine/local.ts +++ b/packages/core/src/machine/local.ts @@ -1,4 +1,4 @@ -import { promises as fs } from 'node:fs'; +import { existsSync, promises as fs } from 'node:fs'; import * as os from 'node:os'; import * as nodePath from 'node:path'; import type { MachineInfo } from '../types'; @@ -54,6 +54,15 @@ function untrackGroup(pid: number | undefined): void { function killTree(pid: number | undefined, signal: NodeJS.Signals): void { if (!pid) return; + if (process.platform === 'win32') { + // Windows has no process groups (kill(-pid) throws): taskkill /T ends the shell and its children + try { + Bun.spawnSync(['taskkill', '/pid', String(pid), '/T', '/F'], { stdout: 'ignore', stderr: 'ignore' }); + } catch { + /* already gone */ + } + return; + } try { process.kill(-pid, signal); return; @@ -67,6 +76,30 @@ function killTree(pid: number | undefined, signal: NodeJS.Signals): void { } } +export const isCmd = (shell: string) => /(^|[\\/])cmd(\.exe)?$/i.test(shell); + +/** The argv that runs one command line: cmd.exe takes /d /s /c, every other shell -c. */ +export function shellArgv(shell: string, command: string): string[] { + return isCmd(shell) ? [shell, '/d', '/s', '/c', command] : [shell, '-c', command]; +} + +/** + * Git Bash on Windows: bash on PATH unless it is the WSL launcher (System32 + * or WindowsApps), else next to git.exe, else where Git for Windows installs. + */ +export function findWindowsBash(env: Record, which: (name: string) => string | null, exists: (path: string) => boolean): string | undefined { + const W = nodePath.win32; + const onPath = which('bash'); + if (onPath && !/\\(system32|windowsapps)\\/i.test(onPath)) return onPath; + const git = which('git'); + const candidates = [ + git && W.join(W.dirname(W.dirname(git)), 'bin', 'bash.exe'), + env.ProgramFiles && W.join(env.ProgramFiles, 'Git', 'bin', 'bash.exe'), + env.LOCALAPPDATA && W.join(env.LOCALAPPDATA, 'Programs', 'Git', 'bin', 'bash.exe'), + ]; + return candidates.find((p): p is string => !!p && exists(p)); +} + /** Keeps the first and last part of a long stream and drops the middle. */ class HeadTailBuffer { private head = ''; @@ -245,7 +278,8 @@ export class LocalMachine implements Machine { platform: process.platform, arch: process.arch, home: os.homedir(), - shell: process.env.SHELL || this.shell(), + // on Windows SHELL (set inside Git Bash) is not what exec runs: report the shell exec picks + shell: (process.platform !== 'win32' && process.env.SHELL) || this.shell(), clis, capabilities, }; @@ -582,9 +616,14 @@ export class LocalMachine implements Machine { // Processes // ------------------------------------------------------------------------- - /** bash when available, else sh. */ + /** bash when available, else sh. On Windows Git Bash, else cmd.exe. */ shell(): string { - if (!this.shellPath) this.shellPath = Bun.which('bash') ?? (process.platform === 'win32' ? 'cmd.exe' : '/bin/sh'); + if (!this.shellPath) { + this.shellPath = + process.platform === 'win32' + ? (findWindowsBash(process.env, (n) => Bun.which(n), existsSync) ?? process.env.ComSpec ?? 'cmd.exe') + : (Bun.which('bash') ?? '/bin/sh'); + } return this.shellPath; } @@ -614,7 +653,7 @@ export class LocalMachine implements Machine { if (opts.signal?.aborted) return { ...fail('Aborted before start'), exitCode: null, aborted: true }; const shell = this.shell(); - const argv = shell.endsWith('cmd.exe') ? [shell, '/d', '/s', '/c', command] : [shell, '-c', command]; + const argv = shellArgv(shell, command); let proc: ReturnType>; try { proc = Bun.spawn(argv, { @@ -718,7 +757,10 @@ export class LocalMachine implements Machine { // a background shell (tools/shells.ts) names its command in the arguments const named = [command, ...args].join(' '); if (commandTouchesHubPrivate(named, cwd) || hubPrivateDirs().some((d) => cwd === d || cwd.startsWith(d + nodePath.sep))) throw Object.assign(new Error(privateRefusal(named)), { code: 'EACCES' }); - const proc = Bun.spawn([command, ...args], { + // a background shell asks for bash -c (tools/shells.ts): on Windows that is this machine's shell, which may be off PATH or cmd.exe + const shell = this.shell(); + const viaShell = (command === 'bash' || command === 'sh') && args.length === 2 && args[0] === '-c' && (process.platform === 'win32' || isCmd(shell)); + const proc = Bun.spawn(viaShell ? shellArgv(shell, args[1] as string) : [command, ...args], { cwd, env: this.env(opts.env), stdin: 'pipe', diff --git a/packages/core/src/session/prompt.ts b/packages/core/src/session/prompt.ts index 366a4194a..aaa6e9750 100644 --- a/packages/core/src/session/prompt.ts +++ b/packages/core/src/session/prompt.ts @@ -16,6 +16,8 @@ export interface PromptParts { toolNames: string[]; platform: string; hostname?: string; + /** The device's shell (MachineInfo.shell): on Windows cmd.exe means no Git Bash. */ + shell?: string; isGitRepo: boolean; deviceName: string; projectInstructions: Array<{ path: string; content: string }>; @@ -183,6 +185,16 @@ export function workflowStepNote(session: Session): string | undefined { return MODE_NOTES.workflow ?? WORKFLOW_STEP_FALLBACK; } +/** The Environment line on the device's OS and the shell the Bash tool runs in. */ +export function shellLine(platform: string, shell?: string): string { + if (platform === 'win32') { + if (shell && /(^|[\\/])cmd(\.exe)?$/i.test(shell)) return '- Shell: Windows, commands run in cmd.exe (no bash): use Windows commands (dir, type, findstr, where) or PowerShell via powershell -NoProfile -Command'; + return '- Shell: Windows with Git Bash: POSIX commands work; paths like D:\\x work as /d/x or D:/x'; + } + const os = platform === 'darwin' ? 'macOS' : platform === 'linux' ? 'Linux' : platform; + return `- Shell: ${os}, commands run in bash`; +} + /** * The system prompt is assembled from stable parts only (no clock times, no * per-turn data) so provider prompt caches keep hitting across turns. Dynamic @@ -196,6 +208,7 @@ export function buildSystemPrompt(p: PromptParts): SystemBlock[] { '# Environment', `- Working directory: ${p.session.cwd}`, `- Device: ${p.deviceName}${p.hostname ? ` (${p.hostname})` : ''}, platform ${p.platform}`, + shellLine(p.platform, p.shell), `- Git repository: ${p.isGitRepo ? 'yes' : 'no'}`, ...(p.testCommand ? [`- Test command: ${p.testCommand}`] : []), ...(p.workspace?.python3Only ? ['- Python: use python3; this device has no python command'] : []), diff --git a/packages/core/src/session/runner.ts b/packages/core/src/session/runner.ts index b03fa374b..4f86a3135 100644 --- a/packages/core/src/session/runner.ts +++ b/packages/core/src/session/runner.ts @@ -272,7 +272,7 @@ interface PromptSnapshot { /** The parts of a prompt read again once per user turn; the same text keeps the snapshot. */ function partsSignature(p: PromptParts): string { - return JSON.stringify([p.projectInstructions, p.skills.map((k) => [k.name, k.description]), p.isGitRepo, p.testCommand ?? '', p.workspace ?? {}, p.platform, p.hostname ?? '', p.deviceName, p.conclave ?? null, p.modelPin ?? '']); + return JSON.stringify([p.projectInstructions, p.skills.map((k) => [k.name, k.description]), p.isGitRepo, p.testCommand ?? '', p.workspace ?? {}, p.platform, p.shell ?? '', p.hostname ?? '', p.deviceName, p.conclave ?? null, p.modelPin ?? '']); } /** Every memory the snapshot shows is still there with the same text (new ones wait for the next rebuild). */ diff --git a/packages/core/src/tools/bash.ts b/packages/core/src/tools/bash.ts index 036c4ca48..0a3d137ec 100644 --- a/packages/core/src/tools/bash.ts +++ b/packages/core/src/tools/bash.ts @@ -7,6 +7,8 @@ import { isHeadless } from '../session/runner'; import { clampInt, fail, outputBudget, truncateMiddleOut } from './util'; import { KEEPS, KIND_NAMES, reduceOutput } from './compress'; import { HEAVY_COMMANDS_DEFAULT, HEAVY_WAIT_NOTE, heavyGate, isHeavyCommand } from './heavy-gate'; +import { isCmd } from '../machine/local'; +import type { MachineInfo } from '../types'; export interface BashInput { command: string; @@ -21,7 +23,7 @@ export const BASH_MAX_OUTPUT_CHARS = 30_000; const MACHINE_OUTPUT_CAP = 4 * 1024 * 1024; const PROGRESS_FLUSH_MS = 250; -const DESCRIPTION = `Run a shell command (bash -c) on the session's machine and return its combined stdout and stderr. +const DESCRIPTION = `Run a shell command on the session's machine and return its combined stdout and stderr. It runs in bash, or in cmd.exe on a Windows device without Git Bash; the Environment section names the shell. - The working directory persists between calls; environment variables and shell functions do not. Prefer absolute paths to cd. - timeout is in milliseconds (default ${BASH_DEFAULT_TIMEOUT_MS}, max ${BASH_MAX_TIMEOUT_MS}). Give a 5 to 10 word description of what the command does, e.g. "Run unit tests". @@ -70,9 +72,40 @@ export function extractCwd(text: string, marker: string): { text: string; cwd?: return { text: before + after, cwd: cwd || undefined }; } +/** + * The same for cmd.exe (a Windows device without Git Bash), which has no exec, + * trap or eval: the command runs inline, then the marker and %CD% go to stderr + * and cmd exits with the command's errorlevel. `call` and `%^X%` delay the + * expansion until that point (command-line mode keeps an unknown %^X%, the + * caret goes, call expands again). The command's own stderr stays on stderr; + * the tool appends it to stdout as it does for bash. cmd /c runs one line, so + * lines are joined with &. + * shortcut: an odd number of % in the command shifts the % pairs and loses the cwd; fine for cmd use, a PowerShell host would avoid it. + */ +export function wrapCmdCommand(marker: string, command: string): string { + const line = command.split(/\r?\n/).filter((l) => l.trim()).join(' & '); + return `${line} & call set __cc_ec=%^errorlevel%& call echo ${marker}%^CD% 1>&2 & call exit %^__cc_ec%`; +} + +/** The shell the device runs commands in (MachineInfo.shell): a paired device's from its hello, no round trip. */ +async function deviceShell(ctx: ToolContext): Promise { + const m = ctx.machine as { lastInfo?: MachineInfo; shell?: () => string }; + if (m.lastInfo) return m.lastInfo.shell; + // the hub's own machine: its exec shell, without info()'s CLI version probes + if (typeof m.shell === 'function') return m.shell(); + return (await ctx.machine.info().catch(() => undefined))?.shell; +} + /** The egress gateway's proxy variables of a Security mode call (session/egress.ts), set by run() for the helpers below. */ const egressOf = new WeakMap>(); +/** Git Bash on Windows prints /c/Users/me for C:\Users\me; a session in a Windows folder keeps the Windows form. */ +export function windowsCwd(cwd: string, sessionCwd: string): string { + const m = /^\/([a-zA-Z])(\/.*)?$/.exec(cwd); + if (!m || !/^[a-zA-Z]:[\\/]/.test(sessionCwd)) return cwd; + return `${m[1].toUpperCase()}:${(m[2] ?? '\\').replace(/\//g, '\\')}`; +} + function bashEnv(ctx: ToolContext, extra?: Record): Record { return { PAGER: 'cat', @@ -104,7 +137,8 @@ async function runForeground(input: BashInput, ctx: ToolContext): Promise { expect(env({ workspace: {} })).not.toContain('Python:'); expect(env({})).not.toContain('Check run when you stop'); }); + + test('the Environment block names the OS and shell', () => { + const base = { session: { cwd: '/w' }, agent: { name: 'coder', prompt: '' }, modelRef: 'm', mode: 'agent', toolNames: ['Bash'], platform: 'linux', isGitRepo: true, deviceName: 'hub', projectInstructions: [], profile: [], skills: [], subagents: [], date: '2026-10-20' } as never; + const env = (p: object) => buildSystemPrompt({ ...(base as object), ...p } as never)[1].text; + expect(env({ platform: 'win32', shell: 'C:\\WINDOWS\\system32\\cmd.exe' })).toContain('- Shell: Windows, commands run in cmd.exe (no bash): use Windows commands (dir, type, findstr, where) or PowerShell via powershell -NoProfile -Command'); + expect(env({ platform: 'win32', shell: 'C:\\Program Files\\Git\\bin\\bash.exe' })).toContain('- Shell: Windows with Git Bash: POSIX commands work; paths like D:\\x work as /d/x or D:/x'); + expect(env({ shell: '/bin/bash' })).toContain('- Shell: Linux, commands run in bash'); + }); }); describe('workspace facts in a session', () => { diff --git a/packages/core/test/tools/bash.test.ts b/packages/core/test/tools/bash.test.ts index 216778a87..e8021f023 100644 --- a/packages/core/test/tools/bash.test.ts +++ b/packages/core/test/tools/bash.test.ts @@ -1,7 +1,8 @@ import { afterAll, describe, expect, test } from 'bun:test'; import { mkdirSync, realpathSync } from 'node:fs'; import { join } from 'node:path'; -import { BashTool, isBlockingWait } from '../../src/tools/bash'; +import { BashTool, isBlockingWait, windowsCwd, wrapCmdCommand, wrapCommand } from '../../src/tools/bash'; +import type { Machine } from '../../src/machine/types'; import { BashOutputTool } from '../../src/tools/bash-output'; import { KillShellTool } from '../../src/tools/kill-shell'; import { shellRegistry } from '../../src/tools/shells'; @@ -179,6 +180,53 @@ describe('Bash', () => { expect(other.isError).toBe(true); }); + test('a Git Bash cwd on a Windows session comes back in Windows form', () => { + expect(windowsCwd('/c/Users/me/src', 'C:\\Users\\me')).toBe('C:\\Users\\me\\src'); + expect(windowsCwd('/d', 'C:\\Users\\me')).toBe('D:\\'); + expect(windowsCwd('/c/Users/me', '/home/me')).toBe('/c/Users/me'); + expect(windowsCwd('/home/me/src', '/home/me')).toBe('/home/me/src'); + }); + + test('a cmd.exe device gets the cmd wrapper; the cwd marker and exit code come back', async () => { + const sent: Array<{ command: string; env?: Record }> = []; + const machine = { + id: 'win', + lastInfo: { shell: 'C:\\WINDOWS\\system32\\cmd.exe' }, + exec: async (command: string, opts: { env?: Record }) => { + sent.push({ command, env: opts.env }); + const marker = /(__CONCLAVE_CWD_\w+__)/.exec(command)![1]; + return { exitCode: 2, stdout: 'File Not Found\r\n', stderr: `nope\r\n${marker}D:\\proj\\sub \r\n`, timedOut: false, aborted: false, durationMs: 5 }; + }, + } as unknown as Machine; + const out = await BashTool.run({ command: 'cd sub\ndir x' }, makeCtx({ cwd: 'D:\\proj', machine })); + const { command } = sent[0]!; + const marker = /(__CONCLAVE_CWD_\w+__)/.exec(command)![1]!; + expect(command).toBe(wrapCmdCommand(marker, 'cd sub\ndir x')); + expect(command).toBe(`cd sub & dir x & call set __cc_ec=%^errorlevel%& call echo ${marker}%^CD% 1>&2 & call exit %^__cc_ec%`); + expect(command).not.toContain('exec 3>&2'); + expect(out.isError).toBe(true); + expect(out.meta?.exitCode).toBe(2); + expect(out.meta?.cwd).toBe('D:\\proj\\sub'); + expect(text(out)).not.toContain('__CONCLAVE_CWD_'); + expect(text(out)).toContain('File Not Found'); + expect(text(out)).toContain('nope'); + }); + + test('a bash device still gets the POSIX wrapper', async () => { + const sent: string[] = []; + const machine = { + id: 'mac', + lastInfo: { shell: '/bin/zsh' }, + exec: async (command: string) => { + sent.push(command); + return { exitCode: 0, stdout: 'hi\n', stderr: '', timedOut: false, aborted: false, durationMs: 1 }; + }, + } as unknown as Machine; + await BashTool.run({ command: 'echo hi' }, makeCtx({ cwd: '/w', machine })); + const marker = /(__CONCLAVE_CWD_\w+__)/.exec(sent[0]!)![1]!; + expect(sent[0]).toBe(wrapCommand(marker)); + }); + test('readOnly and rule hooks', () => { const ro = BashTool.readOnly as (i: any) => boolean; expect(ro({ command: 'ls -la' })).toBe(true); diff --git a/packages/core/test/tools/local-machine.test.ts b/packages/core/test/tools/local-machine.test.ts index 29d360ce6..13a315225 100644 --- a/packages/core/test/tools/local-machine.test.ts +++ b/packages/core/test/tools/local-machine.test.ts @@ -1,7 +1,7 @@ import { afterAll, describe, expect, test } from 'bun:test'; import { homedir } from 'node:os'; import { join } from 'node:path'; -import { LocalMachine } from '../../src/machine/local'; +import { LocalMachine, findWindowsBash, shellArgv } from '../../src/machine/local'; import { tempDir } from './helpers'; const m = new LocalMachine(); @@ -86,6 +86,30 @@ describe('LocalMachine', () => { expect(await s.exited).toBeNull(); }); + test('cmd.exe runs its line with /d /s /c', async () => { + const cmd = new LocalMachine(); + // stands in for cmd.exe: a script that prints the argv it got + const fake = join(dir, 'cmd.exe'); + await cmd.writeFile(fake, '#!/bin/sh\nprintf "%s|" "$@"\n'); + await cmd.exec(`chmod 755 '${fake}'`, { cwd: dir }); + (cmd as any).shellPath = fake; + const r = await cmd.exec('ver & call echo x', { cwd: dir }); + expect(r.stdout).toBe('/d|/s|/c|ver & call echo x|'); + // a background shell's bash -c goes to cmd.exe too + const p = cmd.spawn('bash', ['-c', 'ver'], { cwd: dir }); + expect(await new Response(p.stdout as never).text()).toBe('/d|/s|/c|ver|'); + expect(shellArgv('C:\\WINDOWS\\system32\\cmd.exe', 'ver')).toEqual(['C:\\WINDOWS\\system32\\cmd.exe', '/d', '/s', '/c', 'ver']); + expect(shellArgv('/usr/bin/bash', 'ver')).toEqual(['/usr/bin/bash', '-c', 'ver']); + }); + + test('Windows shell: Git Bash, not the WSL launcher', () => { + const which = (paths: Record) => (n: string) => paths[n] ?? null; + const gitBash = 'C:\\Program Files\\Git\\bin\\bash.exe'; + expect(findWindowsBash({ ProgramFiles: 'C:\\Program Files' }, which({ bash: 'C:\\Windows\\System32\\bash.exe' }), (p) => p === gitBash)).toBe(gitBash); + expect(findWindowsBash({}, which({ git: 'D:\\Git\\cmd\\git.exe' }), (p) => p === 'D:\\Git\\bin\\bash.exe')).toBe('D:\\Git\\bin\\bash.exe'); + expect(findWindowsBash({}, which({}), () => true)).toBeUndefined(); + }); + test('info lists platform and cached CLIs', async () => { const info = await m.info(); expect(info.platform).toBe(process.platform); diff --git a/packages/daemon-rs/src/info.rs b/packages/daemon-rs/src/info.rs index b5f24d898..290ff64f0 100644 --- a/packages/daemon-rs/src/info.rs +++ b/packages/daemon-rs/src/info.rs @@ -145,8 +145,9 @@ async fn collect() -> Value { if clis.contains_key("git") { caps.push("git"); } + // on Windows SHELL (set inside Git Bash or MSYS) is not what exec runs: report the shell exec picks let shell = match std::env::var("SHELL") { - Ok(s) if !s.is_empty() => s, + Ok(s) if !s.is_empty() && !cfg!(windows) => s, _ => crate::procs::shell().to_string(), }; json!({ diff --git a/packages/daemon-rs/src/procs.rs b/packages/daemon-rs/src/procs.rs index 9326e4587..0c6623b96 100644 --- a/packages/daemon-rs/src/procs.rs +++ b/packages/daemon-rs/src/procs.rs @@ -82,8 +82,21 @@ pub fn kill_tree(pid: u32, sig: Sig) { #[cfg(windows)] pub fn kill_tree(pid: u32, _sig: Sig) { + use std::os::windows::process::CommandExt; use windows_sys::Win32::Foundation::CloseHandle; use windows_sys::Win32::System::Threading::{OpenProcess, TerminateProcess, PROCESS_TERMINATE}; + // no process groups on Windows: taskkill /T ends the shell and everything it started + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + let tree = std::process::Command::new("taskkill") + .args(["/pid", &pid.to_string(), "/T", "/F"]) + .creation_flags(CREATE_NO_WINDOW) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); + if matches!(tree, Ok(s) if s.success()) { + return; + } // SAFETY: plain Win32 calls on a process handle we open and close here. unsafe { let h = OpenProcess(PROCESS_TERMINATE, 0, pid); @@ -167,21 +180,55 @@ impl HeadTail { // Shell and commands // --------------------------------------------------------------------------- -/// bash when available, else sh (cmd.exe on Windows). +/// bash when available, else sh. On Windows Git Bash, else cmd.exe. pub fn shell() -> &'static str { static SHELL: OnceLock = OnceLock::new(); - SHELL.get_or_init(|| match crate::env::which("bash") { - Some(p) => p.to_string_lossy().into_owned(), - None => { - if cfg!(windows) { - "cmd.exe".into() - } else { - "/bin/sh".into() - } + SHELL.get_or_init(|| { + if cfg!(windows) { + let which = |n: &str| crate::env::which(n).map(|p| p.to_string_lossy().into_owned()); + find_windows_bash(|k: &str| std::env::var(k).ok(), which, |p: &str| std::path::Path::new(p).is_file()) + .or_else(|| std::env::var("ComSpec").ok()) + .unwrap_or_else(|| "cmd.exe".into()) + } else { + crate::env::which("bash").map(|p| p.to_string_lossy().into_owned()).unwrap_or_else(|| "/bin/sh".into()) } }) } +/// cmd.exe (also as ComSpec's full path), which takes /d /s /c instead of -c. +fn is_cmd(sh: &str) -> bool { + let l = sh.to_ascii_lowercase(); + let base = l.rsplit(|c: char| c == '\\' || c == '/').next().unwrap_or(""); + base == "cmd.exe" || base == "cmd" +} + +/// The folder a Windows path is in ("C:\Git\cmd\git.exe" is in "C:\Git\cmd"). +fn win_parent(p: &str) -> &str { + p.rfind(|c: char| c == '\\' || c == '/').map(|i| &p[..i]).unwrap_or("") +} + +/// Git Bash on Windows: bash on PATH unless it is the WSL launcher (System32 +/// or WindowsApps), else next to git.exe, else where Git for Windows installs. +pub fn find_windows_bash(var: impl Fn(&str) -> Option, which: impl Fn(&str) -> Option, exists: impl Fn(&str) -> bool) -> Option { + if let Some(p) = which("bash") { + let l = p.to_ascii_lowercase(); + if !l.contains("\\system32\\") && !l.contains("\\windowsapps\\") { + return Some(p); + } + } + let mut candidates = Vec::new(); + if let Some(git) = which("git") { + candidates.push(format!("{}\\bin\\bash.exe", win_parent(win_parent(&git)))); + } + if let Some(pf) = var("ProgramFiles") { + candidates.push(format!("{pf}\\Git\\bin\\bash.exe")); + } + if let Some(la) = var("LOCALAPPDATA") { + candidates.push(format!("{la}\\Programs\\Git\\bin\\bash.exe")); + } + candidates.into_iter().find(|c| exists(c)) +} + fn configure(cmd: &mut tokio::process::Command, own_group: bool) { #[cfg(unix)] if own_group { @@ -266,7 +313,7 @@ pub async fn exec(command: String, opts: ExecOpts, mut abort: watch::Receiver { pumps_done = true; } Some(sig) = kill_rx.recv() => { #[cfg(windows)] - { if !exited { let _ = child.start_kill(); } } + { + if !exited { + match pid { + Some(p) => kill_tree(p, sig), + None => { let _ = child.start_kill(); } + } + } + } #[cfg(unix)] { if let Some(p) = pid { kill_tree(p, sig); } } let _ = sig; @@ -672,6 +739,32 @@ mod tests { assert_eq!(b.finish(), "short"); } + #[test] + fn is_cmd_matches_cmd_exe_only() { + assert!(is_cmd("cmd.exe")); + assert!(is_cmd("C:\\WINDOWS\\system32\\CMD.EXE")); + assert!(is_cmd("cmd")); + assert!(!is_cmd("C:\\Program Files\\Git\\bin\\bash.exe")); + assert!(!is_cmd("/usr/bin/bash")); + assert!(!is_cmd("C:\\tools\\notcmd.exe")); + } + + #[test] + fn windows_bash_skips_wsl_and_finds_git_bash() { + let pf = |k: &str| (k == "ProgramFiles").then(|| "C:\\Program Files".to_string()); + let wsl = |n: &str| (n == "bash").then(|| "C:\\Windows\\System32\\bash.exe".to_string()); + let installed = |p: &str| p == "C:\\Program Files\\Git\\bin\\bash.exe"; + assert_eq!(find_windows_bash(pf, wsl, installed).as_deref(), Some("C:\\Program Files\\Git\\bin\\bash.exe")); + // git.exe on PATH: the bash of that Git + let git = |n: &str| (n == "git").then(|| "D:\\Git\\cmd\\git.exe".to_string()); + assert_eq!(find_windows_bash(|_: &str| None, git, |p: &str| p == "D:\\Git\\bin\\bash.exe").as_deref(), Some("D:\\Git\\bin\\bash.exe")); + // a real bash on PATH wins + let msys = |n: &str| (n == "bash").then(|| "C:\\msys64\\usr\\bin\\bash.exe".to_string()); + assert_eq!(find_windows_bash(|_: &str| None, msys, |_: &str| false).as_deref(), Some("C:\\msys64\\usr\\bin\\bash.exe")); + // no Git at all: none, so the daemon falls back to cmd.exe + assert_eq!(find_windows_bash(|_: &str| None, |_: &str| None, |_: &str| true), None); + } + #[test] fn head_tail_counts_utf16() { let mut b = HeadTail::new(4); diff --git a/packages/web/src/features/devices/DevicesPage.tsx b/packages/web/src/features/devices/DevicesPage.tsx index fb65330ce..a061c7a7d 100644 --- a/packages/web/src/features/devices/DevicesPage.tsx +++ b/packages/web/src/features/devices/DevicesPage.tsx @@ -395,6 +395,14 @@ function DeviceDetail({ d, running }: { d: Device; running: Session[] }) { {d.info.shell} + {d.info.platform === 'win32' && /(^|[\\/])cmd(\.exe)?$/i.test(d.info.shell) && ( +

+ + Install Git for Windows + {' '} + for full shell support +

+ )} {d.info.capabilities.length > 0 && {capabilityWords(d.info.capabilities)}} {d.info.daemon && ( From e946cb18feeb5ceae32b5b148cf204cdcbf19957 Mon Sep 17 00:00:00 2001 From: default-cybe <201046277+default-cybe@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:41:57 -0800 Subject: [PATCH 2/8] cmd wrapper: keep the marker after if/for and multi-line blocks, quote verbatim Review fixes: the command goes in parentheses so an if or for cannot take the marker into its body; lines join without & inside a ( ) block, rem and :: lines are dropped, and a trailing & is cut. cmd runs with /v:off, and on Windows the hub passes its line in quotes with windowsVerbatimArguments, as raw_arg does in the daemon, so Bun's own quoting cannot break inner quotes. Committed-by: Conclave (cliproxy/claude-opus-5-5) --- packages/core/src/machine/local.ts | 13 +++++++++++-- packages/core/src/tools/bash.ts | 15 +++++++++++---- packages/core/test/engine/platform-card.test.ts | 3 ++- packages/core/test/tools/bash.test.ts | 8 +++++++- packages/core/test/tools/local-machine.test.ts | 8 ++++---- packages/daemon-rs/src/procs.rs | 4 ++-- 6 files changed, 37 insertions(+), 14 deletions(-) diff --git a/packages/core/src/machine/local.ts b/packages/core/src/machine/local.ts index fe39a1bad..b22d00656 100644 --- a/packages/core/src/machine/local.ts +++ b/packages/core/src/machine/local.ts @@ -78,9 +78,14 @@ function killTree(pid: number | undefined, signal: NodeJS.Signals): void { export const isCmd = (shell: string) => /(^|[\\/])cmd(\.exe)?$/i.test(shell); -/** The argv that runs one command line: cmd.exe takes /d /s /c, every other shell -c. */ +/** + * The argv that runs one command line: cmd.exe takes /d /v:off /s /c, every + * other shell -c. On Windows cmd's line goes in quotes that /s strips, with + * windowsVerbatimArguments so Bun adds no quoting of its own (as raw_arg in daemon-rs). + */ export function shellArgv(shell: string, command: string): string[] { - return isCmd(shell) ? [shell, '/d', '/s', '/c', command] : [shell, '-c', command]; + if (!isCmd(shell)) return [shell, '-c', command]; + return [shell, '/d', '/v:off', '/s', '/c', process.platform === 'win32' ? `"${command}"` : command]; } /** @@ -654,6 +659,7 @@ export class LocalMachine implements Machine { const shell = this.shell(); const argv = shellArgv(shell, command); + const verbatim = isCmd(shell); let proc: ReturnType>; try { proc = Bun.spawn(argv, { @@ -663,6 +669,7 @@ export class LocalMachine implements Machine { stdout: 'pipe', stderr: 'pipe', detached: true, + windowsVerbatimArguments: verbatim, }); } catch (err) { return fail(`Failed to start shell: ${(err as Error).message}`); @@ -760,6 +767,7 @@ export class LocalMachine implements Machine { // a background shell asks for bash -c (tools/shells.ts): on Windows that is this machine's shell, which may be off PATH or cmd.exe const shell = this.shell(); const viaShell = (command === 'bash' || command === 'sh') && args.length === 2 && args[0] === '-c' && (process.platform === 'win32' || isCmd(shell)); + const verbatim = viaShell && isCmd(shell); const proc = Bun.spawn(viaShell ? shellArgv(shell, args[1] as string) : [command, ...args], { cwd, env: this.env(opts.env), @@ -767,6 +775,7 @@ export class LocalMachine implements Machine { stdout: 'pipe', stderr: 'pipe', detached: true, + windowsVerbatimArguments: verbatim, }); trackGroup(proc.pid); const exited = proc.exited.then(() => { diff --git a/packages/core/src/tools/bash.ts b/packages/core/src/tools/bash.ts index 0a3d137ec..8f5fe8b53 100644 --- a/packages/core/src/tools/bash.ts +++ b/packages/core/src/tools/bash.ts @@ -79,12 +79,19 @@ export function extractCwd(text: string, marker: string): { text: string; cwd?: * expansion until that point (command-line mode keeps an unknown %^X%, the * caret goes, call expands again). The command's own stderr stays on stderr; * the tool appends it to stdout as it does for bash. cmd /c runs one line, so - * lines are joined with &. - * shortcut: an odd number of % in the command shifts the % pairs and loses the cwd; fine for cmd use, a PowerShell host would avoid it. + * lines are joined with & (not inside a ( ) block, and rem lines dropped, as + * they would comment out the rest). The parentheses keep an if or for from + * taking the marker into its body. + * shortcut: an odd number of % or an unescaped ) outside quotes (echo (x)) breaks the line; fine for cmd use, a PowerShell host would avoid it. */ export function wrapCmdCommand(marker: string, command: string): string { - const line = command.split(/\r?\n/).filter((l) => l.trim()).join(' & '); - return `${line} & call set __cc_ec=%^errorlevel%& call echo ${marker}%^CD% 1>&2 & call exit %^__cc_ec%`; + let body = ''; + for (const raw of command.split(/\r?\n/)) { + const l = raw.trim().replace(/\s*&+$/, ''); + if (!l || /^(rem(\s|$)|::)/i.test(l)) continue; + body = !body ? l : body.endsWith('(') || l.startsWith(')') ? `${body} ${l}` : `${body} & ${l}`; + } + return `(${body}) & call set __cc_ec=%^errorlevel%& call echo ${marker}%^CD% 1>&2 & call exit %^__cc_ec%`; } /** The shell the device runs commands in (MachineInfo.shell): a paired device's from its hello, no round trip. */ diff --git a/packages/core/test/engine/platform-card.test.ts b/packages/core/test/engine/platform-card.test.ts index 3b7f7ce22..effffc12b 100644 --- a/packages/core/test/engine/platform-card.test.ts +++ b/packages/core/test/engine/platform-card.test.ts @@ -128,7 +128,8 @@ describe('the platform card in requests', () => { expect(sys).not.toContain('Settings > AI connections'); // 14,476 chars before the cut (v0.4.41), about 13.5k after // +350 for the identity lines at the top of BASE.md (who Conclave is and who made it) - expect(sys.length).toBeLessThan(14_250); + // +50 for the Environment's Shell line (the device's OS and shell, so Windows gets Windows commands) + expect(sys.length).toBeLessThan(14_300); const assistant = await t.engine.createSession({ title: 't', cwd: t.cwd, agent: 'assistant' }); await t.run(assistant.id, 'my day'); diff --git a/packages/core/test/tools/bash.test.ts b/packages/core/test/tools/bash.test.ts index e8021f023..44898435a 100644 --- a/packages/core/test/tools/bash.test.ts +++ b/packages/core/test/tools/bash.test.ts @@ -202,7 +202,7 @@ describe('Bash', () => { const { command } = sent[0]!; const marker = /(__CONCLAVE_CWD_\w+__)/.exec(command)![1]!; expect(command).toBe(wrapCmdCommand(marker, 'cd sub\ndir x')); - expect(command).toBe(`cd sub & dir x & call set __cc_ec=%^errorlevel%& call echo ${marker}%^CD% 1>&2 & call exit %^__cc_ec%`); + expect(command).toBe(`(cd sub & dir x) & call set __cc_ec=%^errorlevel%& call echo ${marker}%^CD% 1>&2 & call exit %^__cc_ec%`); expect(command).not.toContain('exec 3>&2'); expect(out.isError).toBe(true); expect(out.meta?.exitCode).toBe(2); @@ -212,6 +212,12 @@ describe('Bash', () => { expect(text(out)).toContain('nope'); }); + test('the cmd wrapper joins lines so an if, a block, rem and a trailing & keep the marker', () => { + const tail = ' & call set __cc_ec=%^errorlevel%& call echo M%^CD% 1>&2 & call exit %^__cc_ec%'; + expect(wrapCmdCommand('M', 'if exist x echo y')).toBe(`(if exist x echo y)${tail}`); + expect(wrapCmdCommand('M', 'rem setup\r\n:: note\r\ncd /d D:\\w &\r\n\r\nif exist a (\r\n echo a\r\n) else (\r\n echo b\r\n)')).toBe(`(cd /d D:\\w & if exist a ( echo a ) else ( echo b ))${tail}`); + }); + test('a bash device still gets the POSIX wrapper', async () => { const sent: string[] = []; const machine = { diff --git a/packages/core/test/tools/local-machine.test.ts b/packages/core/test/tools/local-machine.test.ts index 13a315225..732a04236 100644 --- a/packages/core/test/tools/local-machine.test.ts +++ b/packages/core/test/tools/local-machine.test.ts @@ -86,7 +86,7 @@ describe('LocalMachine', () => { expect(await s.exited).toBeNull(); }); - test('cmd.exe runs its line with /d /s /c', async () => { + test('cmd.exe runs its line with /d /v:off /s /c', async () => { const cmd = new LocalMachine(); // stands in for cmd.exe: a script that prints the argv it got const fake = join(dir, 'cmd.exe'); @@ -94,11 +94,11 @@ describe('LocalMachine', () => { await cmd.exec(`chmod 755 '${fake}'`, { cwd: dir }); (cmd as any).shellPath = fake; const r = await cmd.exec('ver & call echo x', { cwd: dir }); - expect(r.stdout).toBe('/d|/s|/c|ver & call echo x|'); + expect(r.stdout).toBe('/d|/v:off|/s|/c|ver & call echo x|'); // a background shell's bash -c goes to cmd.exe too const p = cmd.spawn('bash', ['-c', 'ver'], { cwd: dir }); - expect(await new Response(p.stdout as never).text()).toBe('/d|/s|/c|ver|'); - expect(shellArgv('C:\\WINDOWS\\system32\\cmd.exe', 'ver')).toEqual(['C:\\WINDOWS\\system32\\cmd.exe', '/d', '/s', '/c', 'ver']); + expect(await new Response(p.stdout as never).text()).toBe('/d|/v:off|/s|/c|ver|'); + expect(shellArgv('C:\\WINDOWS\\system32\\cmd.exe', 'ver')).toEqual(['C:\\WINDOWS\\system32\\cmd.exe', '/d', '/v:off', '/s', '/c', 'ver']); expect(shellArgv('/usr/bin/bash', 'ver')).toEqual(['/usr/bin/bash', '-c', 'ver']); }); diff --git a/packages/daemon-rs/src/procs.rs b/packages/daemon-rs/src/procs.rs index 7187c6710..4db525002 100644 --- a/packages/daemon-rs/src/procs.rs +++ b/packages/daemon-rs/src/procs.rs @@ -316,7 +316,7 @@ pub async fn exec(command: String, opts: ExecOpts, mut abort: watch::Receiver Date: Thu, 19 Nov 2026 00:51:31 -0800 Subject: [PATCH 3/8] cmd wrapper: cut a trailing & without a regex (CodeQL polynomial-redos) Committed-by: Conclave (cliproxy/claude-opus-5-5) --- packages/core/src/tools/bash.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/core/src/tools/bash.ts b/packages/core/src/tools/bash.ts index 8f5fe8b53..b1fc0b4c3 100644 --- a/packages/core/src/tools/bash.ts +++ b/packages/core/src/tools/bash.ts @@ -87,7 +87,8 @@ export function extractCwd(text: string, marker: string): { text: string; cwd?: export function wrapCmdCommand(marker: string, command: string): string { let body = ''; for (const raw of command.split(/\r?\n/)) { - const l = raw.trim().replace(/\s*&+$/, ''); + let l = raw.trim(); + while (l.endsWith('&')) l = l.slice(0, -1).trimEnd(); if (!l || /^(rem(\s|$)|::)/i.test(l)) continue; body = !body ? l : body.endsWith('(') || l.startsWith(')') ? `${body} ${l}` : `${body} & ${l}`; } From 57c22d8ee9ae2ab438b34fd3e7892a9e70d94f4e Mon Sep 17 00:00:00 2001 From: default-cybe <201046277+default-cybe@users.noreply.github.com> Date: Thu, 19 Nov 2026 09:19:44 -0800 Subject: [PATCH 4/8] Switch cmd.exe to UTF-8 before opening the batch script Run chcp 65001 >nul in the outer cmd.exe /d /v:off /s /c command line before invoking "%__CONCLAVE_SCRIPT%". Running chcp inside the .cmd file after cmd.exe had already opened it in the default codepage misread Unicode paths and shifted batch file byte offsets across :__conclave_run. Committed-by: Conclave (cliproxy/gpt-6.1-sol) --- packages/core/src/tools/bash.ts | 3 +-- packages/core/test/tools/bash.test.ts | 2 +- packages/core/test/tools/cmd-runtime.test.ts | 26 +++++++++++++++----- 3 files changed, 22 insertions(+), 9 deletions(-) diff --git a/packages/core/src/tools/bash.ts b/packages/core/src/tools/bash.ts index 63d5999b0..91c2b5e65 100644 --- a/packages/core/src/tools/bash.ts +++ b/packages/core/src/tools/bash.ts @@ -77,7 +77,6 @@ export function extractCwd(text: string, marker: string): { text: string; cwd?: export function wrapCmdCommand(marker: string, command: string): string { return [ '@echo off', - 'chcp 65001 >nul', 'call :__conclave_run', 'set "__conclave_exit=%errorlevel%"', 'setlocal DisableDelayedExpansion', @@ -159,7 +158,7 @@ async function runForeground(input: BashInput, ctx: ToolContext): Promisenul & "%__CONCLAVE_SCRIPT%"' : wrapCommand(marker), { cwd: ctx.cwd, env: bashEnv(ctx, { __CONCLAVE_CMD: input.command, ...(script ? { __CONCLAVE_SCRIPT: script } : {}) }), timeoutMs, diff --git a/packages/core/test/tools/bash.test.ts b/packages/core/test/tools/bash.test.ts index eb4d30972..e7be9c34e 100644 --- a/packages/core/test/tools/bash.test.ts +++ b/packages/core/test/tools/bash.test.ts @@ -200,7 +200,7 @@ describe('Bash', () => { const { command, env } = sent[1]!; const marker = /(__CONCLAVE_CWD_\w+__)/.exec(script)![1]!; expect(script).toBe(wrapCmdCommand(marker, 'cd sub\ndir x')); - expect(command).toBe('"%__CONCLAVE_SCRIPT%"'); + expect(command).toBe('chcp 65001 >nul & "%__CONCLAVE_SCRIPT%"'); expect(env?.__CONCLAVE_CMD).toBe('cd sub\ndir x'); expect(removed).toBe(env!.__CONCLAVE_SCRIPT!); expect(out.isError).toBe(true); diff --git a/packages/core/test/tools/cmd-runtime.test.ts b/packages/core/test/tools/cmd-runtime.test.ts index 2b544aeb1..ac11e6d9c 100644 --- a/packages/core/test/tools/cmd-runtime.test.ts +++ b/packages/core/test/tools/cmd-runtime.test.ts @@ -80,14 +80,21 @@ describe.skipIf(process.platform !== 'win32')('Bash tool on cmd.exe (Windows run } } const out = await bash(`"${exe}" "${echoJs}" alpha "two words"`); - expect(out.isError).toBeFalsy(); - expect(out.meta?.exitCode).toBe(0); + expect({ isError: out.isError, exitCode: out.meta?.exitCode, out: clean(text(out)) }).toEqual({ + isError: false, + exitCode: 0, + out: expect.stringMatching(/^\{/), + }); expect(JSON.parse(clean(text(out))).args).toEqual(['alpha', 'two words']); }, TEST_TIMEOUT); test('starts in a cwd with spaces, parentheses, percent and ampersand, and leaves it unchanged', async () => { const out = await bash(`"${bun}" "${echoJs}"`); - expect(out.isError).toBeFalsy(); + expect({ isError: out.isError, exitCode: out.meta?.exitCode, out: clean(text(out)) }).toEqual({ + isError: false, + exitCode: 0, + out: expect.stringMatching(/^\{/), + }); expect(same(JSON.parse(clean(text(out))).cwd, root)).toBe(true); expect(out.meta?.cwd).toBeUndefined(); const cd = await bash('cd'); @@ -160,7 +167,11 @@ describe.skipIf(process.platform !== 'win32')('Bash tool on cmd.exe (Windows run mkdirSync(sub, { recursive: true }); // batch semantics: a literal % in the command is written %% const out = await bash(`cd /d "${sub.replace(/%/g, '%%')}"\n"${bun}" "${echoJs}"`); - expect(out.isError).toBeFalsy(); + expect({ isError: out.isError, exitCode: out.meta?.exitCode, out: clean(text(out)) }).toEqual({ + isError: false, + exitCode: 0, + out: expect.stringMatching(/^\{/), + }); expect(same(out.meta?.cwd as string | undefined, sub)).toBe(true); expect(same(JSON.parse(clean(text(out)).split('\n')[0] as string).cwd, sub)).toBe(true); // the next call starts where the last one ended @@ -184,8 +195,11 @@ describe.skipIf(process.platform !== 'win32')('Bash tool on cmd.exe (Windows run test('runs an npm-style .cmd shim from PATH without CALL', async () => { const out = await bash(`set "PATH=${binDir};%PATH%"\ncc-shim hello "two words"`); - expect(out.isError).toBeFalsy(); - expect(out.meta?.exitCode).toBe(0); + expect({ isError: out.isError, exitCode: out.meta?.exitCode, out: clean(text(out)) }).toEqual({ + isError: false, + exitCode: 0, + out: expect.stringMatching(/^\{/), + }); const lines = clean(text(out)).split('\n'); expect(lines).toHaveLength(1); expect(JSON.parse(lines[0] as string).args).toEqual(['hello', 'two words']); From 2bcbea60b783f731be4007d2dc9101e0fc0d39e9 Mon Sep 17 00:00:00 2001 From: default-cybe <201046277+default-cybe@users.noreply.github.com> Date: Thu, 19 Nov 2026 09:29:37 -0800 Subject: [PATCH 5/8] Run cmd.exe batch scripts via outer call and capture cwd outside the file Move the batch epilogue (exit code capture, stderr cwd marker, and exit) out of the temporary .cmd file and into the outer cmd.exe /d /v:off /s /c command line after `call "%__CONCLAVE_SCRIPT%"`. When a command invoked another .cmd shim without CALL, cmd.exe transferred batch execution to the shim and returned to the top-level `call`, skipping any statements after `call :__conclave_run` inside the outer .cmd file. Committed-by: Conclave (cliproxy/gpt-6.1-sol) --- packages/core/src/tools/bash.ts | 22 ++++++---------------- packages/core/test/tools/bash.test.ts | 10 ++++------ 2 files changed, 10 insertions(+), 22 deletions(-) diff --git a/packages/core/src/tools/bash.ts b/packages/core/src/tools/bash.ts index 91c2b5e65..2aaf078ca 100644 --- a/packages/core/src/tools/bash.ts +++ b/packages/core/src/tools/bash.ts @@ -74,20 +74,8 @@ export function extractCwd(text: string, marker: string): { text: string; cwd?: } /** Batch lines stay intact: wrapping or joining user text changes cmd's percent and parentheses parsing. */ -export function wrapCmdCommand(marker: string, command: string): string { - return [ - '@echo off', - 'call :__conclave_run', - 'set "__conclave_exit=%errorlevel%"', - 'setlocal DisableDelayedExpansion', - `>&2 &2 echo(', - 'exit /b %__conclave_exit%', - ':__conclave_run', - command.replace(/\r?\n/g, '\r\n'), - 'exit /b', - '', - ].join('\r\n'); +export function wrapCmdCommand(command: string): string { + return ['@echo off', command.replace(/\r?\n/g, '\r\n'), ''].join('\r\n'); } /** The shell the device runs commands in (MachineInfo.shell): a paired device's from its hello, no round trip. */ @@ -156,9 +144,11 @@ async function runForeground(input: BashInput, ctx: ToolContext): Promisenul & "%__CONCLAVE_SCRIPT%"' : wrapCommand(marker), { + res = await ctx.machine.exec( + script ? `chcp 65001 >nul & call "%__CONCLAVE_SCRIPT%" & call set "__conclave_exit=%%errorlevel%%" & >&2 &2 cd & call exit /b %%__conclave_exit%%` : wrapCommand(marker), + { cwd: ctx.cwd, env: bashEnv(ctx, { __CONCLAVE_CMD: input.command, ...(script ? { __CONCLAVE_SCRIPT: script } : {}) }), timeoutMs, diff --git a/packages/core/test/tools/bash.test.ts b/packages/core/test/tools/bash.test.ts index e7be9c34e..fbb4764ce 100644 --- a/packages/core/test/tools/bash.test.ts +++ b/packages/core/test/tools/bash.test.ts @@ -192,15 +192,14 @@ describe('Bash', () => { exec: async (command: string, opts: { env?: Record }) => { sent.push({ command, env: opts.env }); if (command === 'chcp 65001 >nul & set TEMP') return { exitCode: 0, stdout: 'TEMP=C:\\Temp\r\n', stderr: '' }; - const marker = /(__CONCLAVE_CWD_\w+__)/.exec(script)![1]; + const marker = /(__CONCLAVE_CWD_\w+__)/.exec(command)![1]; return { exitCode: 2, stdout: 'File Not Found\r\n', stderr: `nope\r\n${marker}D:\\proj\\sub \r\n`, timedOut: false, aborted: false, durationMs: 5 }; }, } as unknown as Machine; const out = await BashTool.run({ command: 'cd sub\ndir x' }, makeCtx({ cwd: 'D:\\proj', machine })); const { command, env } = sent[1]!; - const marker = /(__CONCLAVE_CWD_\w+__)/.exec(script)![1]!; - expect(script).toBe(wrapCmdCommand(marker, 'cd sub\ndir x')); - expect(command).toBe('chcp 65001 >nul & "%__CONCLAVE_SCRIPT%"'); + expect(script).toBe(wrapCmdCommand('cd sub\ndir x')); + expect(command).toMatch(/^chcp 65001 >nul & call "%__CONCLAVE_SCRIPT%" & call set "__conclave_exit=%%errorlevel%%" & >&2 &2 cd & call exit \/b %%__conclave_exit%%$/); expect(env?.__CONCLAVE_CMD).toBe('cd sub\ndir x'); expect(removed).toBe(env!.__CONCLAVE_SCRIPT!); expect(out.isError).toBe(true); @@ -238,8 +237,7 @@ describe('Bash', () => { test('the cmd batch wrapper preserves lines and does not nest user parentheses', () => { const command = 'rem setup\n:: note\nif exist a (\n echo 100%% (a)\n) else (\n echo b\n)'; - expect(wrapCmdCommand('M', command)).toContain(`:__conclave_run\r\n${command.replace(/\n/g, '\r\n')}\r\nexit /b\r\n`); - expect(wrapCmdCommand('M', command)).toContain('set "__conclave_exit=%errorlevel%"'); + expect(wrapCmdCommand(command)).toBe(`@echo off\r\n${command.replace(/\n/g, '\r\n')}\r\n`); }); test('a bash device still gets the POSIX wrapper', async () => { From c3cbd3cbe8a6477817ac5d64ccf9afe6f3239b3d Mon Sep 17 00:00:00 2001 From: default-cybe <201046277+default-cybe@users.noreply.github.com> Date: Thu, 19 Nov 2026 10:03:59 -0800 Subject: [PATCH 6/8] Fix cmd.exe exit code expansion, pipe attachment and UTF-8 batch reading on Windows In command-line mode (`cmd.exe /c`), `%%errorlevel%%` is not de-doubled by `call`, so `call exit /b %%__conclave_exit%%` always evaluated to 0; use `%^errorlevel%` and `%^__conclave_exit%` so the caret prevents first-pass expansion and `call` expands the real exit code after the script finishes. Also avoid `detached: true` on win32 so child processes inherit stdout/stderr pipes instead of a detached console, and include `chcp 65001 >nul` inside the batch script as well. Committed-by: Conclave (cliproxy/backup-gemini/gemini-4-argon-high) --- packages/core/src/machine/local.ts | 4 ++-- packages/core/src/tools/bash.ts | 4 ++-- packages/core/test/tools/bash.test.ts | 4 ++-- packages/core/test/tools/cmd-runtime.test.ts | 5 +++-- 4 files changed, 9 insertions(+), 8 deletions(-) diff --git a/packages/core/src/machine/local.ts b/packages/core/src/machine/local.ts index 9b31fa1df..9ac274548 100644 --- a/packages/core/src/machine/local.ts +++ b/packages/core/src/machine/local.ts @@ -674,7 +674,7 @@ export class LocalMachine implements Machine { stdin: opts.stdin !== undefined ? 'pipe' : 'ignore', stdout: 'pipe', stderr: 'pipe', - detached: true, + detached: process.platform !== 'win32', windowsVerbatimArguments: verbatim, }); } catch (err) { @@ -780,7 +780,7 @@ export class LocalMachine implements Machine { stdin: 'pipe', stdout: 'pipe', stderr: 'pipe', - detached: true, + detached: process.platform !== 'win32', windowsVerbatimArguments: verbatim, }); trackGroup(proc.pid); diff --git a/packages/core/src/tools/bash.ts b/packages/core/src/tools/bash.ts index 2aaf078ca..db307c191 100644 --- a/packages/core/src/tools/bash.ts +++ b/packages/core/src/tools/bash.ts @@ -75,7 +75,7 @@ export function extractCwd(text: string, marker: string): { text: string; cwd?: /** Batch lines stay intact: wrapping or joining user text changes cmd's percent and parentheses parsing. */ export function wrapCmdCommand(command: string): string { - return ['@echo off', command.replace(/\r?\n/g, '\r\n'), ''].join('\r\n'); + return ['@echo off', 'chcp 65001 >nul', command.replace(/\r?\n/g, '\r\n'), ''].join('\r\n'); } /** The shell the device runs commands in (MachineInfo.shell): a paired device's from its hello, no round trip. */ @@ -147,7 +147,7 @@ async function runForeground(input: BashInput, ctx: ToolContext): Promisenul & call "%__CONCLAVE_SCRIPT%" & call set "__conclave_exit=%%errorlevel%%" & >&2 &2 cd & call exit /b %%__conclave_exit%%` : wrapCommand(marker), + script ? `chcp 65001 >nul & call "%__CONCLAVE_SCRIPT%" & call set "__conclave_exit=%^errorlevel%" & >&2 &2 cd & call exit /b %^__conclave_exit%` : wrapCommand(marker), { cwd: ctx.cwd, env: bashEnv(ctx, { __CONCLAVE_CMD: input.command, ...(script ? { __CONCLAVE_SCRIPT: script } : {}) }), diff --git a/packages/core/test/tools/bash.test.ts b/packages/core/test/tools/bash.test.ts index fbb4764ce..62dc48778 100644 --- a/packages/core/test/tools/bash.test.ts +++ b/packages/core/test/tools/bash.test.ts @@ -199,7 +199,7 @@ describe('Bash', () => { const out = await BashTool.run({ command: 'cd sub\ndir x' }, makeCtx({ cwd: 'D:\\proj', machine })); const { command, env } = sent[1]!; expect(script).toBe(wrapCmdCommand('cd sub\ndir x')); - expect(command).toMatch(/^chcp 65001 >nul & call "%__CONCLAVE_SCRIPT%" & call set "__conclave_exit=%%errorlevel%%" & >&2 &2 cd & call exit \/b %%__conclave_exit%%$/); + expect(command).toMatch(/^chcp 65001 >nul & call "%__CONCLAVE_SCRIPT%" & call set "__conclave_exit=%\^errorlevel%" & >&2 &2 cd & call exit \/b %\^__conclave_exit%$/); expect(env?.__CONCLAVE_CMD).toBe('cd sub\ndir x'); expect(removed).toBe(env!.__CONCLAVE_SCRIPT!); expect(out.isError).toBe(true); @@ -237,7 +237,7 @@ describe('Bash', () => { test('the cmd batch wrapper preserves lines and does not nest user parentheses', () => { const command = 'rem setup\n:: note\nif exist a (\n echo 100%% (a)\n) else (\n echo b\n)'; - expect(wrapCmdCommand(command)).toBe(`@echo off\r\n${command.replace(/\n/g, '\r\n')}\r\n`); + expect(wrapCmdCommand(command)).toBe(`@echo off\r\nchcp 65001 >nul\r\n${command.replace(/\n/g, '\r\n')}\r\n`); }); test('a bash device still gets the POSIX wrapper', async () => { diff --git a/packages/core/test/tools/cmd-runtime.test.ts b/packages/core/test/tools/cmd-runtime.test.ts index ac11e6d9c..5bfc65f14 100644 --- a/packages/core/test/tools/cmd-runtime.test.ts +++ b/packages/core/test/tools/cmd-runtime.test.ts @@ -110,8 +110,9 @@ describe.skipIf(process.platform !== 'win32')('Bash tool on cmd.exe (Windows run test('types a file with a Unicode name and prints its UTF-8 text exactly', async () => { const body = 'héllo wörld ✓ 日本語'; - writeFileSync(join(root, 'café.txt'), body); - const out = await bash('type "café.txt"'); + const file = join(root, 'café.txt'); + writeFileSync(file, body); + const out = await bash(`type "${file.replace(/%/g, '%%')}"`); expect(out.isError).toBeFalsy(); expect(clean(text(out))).toBe(body); }, TEST_TIMEOUT); From e33d850fc5a873d77cbafa365c212b6544adaace Mon Sep 17 00:00:00 2001 From: default-cybe <201046277+default-cybe@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:29:41 -0800 Subject: [PATCH 7/8] Capture the cmd.exe exit code outside quotes A caret inside set "..." quotes is literal, so %^errorlevel% never turned into %errorlevel% and every command reported exit code 0. Use the unquoted call set form, with no space before &, so call expands the real errorlevel. Committed-by: Conclave (cliproxy/personal-claude/claude-opus-5-5) --- packages/core/src/tools/bash.ts | 2 +- packages/core/test/tools/bash.test.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/core/src/tools/bash.ts b/packages/core/src/tools/bash.ts index db307c191..6b483a6f7 100644 --- a/packages/core/src/tools/bash.ts +++ b/packages/core/src/tools/bash.ts @@ -147,7 +147,7 @@ async function runForeground(input: BashInput, ctx: ToolContext): Promisenul & call "%__CONCLAVE_SCRIPT%" & call set "__conclave_exit=%^errorlevel%" & >&2 &2 cd & call exit /b %^__conclave_exit%` : wrapCommand(marker), + script ? `chcp 65001 >nul & call "%__CONCLAVE_SCRIPT%" & call set __conclave_exit=%^errorlevel%& >&2 &2 cd & call exit /b %^__conclave_exit%` : wrapCommand(marker), { cwd: ctx.cwd, env: bashEnv(ctx, { __CONCLAVE_CMD: input.command, ...(script ? { __CONCLAVE_SCRIPT: script } : {}) }), diff --git a/packages/core/test/tools/bash.test.ts b/packages/core/test/tools/bash.test.ts index 62dc48778..3067f7d65 100644 --- a/packages/core/test/tools/bash.test.ts +++ b/packages/core/test/tools/bash.test.ts @@ -199,7 +199,7 @@ describe('Bash', () => { const out = await BashTool.run({ command: 'cd sub\ndir x' }, makeCtx({ cwd: 'D:\\proj', machine })); const { command, env } = sent[1]!; expect(script).toBe(wrapCmdCommand('cd sub\ndir x')); - expect(command).toMatch(/^chcp 65001 >nul & call "%__CONCLAVE_SCRIPT%" & call set "__conclave_exit=%\^errorlevel%" & >&2 &2 cd & call exit \/b %\^__conclave_exit%$/); + expect(command).toMatch(/^chcp 65001 >nul & call "%__CONCLAVE_SCRIPT%" & call set __conclave_exit=%\^errorlevel%& >&2 &2 cd & call exit \/b %\^__conclave_exit%$/); expect(env?.__CONCLAVE_CMD).toBe('cd sub\ndir x'); expect(removed).toBe(env!.__CONCLAVE_SCRIPT!); expect(out.isError).toBe(true); From 42f895ca73d9ca1445d9f153cbaaa39d658cad63 Mon Sep 17 00:00:00 2001 From: default-cybe <201046277+default-cybe@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:47:30 -0800 Subject: [PATCH 8/8] Judge cmd.exe commands as cmd everywhere, and skip cmd's current-folder lookup The runner's parallel batch, extension gate (project gate) and audit still read a Bash command as bash, so on a cmd.exe device `echo hi #& del x` ran as read-only: unaudited, ungated and in parallel. callReadOnly judges it in the shell it runs in, as checkPermission already does. cmd.exe runs a program from the current folder before PATH, so a repo's git.bat ran under an allow rule for git. Set NoDefaultCurrentDirectoryInExePath for cmd in the hub's exec and spawn and in the daemon's. Committed-by: Conclave (cliproxy/personal-claude/claude-opus-5-5) --- packages/core/src/machine/local.ts | 7 +++++-- packages/core/src/session/permissions.ts | 6 ++++++ packages/core/src/session/runner.ts | 10 +++++----- packages/core/test/session/permissions.test.ts | 10 +++++++++- packages/daemon-rs/src/procs.rs | 11 +++++++++++ 5 files changed, 36 insertions(+), 8 deletions(-) diff --git a/packages/core/src/machine/local.ts b/packages/core/src/machine/local.ts index 9ac274548..e7840b90f 100644 --- a/packages/core/src/machine/local.ts +++ b/packages/core/src/machine/local.ts @@ -78,6 +78,9 @@ function killTree(pid: number | undefined, signal: NodeJS.Signals): void { export const isCmd = (shell: string) => /(^|[\\/])cmd(\.exe)?$/i.test(shell); +/** cmd.exe looks in the current folder before PATH: a repo's git.bat would run under a Bash(git status) rule. Bash never does. */ +export const CMD_ENV = { NoDefaultCurrentDirectoryInExePath: '1' }; + /** * The argv that runs one command line: cmd.exe takes /d /v:off /s /c, every * other shell -c. On Windows cmd's line goes in quotes that /s strips, with @@ -670,7 +673,7 @@ export class LocalMachine implements Machine { try { proc = Bun.spawn(argv, { cwd, - env: this.env(opts.env), + env: verbatim ? { ...this.env(opts.env), ...CMD_ENV } : this.env(opts.env), stdin: opts.stdin !== undefined ? 'pipe' : 'ignore', stdout: 'pipe', stderr: 'pipe', @@ -776,7 +779,7 @@ export class LocalMachine implements Machine { const verbatim = viaShell && isCmd(shell); const proc = Bun.spawn(viaShell ? shellArgv(shell, args[1] as string) : [command, ...args], { cwd, - env: this.env(opts.env), + env: verbatim ? { ...this.env(opts.env), ...CMD_ENV } : this.env(opts.env), stdin: 'pipe', stdout: 'pipe', stderr: 'pipe', diff --git a/packages/core/src/session/permissions.ts b/packages/core/src/session/permissions.ts index 832b4927a..e9a243696 100644 --- a/packages/core/src/session/permissions.ts +++ b/packages/core/src/session/permissions.ts @@ -315,6 +315,12 @@ export function machineShell(machine: unknown): string | undefined { return typeof m.shell === 'function' ? m.shell() : undefined; } +/** A call's readOnly as the shell will run it: on cmd.exe the Bash tool's own bash reading can miss a command (echo hi #& del x). */ +export function callReadOnly(tool: Tool, input: Record, shell: string | undefined): boolean { + if (tool.name !== 'Bash' || !shell || !isCmd(shell) || typeof input?.command !== 'string') return toolIsReadOnly(tool, input); + return tool.readOnly !== false && !input.run_in_background && cmdReadOnly(input.command.trim()); +} + export interface CheckInput { tool: Tool; input: Record; diff --git a/packages/core/src/session/runner.ts b/packages/core/src/session/runner.ts index 0ad2615a7..1d4d21bcb 100644 --- a/packages/core/src/session/runner.ts +++ b/packages/core/src/session/runner.ts @@ -15,7 +15,7 @@ import type { } from '../types'; import type { SendInput, SendResult } from '../client'; import type { ReadMark, Tool, ToolContext, ToolOutput } from '../tools/types'; -import { coerceInput, timeoutOutput, toolIsReadOnly, validateInput } from '../tools/types'; +import { coerceInput, timeoutOutput, validateInput } from '../tools/types'; import type { AgentDef } from '../extensions/types'; import type { ProviderMessage, SystemBlock, ToolSpec } from '../providers/types'; import { ProviderError } from '../providers/types'; @@ -32,7 +32,7 @@ import { seesImages } from '../providers/common'; import { pickedName } from '../attachments/prepare'; import { refusalPlanFor } from './member-fallbacks'; import { refusalStepOf, refusalWords, RefusalWalk, servedLabel, stepOfTarget, type FallbackTarget } from './refusal-fallback'; -import { checkPermission, dangerousCommand, machineShell } from './permissions'; +import { callReadOnly, checkPermission, dangerousCommand, machineShell } from './permissions'; import { ReadTool } from '../tools/read'; import { maybeCompact, estimateRequestTokens, meteredTokens, partHash, type TokenMeter } from './compaction'; import { applyClearing } from './context-edit'; @@ -1604,7 +1604,7 @@ export class SessionRunner { continue; } const tool = resolveTool(toolMap, use.name); - const safe = tool && (toolIsReadOnly(tool, use.input) || CONCURRENT_TOOLS.has(tool.name)); + const safe = tool && (callReadOnly(tool, use.input, machineShell(engine.machineFor(this.session))) || CONCURRENT_TOOLS.has(tool.name)); if (safe) { batch.push(use); continue; @@ -2024,7 +2024,7 @@ export class SessionRunner { if (decision.decision === 'deny') return fail(`Permission denied: ${decision.reason}`, { denied: 'rule' }); // runner extensions (runner-ext.ts), for example the folder check after a session moved - const callCtx = { sessionId: this.id, session, tool, input, toolUseId: use.id, depth: this.depth, readOnly: toolIsReadOnly(tool, input), signal }; + const callCtx = { sessionId: this.id, session, tool, input, toolUseId: use.id, depth: this.depth, readOnly: callReadOnly(tool, input, shell), signal }; const extVerdict = await engine.runnerExtensions.beforeTool(callCtx, { failClosed: untrusted }); if (extVerdict?.decision === 'deny') return fail(extVerdict.reason, { denied: 'extension' }); if (extVerdict?.decision === 'ask' && decision.decision === 'allow') decision = { decision: 'ask', reason: extVerdict.reason }; @@ -2173,7 +2173,7 @@ export class SessionRunner { // after the offload, so a long result never cuts the instructions if (scoped) content = typeof content === 'string' ? `${content}\n\n${scoped}` : [...content, { type: 'text', text: scoped } as TextBlock]; - if (!toolIsReadOnly(tool, input)) { + if (!callReadOnly(tool, input, shell)) { engine.audit(this.id, `tool:${tool.name}`, tool.summarize?.(input) ?? oneLine(JSON.stringify(input), 300)); } diff --git a/packages/core/test/session/permissions.test.ts b/packages/core/test/session/permissions.test.ts index 3a1c84c23..7ef219e54 100644 --- a/packages/core/test/session/permissions.test.ts +++ b/packages/core/test/session/permissions.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from 'bun:test'; -import { bashRuleTargets, checkPermission, type CheckInput } from '../../src/session/permissions'; +import { bashRuleTargets, callReadOnly, checkPermission, type CheckInput } from '../../src/session/permissions'; import { gatedConstructs, HEREDOC_WORD, maskSafeHeredocs, substitutionBodies, suggestBashRule } from '../../src/tools/bash-rules'; import { toolByName } from '../../src/tools'; import type { PermissionMode } from '../../src/types'; @@ -254,6 +254,14 @@ describe('a Bash command on a cmd.exe machine', () => { expect(check(payload, { deny: ['Bash(mkdir:*)'] }, 'bypass').decision).toBe('allow'); }); + test('callReadOnly reads a cmd line as cmd, so the runner audits and serializes it', () => { + expect(callReadOnly(bash, { command: payload }, undefined)).toBe(true); + expect(callReadOnly(bash, { command: payload }, 'C:\\Windows\\System32\\cmd.exe')).toBe(false); + expect(callReadOnly(bash, { command: 'echo hi #& del /q x' }, 'cmd.exe')).toBe(false); + expect(callReadOnly(bash, { command: 'dir' }, 'cmd.exe')).toBe(true); + expect(callReadOnly(bash, { command: 'dir', run_in_background: true }, 'cmd.exe')).toBe(false); + }); + test('single quotes hide no command from a deny rule, in every mode', () => { for (const mode of ['default', 'plan', 'bypass', 'acceptEdits'] as PermissionMode[]) { expect(cmdCheck(payload, { deny: ['Bash(mkdir:*)'] }, mode).decision).toBe('deny'); diff --git a/packages/daemon-rs/src/procs.rs b/packages/daemon-rs/src/procs.rs index 3593e3bcd..0dd8915d3 100644 --- a/packages/daemon-rs/src/procs.rs +++ b/packages/daemon-rs/src/procs.rs @@ -253,6 +253,13 @@ fn shell_command(sh: &str, command: &str) -> tokio::process::Command { cmd } +/// cmd.exe looks in the current folder before PATH, so a repo's git.bat would run under an allow rule for git; bash never does. +fn no_cwd_lookup(cmd: &mut tokio::process::Command, sh: &str) { + if is_cmd(sh) { + cmd.env("NoDefaultCurrentDirectoryInExePath", "1"); + } +} + fn configure(cmd: &mut tokio::process::Command, own_group: bool) { #[cfg(unix)] if own_group { @@ -338,6 +345,7 @@ pub async fn exec(command: String, opts: ExecOpts, mut abort: watch::Receiver