Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 18 additions & 3 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -97,10 +97,9 @@ jobs:
# way the desktop app does (stdin a pipe that stays open, stop on its end).
windows-hub:
name: Windows hub binary
# a Windows minute costs about twice a Linux one: main and manual runs only
if: github.event_name != 'pull_request'
runs-on: windows-latest
timeout-minutes: 20
# the native Rust tests' first build, before rust-cache has anything
timeout-minutes: 30
defaults:
run:
shell: bash
Expand All @@ -114,6 +113,22 @@ jobs:
- name: Install
run: bun install --frozen-lockfile

# the runner has Git Bash; the test forces cmd.exe, the shell of a Windows device without it
- name: Bash tool on cmd.exe
run: bun test packages/core/test/tools/cmd-runtime.test.ts

- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable branch
with:
toolchain: stable

- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
with:
workspaces: packages/daemon-rs

# the Rust daemon's cmd.exe runs, cfg(windows) tests named windows_cmd_*
- name: Rust daemon on cmd.exe
run: cargo test --locked --manifest-path packages/daemon-rs/Cargo.toml windows_cmd

- name: Compile the Windows hub as the release does
run: |
bun scripts/build-cli.ts --target bun-windows-x64 --outfile dist/conclave.exe
Expand Down
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ like `## [0.4.16] - 2026-10-24`.

## [Unreleased]

### Fixed

- Windows: commands work on PCs without Git Bash, using cmd.exe batch scripts. Quoted paths, multiline blocks, percent variables, exit codes and working-directory changes stay intact; command timeouts stop the process tree.
- The agent is told the device's actual execution shell and Windows command syntax instead of assuming Unix commands.

### Changed

- Desktop: Open folder… uses the native OS folder picker for this app's paired computer, then confirms the folder with the existing checks and Add as project. Other devices keep the in-app browser; cancelling keeps the current folder, and a native dialog failure opens the in-app browser with an explanation.
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/engine/commands.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { Engine } from './engine';
import { expandCommand } from '../extensions/commands';
import { checkPermission, dangerousCommand } from '../session/permissions';
import { checkPermission, dangerousCommand, machineShell } from '../session/permissions';
import { BashTool } from '../tools/bash';
import { ReadTool } from '../tools/read';
import type { Tool } from '../tools/types';
Expand Down Expand Up @@ -172,6 +172,7 @@ export async function bashRefusal(engine: Engine, s: Session, command: string, s
cwd: s.cwd,
home: (await engine.machineHome(engine.machineFor(s))) ?? '/',
workspaceRoots: [s.cwd, ...engine.config.get().permissions.additionalDirectories],
shell: machineShell(engine.machineFor(s)),
});
if (v.decision === 'allow' && dangerousCommand(command)) v = { decision: 'ask', reason: 'Potentially destructive command' };
if (v.decision === 'deny') return v.reason;
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/engine/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2741,6 +2741,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,
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/engine/extensions-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ import { claudeHome, codexHome, parseJsonc } from '../config';
import type { AgentDef, HookInput, HookOutcome, InstalledPlugin, MarketplaceEntry, RuntimeHookCommand } from '../extensions/types';
import type { Tool } from '../tools/types';
import { filterTools, untrustedOffers } from '../tools';
import { checkPermission, dangerousCommand } from '../session/permissions';
import { checkPermission, dangerousCommand, machineShell } from '../session/permissions';
import { mcpFromClaude, mcpFromCodexToml, mcpFromGemini, mcpFromOpenCode, readForeignHooks } from '../extensions/compat';
import { mcpConnectPlan } from '../extensions/cli-sync';
import { oauthFailure } from '../extensions/mcp-oauth';
Expand Down Expand Up @@ -301,6 +301,7 @@ function permissionFor(
cwd: ctx.session.cwd,
home: ctx.home,
workspaceRoots: [ctx.session.cwd, ...cfg.permissions.additionalDirectories],
shell: machineShell(engine.machineFor(ctx.session)),
});
let dangerous: string | false = false;
if (tool.name === 'Bash' && typeof input.command === 'string') {
Expand Down
46 changes: 39 additions & 7 deletions packages/core/src/machine/local.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -67,6 +76,21 @@ 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
* windowsVerbatimArguments so Bun adds no quoting of its own (as raw_arg in daemon-rs).
*/
export function shellArgv(shell: string, command: string): string[] {
if (!isCmd(shell)) return [shell, '-c', command];
return [shell, '/d', '/v:off', '/s', '/c', process.platform === 'win32' ? `"${command}"` : command];
}

/** Keeps the first and last part of a long stream and drops the middle. */
class HeadTailBuffer {
private head = '';
Expand Down Expand Up @@ -268,7 +292,8 @@ export class LocalMachine implements Machine {
platform: process.platform,
arch: process.arch,
home: os.homedir(),
shell: (process.platform !== 'win32' && process.env.SHELL) || this.shell(),
// SHELL describes the login shell, not necessarily what exec runs.
shell: this.shell(),
clis,
capabilities,
};
Expand Down Expand Up @@ -642,16 +667,18 @@ 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);
const verbatim = isCmd(shell);
let proc: ReturnType<typeof Bun.spawn<'pipe' | 'ignore', 'pipe', 'pipe'>>;
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',
detached: true,
detached: process.platform !== 'win32',
windowsVerbatimArguments: verbatim,
});
} catch (err) {
return fail(`Failed to start shell: ${(err as Error).message}`);
Expand Down Expand Up @@ -746,13 +773,18 @@ 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 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',
detached: true,
detached: process.platform !== 'win32',
windowsVerbatimArguments: verbatim,
});
trackGroup(proc.pid);
const exited = proc.exited.then(() => {
Expand Down
119 changes: 114 additions & 5 deletions packages/core/src/session/permissions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { PermissionMode } from '../types';
import type { Tool } from '../tools/types';
import { toolIsReadOnly } from '../tools/types';
import { gatedConstructs, heredocLines, maskSafeHeredocs, parseCommand, quoteEnd, readHeredoc, startsComment, substitutionBodies, type Heredoc } from '../tools/bash-rules';
import { isCmd } from '../machine/local';

/**
* Permission rules use Claude Code syntax:
Expand Down Expand Up @@ -223,6 +224,103 @@ export function bashRuleTargets(cmd: string): string[] {
return [...out];
}

/**
* cmd.exe syntax these checks cannot read the way cmd does: % and ! expansion
* and ^ escapes change the line before cmd parses it, ( ) and if/for/call/start
* run commands in places the splitter does not look, plus redirects, line
* breaks and an unclosed quote. Returns the construct's name, or undefined.
*/
export function cmdUnsure(cmd: string): string | undefined {
if (/[%!^]/.test(cmd)) return 'cmd.exe expansion or ^ escape';
if (/[\r\n]/.test(cmd)) return 'a line break';
if ((cmd.match(/"/g)?.length ?? 0) % 2) return 'an unclosed quote';
if (/[()]/.test(cmd)) return 'cmd.exe grouping or block';
if (/[<>]/.test(cmd)) return 'redirect';
if (cmdParts(cmd).some((p) => cmdNames(cmdCommand(p).name).some((n) => RUNS_OTHERS.has(n)))) return 'a command that runs other commands';
return undefined;
}

/** Keywords and programs that run a command line of their own, which the checks do not read. */
const RUNS_OTHERS = new Set(['if', 'for', 'call', 'start', 'cmd', 'command', 'powershell', 'pwsh', 'powershell_ise', 'bash', 'sh', 'zsh', 'wsl', 'wscript', 'cscript', 'mshta', 'conhost', 'runas']);

/** The commands of a cmd.exe line: & && | || separate them outside double quotes; single quotes, backslashes and # are plain text to cmd. */
export function cmdParts(cmd: string): string[] {
const parts: string[] = [];
let cur = '';
let quoted = false;
for (const c of cmd) {
if (c === '"') quoted = !quoted;
if (!quoted && (c === '&' || c === '|')) {
parts.push(cur);
cur = '';
} else cur += c;
}
parts.push(cur);
return parts.map((p) => p.trim()).filter(Boolean);
}

/** One cmd command as its program, as written (a quoted one without its quotes), and the rest: cmd ends a bare name at a space , ; or =. */
function cmdCommand(part: string): { name: string; quoted: boolean; rest: string } {
const s = part.replace(/^[\s@]+/, '');
if (s.startsWith('"')) {
const end = s.indexOf('"', 1);
return end === -1 ? { name: s.slice(1), quoted: true, rest: '' } : { name: s.slice(1, end), quoted: true, rest: s.slice(end + 1) };
}
const name = /^[^\s,;=]*/.exec(s)![0];
return { name, quoted: false, rest: s.slice(name.length) };
}

/**
* The names a program may go by for rules, lower case: as written, its file
* name after a \ or / path, the part before a glued /switch (cmd/c), each with
* and without .exe/.com/.bat/.cmd. Only for deny, ask and nested-shell checks,
* never to trust a program: dir.cmd is a script, not dir.
*/
function cmdNames(name: string): string[] {
const n = name.toLowerCase();
const forms = [n, n.slice(Math.max(n.lastIndexOf('\\'), n.lastIndexOf('/')) + 1), n.split('/')[0]];
return [...new Set(forms.flatMap((f) => [f, f.replace(/\.(exe|com|bat|cmd)$/, '')]))].filter(Boolean);
}

/** Every command a cmd line may run, as written and under each name of its program, for deny and ask rules. */
function cmdTargets(cmd: string): string[] {
return cmdParts(cmd).flatMap((p) => {
const { name, rest } = cmdCommand(p);
const args = rest.replace(/"/g, '').replace(/^[\s,;=]+/, '').trim();
return [p, ...cmdNames(name).map((n) => `${n} ${args}`.trim())];
});
}

/**
* cmd's own commands that only read. Built-ins only: cmd runs them before any
* file, while a program name (where, sort, git) may find a script in the
* folder first, and Windows programs share names, not flags, with POSIX ones
* (sort /o writes, date sets the clock).
*/
const CMD_READ_ONLY = new Set(['dir', 'type', 'echo', 'cd', 'chdir', 'ver', 'vol']);

/** True when a cmd line has nothing the checks cannot read and each of its commands is a read-only built-in, written bare. */
function cmdReadOnly(cmd: string): boolean {
return !cmdUnsure(cmd) && cmdParts(cmd).every((p) => {
const { name, quoted } = cmdCommand(p);
// a quoted or suffixed name ("dir", dir.cmd) is looked up as a file, not run as the built-in
return !quoted && /^[a-z]+$/i.test(name) && CMD_READ_ONLY.has(name.toLowerCase());
});
}

/** The shell a machine runs commands in: a paired device's from its hello, the hub's own from shell(). */
export function machineShell(machine: unknown): string | undefined {
const m = machine as { lastInfo?: { shell?: string }; shell?: () => string };
if (m.lastInfo) return m.lastInfo.shell;
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<string, any>, 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<string, any>;
Expand All @@ -236,6 +334,8 @@ export interface CheckInput {
home: string;
/** Directories edits may touch without asking in acceptEdits mode. */
workspaceRoots: string[];
/** The shell the command runs in (machineShell). cmd.exe gets its own reading of a Bash command; unset reads it as bash. */
shell?: string;
}

/** Bash as checkOne needs it, for preview_start's command (no import cycle with tools/bash.ts). */
Expand All @@ -256,7 +356,12 @@ export function checkPermission(c: CheckInput): PermissionCheck {

function checkOne(c: CheckInput): PermissionCheck {
const name = c.tool.name;
const readOnly = toolIsReadOnly(c.tool, c.input);
// cmd.exe: single quotes, backslashes and # hide nothing, so the bash reading may miss a command
const cmd = name === 'Bash' && !!c.content && !!c.shell && isCmd(c.shell) ? c.content : undefined;
const unsure = cmd !== undefined ? cmdUnsure(cmd) : undefined;
// the Bash tool's own readOnly reads the line as bash; sleep and watch waits are not read-only segments either way
// (BASH_RULES, preview_start's stand-in, is never read-only)
const readOnly = cmd !== undefined ? c.tool.readOnly !== false && !c.input?.run_in_background && cmdReadOnly(cmd) : toolIsReadOnly(c.tool, c.input);
const rules = (list: string[]) => list.map(parseRule).filter((r) => toolMatches(r.tool, name));

const matchAny = (list: ParsedRule[]): ParsedRule | undefined => {
Expand All @@ -268,32 +373,36 @@ function checkOne(c: CheckInput): PermissionCheck {
};

// deny: any sub-command hit denies, including commands inside $( ) and backticks
const bashTargets = name === 'Bash' && c.content ? bashRuleTargets(c.content) : [];
const bashTargets = name === 'Bash' && c.content ? [...new Set([...bashRuleTargets(c.content), ...(cmd !== undefined ? cmdTargets(cmd) : [])])] : [];
const denyRules = rules(c.rules.deny);
for (const part of bashTargets) {
const hit = denyRules.find((r) => contentMatches(r, name, part, c.cwd, c.home));
if (hit) return { decision: 'deny', reason: `Denied by rule ${hit.raw}`, rule: hit.raw };
}
const deny = matchAny(denyRules);
if (deny) return { decision: 'deny', reason: `Denied by rule ${deny.raw}`, rule: deny.raw };
// cmd syntax that hides which commands run cannot be cleared against a command deny rule: fail closed
const unsureDeny = unsure ? denyRules.find((r) => r.content !== undefined) : undefined;
if (unsureDeny) return { decision: 'deny', reason: `Denied: ${unsure} hides which commands run from rule ${unsureDeny.raw}`, rule: unsureDeny.raw };

if (c.mode === 'plan' && !readOnly && name !== 'ExitPlanMode') {
return { decision: 'deny', reason: 'Plan mode is read-only. Present a plan with ExitPlanMode first.' };
}

// ask: like deny, any sub-command hit asks
const askRules = rules(c.rules.ask);
const ask = matchAny(askRules) ?? bashTargets.map((p) => askRules.find((r) => contentMatches(r, name, p, c.cwd, c.home))).find(Boolean);
const ask =
matchAny(askRules) ?? bashTargets.map((p) => askRules.find((r) => contentMatches(r, name, p, c.cwd, c.home))).find(Boolean) ?? (unsure ? askRules.find((r) => r.content !== undefined) : undefined);
if (ask) return { decision: 'ask', reason: `Rule ${ask.raw} requires approval`, rule: ask.raw };

const allowList = rules([...c.rules.allow, ...c.sessionAllow]);
/** Set when prefix rules matched but the command has constructs they never cover. */
let gatedReason: string | undefined;
if (name === 'Bash' && c.content) {
const whole = c.content.trim();
const gated = gatedConstructs(whole);
const gated = cmd !== undefined ? (unsure ? [unsure] : []) : gatedConstructs(whole);
// a $(cat <<'EOF' ... EOF) commit message is one word here, so its lines are not sub-commands
const parts = splitBashCommand(maskSafeHeredocs(whole));
const parts = cmd !== undefined ? cmdParts(whole) : splitBashCommand(maskSafeHeredocs(whole));
if (gated.length) {
// only a bare "Bash" rule or a rule naming this exact command covers substitution, redirects and the like;
// the comparison is literal, so a suggested exact rule covers its command even when it contains *
Expand Down
Loading
Loading