Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

feat(security): execute argv-lane commands with execFile from the pinned PATH

Salman Qureshi9afd7fd28f35
diff --git a/src/capabilities/git/git-diff.ts b/src/capabilities/git/git-diff.ts
index 46a58eb9..682830a0 100644
--- a/src/capabilities/git/git-diff.ts
+++ b/src/capabilities/git/git-diff.ts
@@ -2,7 +2,7 @@ import { tool, zodSchema } from 'ai';
import { z } from 'zod';
import { execFileSync } from 'node:child_process';
import type { PermissionManager } from '../permissions.js';
-import { checkGitReadPath } from './git-path.js';
+import { checkGitReadPath, gitReadInvocation } from './git-path.js';
export function createGitDiffTool(permissions: PermissionManager, getCwd: () => string) {
return tool({
@@ -22,7 +22,9 @@ export function createGitDiffTool(permissions: PermissionManager, getCwd: () =>
args.push('--', path);
}
try {
- const result = execFileSync('git', args, { encoding: 'utf-8', timeout: 30000, cwd: getCwd() });
+ const git = gitReadInvocation(args);
+ if ('error' in git) return git.error;
+ const result = execFileSync(git.file, git.args, { encoding: 'utf-8', timeout: 30000, cwd: getCwd(), env: git.env });
if (!result.trim()) return 'No differences found.';
const truncated = result.length > 15000 ? result.slice(0, 15000) + '\n... (truncated)' : result;
return truncated;
diff --git a/src/capabilities/git/git-helpers.test.ts b/src/capabilities/git/git-helpers.test.ts
index 51fb0323..928f0250 100644
--- a/src/capabilities/git/git-helpers.test.ts
+++ b/src/capabilities/git/git-helpers.test.ts
@@ -17,6 +17,13 @@ import { createGitLogTool } from './git-log.js';
import { createGitDiffTool } from './git-diff.js';
import { createGitPushTool } from './git-push.js';
import type { PermissionManager } from '../permissions.js';
+import { setPinnedBinariesForTest } from '../shell/argv-lane.js';
+import { GIT_READ_HARDENING } from './git-path.js';
+
+// Read helpers run the git resolved from the pinned system PATH (#103).
+const PINNED_GIT = '/usr/bin/git';
+setPinnedBinariesForTest({ git: PINNED_GIT });
+const H = [...GIT_READ_HARDENING];
const CWD = '/repo';
const INJECTED = '/tmp/x"; echo pwned; "';
@@ -44,10 +51,13 @@ describe('git helpers pass the path as a single argv element (no shell)', () =>
expect(execSync).not.toHaveBeenCalled();
expect(execFileSync).toHaveBeenCalledTimes(1);
const [file, args, opts] = vi.mocked(execFileSync).mock.calls[0] as unknown as [string, string[], any];
- expect(file).toBe('git');
- expect(args).toEqual(['-C', resolve(INJECTED), 'status', '--porcelain']);
+ expect(file).toBe(PINNED_GIT);
+ expect(args).toEqual([...H, '-C', resolve(INJECTED), 'status', '--porcelain']);
expect(opts.cwd).toBe(CWD);
expect(opts.shell).toBeUndefined();
+ // Minimal env: pinned PATH, nothing inherited wholesale.
+ expect(opts.env.PATH).not.toBe(process.env.PATH);
+ expect(opts.env.GIT_PAGER).toBe('cat');
});
it('git_log: path follows `--` as one argv element', async () => {
@@ -56,8 +66,8 @@ describe('git helpers pass the path as a single argv element (no shell)', () =>
expect(execSync).not.toHaveBeenCalled();
const [file, args] = vi.mocked(execFileSync).mock.calls[0] as unknown as [string, string[]];
- expect(file).toBe('git');
- expect(args).toEqual(['log', '--oneline', '--decorate', '-5', '--', INJECTED]);
+ expect(file).toBe(PINNED_GIT);
+ expect(args).toEqual([...H, 'log', '--no-ext-diff', '--no-textconv', '--oneline', '--decorate', '-5', '--', INJECTED]);
});
it('git_diff: path follows `--` as one argv element', async () => {
@@ -66,8 +76,8 @@ describe('git helpers pass the path as a single argv element (no shell)', () =>
expect(execSync).not.toHaveBeenCalled();
const [file, args] = vi.mocked(execFileSync).mock.calls[0] as unknown as [string, string[]];
- expect(file).toBe('git');
- expect(args).toEqual(['diff', '--cached', '--', INJECTED]);
+ expect(file).toBe(PINNED_GIT);
+ expect(args).toEqual([...H, 'diff', '--no-ext-diff', '--no-textconv', '--cached', '--', INJECTED]);
});
it('git_push: remote and branch are argv elements, and options are refused', async () => {
@@ -91,7 +101,7 @@ describe('git helpers pass the path as a single argv element (no shell)', () =>
await run(createGitStatusTool(permissions, () => CWD), {});
expect(permissions.checkFsAccess).not.toHaveBeenCalled();
const [, args] = vi.mocked(execFileSync).mock.calls[0] as unknown as [string, string[]];
- expect(args).toEqual(['status', '--porcelain']);
+ expect(args).toEqual([...H, 'status', '--porcelain']);
});
});
diff --git a/src/capabilities/git/git-log.ts b/src/capabilities/git/git-log.ts
index fef5c44f..0629fc73 100644
--- a/src/capabilities/git/git-log.ts
+++ b/src/capabilities/git/git-log.ts
@@ -2,7 +2,7 @@ import { tool, zodSchema } from 'ai';
import { z } from 'zod';
import { execFileSync } from 'node:child_process';
import type { PermissionManager } from '../permissions.js';
-import { checkGitReadPath } from './git-path.js';
+import { checkGitReadPath, gitReadInvocation } from './git-path.js';
export function createGitLogTool(permissions: PermissionManager, getCwd: () => string) {
return tool({
@@ -22,7 +22,9 @@ export function createGitLogTool(permissions: PermissionManager, getCwd: () => s
args.push('--', path);
}
try {
- const result = execFileSync('git', args, { encoding: 'utf-8', timeout: 20000, cwd: getCwd() });
+ const git = gitReadInvocation(args);
+ if ('error' in git) return git.error;
+ const result = execFileSync(git.file, git.args, { encoding: 'utf-8', timeout: 20000, cwd: getCwd(), env: git.env });
if (!result.trim()) return 'No commits found.';
return result.trim();
} catch (err: any) {
diff --git a/src/capabilities/git/git-path.ts b/src/capabilities/git/git-path.ts
index e81abeda..fb594959 100644
--- a/src/capabilities/git/git-path.ts
+++ b/src/capabilities/git/git-path.ts
@@ -1,6 +1,7 @@
import { resolve, isAbsolute } from 'node:path';
import type { PermissionManager } from '../permissions.js';
import { readDenialMessage } from '../filesystem/verified-read.js';
+import { pinnedBinary, pinnedSearchDirs, minimalEnv } from '../shell/argv-lane.js';
/**
* Resolve a model-chosen path against the tool cwd and run it through the
@@ -31,3 +32,22 @@ export async function checkGitReadPath(
export function looksLikeGitOption(value: string): boolean {
return value.startsWith('-');
}
+
+/**
+ * Invocation for the auto-approved git read helpers (git_status, git_log,
+ * git_diff): the git binary from the pinned system PATH (never
+ * `process.env.PATH`, #103), a minimal environment, and config overrides so
+ * a repository's own `.git/config` cannot make a read run a program
+ * (fsmonitor hook, pager, external diff, textconv filter).
+ */
+export function gitReadInvocation(args: string[]): { file: string; args: string[]; env: NodeJS.ProcessEnv } | { error: string } {
+ const file = pinnedBinary('git');
+ if (!file) {
+ return { error: `Error: git was not found in the pinned system PATH (${pinnedSearchDirs().join(', ')}). Use run_command to run git with approval.` };
+ }
+ const [sub, ...rest] = args;
+ const body = sub === 'diff' || sub === 'log' ? [sub, '--no-ext-diff', '--no-textconv', ...rest] : args;
+ return { file, args: [...GIT_READ_HARDENING, ...body], env: minimalEnv() };
+}
+
+export const GIT_READ_HARDENING: readonly string[] = ['-c', 'core.fsmonitor=false', '-c', 'core.pager=cat', '--no-pager'];
diff --git a/src/capabilities/git/git-status.ts b/src/capabilities/git/git-status.ts
index 6d260676..988b0cfa 100644
--- a/src/capabilities/git/git-status.ts
+++ b/src/capabilities/git/git-status.ts
@@ -2,7 +2,7 @@ import { tool, zodSchema } from 'ai';
import { z } from 'zod';
import { execFileSync } from 'node:child_process';
import type { PermissionManager } from '../permissions.js';
-import { checkGitReadPath } from './git-path.js';
+import { checkGitReadPath, gitReadInvocation } from './git-path.js';
export function createGitStatusTool(permissions: PermissionManager, getCwd: () => string) {
return tool({
@@ -20,7 +20,9 @@ export function createGitStatusTool(permissions: PermissionManager, getCwd: () =
args.unshift('-C', check.resolved);
}
try {
- const result = execFileSync('git', args, { encoding: 'utf-8', timeout: 20000, cwd: getCwd() });
+ const git = gitReadInvocation(args);
+ if ('error' in git) return git.error;
+ const result = execFileSync(git.file, git.args, { encoding: 'utf-8', timeout: 20000, cwd: getCwd(), env: git.env });
if (!result.trim()) return 'Working tree clean — no changes.';
return result.trim();
} catch (err: any) {
diff --git a/src/capabilities/shell/run-command-argv.test.ts b/src/capabilities/shell/run-command-argv.test.ts
new file mode 100644
index 00000000..c680b8dd
--- /dev/null
+++ b/src/capabilities/shell/run-command-argv.test.ts
@@ -0,0 +1,112 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { EventEmitter } from 'node:events';
+import { PassThrough } from 'node:stream';
+
+/**
+ * Argv-lane execution: an auto-approved command must run through
+ * execFile(absBinary, argv, { env: minimal }) — never spawn(..., {shell}).
+ */
+vi.mock('node:child_process', () => {
+ const fakeChild = (stdoutText: string) => {
+ const child: any = new EventEmitter();
+ child.stdout = new PassThrough();
+ child.stderr = new PassThrough();
+ child.kill = vi.fn();
+ child.killed = false;
+ child.exitCode = null;
+ setTimeout(() => {
+ child.stdout.write(stdoutText);
+ child.exitCode = 0;
+ child.emit('exit', 0);
+ }, 1);
+ return child;
+ };
+ return {
+ execFile: vi.fn(() => fakeChild('argv-output\n')),
+ spawn: vi.fn(() => fakeChild('shell-output\n')),
+ };
+});
+
+import { execFile, spawn } from 'node:child_process';
+import { createRunCommandTool } from './run-command.js';
+import { setPinnedBinariesForTest, pinnedPath } from './argv-lane.js';
+import type { PermissionManager } from '../permissions.js';
+
+const run = (t: any, input: Record<string, unknown>) => (t.execute as any)(input, { toolCallId: 't', messages: [] });
+
+function fakePermissions(result: { allowed: boolean; lane?: 'argv' | 'shell'; reason?: string }) {
+ return { checkShellCommand: vi.fn(async () => ({ needsApproval: false, ...result })) } as unknown as PermissionManager & { checkShellCommand: ReturnType<typeof vi.fn> };
+}
+
+beforeEach(() => {
+ vi.mocked(execFile).mockClear();
+ vi.mocked(spawn).mockClear();
+ setPinnedBinariesForTest({ cat: '/usr/bin/cat', git: '/usr/bin/git', ls: '/bin/ls' });
+ process.env.SUPER_SECRET_TOKEN = 'do-not-leak';
+});
+
+describe('run_command argv lane', () => {
+ it('executes an auto-approved command with execFile, the pinned absolute binary and a minimal env', async () => {
+ const permissions = fakePermissions({ allowed: true, lane: 'argv' });
+ const tool = createRunCommandTool(permissions, () => '/work', () => {});
+ const out = await run(tool, { command: 'cat "my file.txt" other' });
+
+ expect(out).toBe('argv-output');
+ expect(spawn).not.toHaveBeenCalled();
+ expect(execFile).toHaveBeenCalledTimes(1);
+ const [file, args, opts] = vi.mocked(execFile).mock.calls[0] as unknown as [string, string[], any];
+ expect(file).toBe('/usr/bin/cat');
+ expect(args).toEqual(['my file.txt', 'other']);
+ expect(opts.cwd).toBe('/work');
+ expect(opts.shell).toBe(false);
+ expect(opts.env.PATH).toBe(pinnedPath());
+ expect(opts.env.SUPER_SECRET_TOKEN).toBeUndefined();
+ expect(permissions.checkShellCommand).toHaveBeenCalledWith('cat "my file.txt" other', { cwd: '/work' });
+ });
+
+ it('a user-approved command that the argv lane can express still runs without a shell', async () => {
+ const tool = createRunCommandTool(fakePermissions({ allowed: true, lane: 'shell' }), () => '/work', () => {});
+ await run(tool, { command: 'git log --oneline' });
+ expect(spawn).not.toHaveBeenCalled();
+ const [file, args] = vi.mocked(execFile).mock.calls[0] as unknown as [string, string[]];
+ expect(file).toBe('/usr/bin/git');
+ expect(args.slice(-1)).toEqual(['--oneline']);
+ expect(args).toContain('core.fsmonitor=false');
+ });
+
+ it('approval-lane commands (pipelines) run the exact approved string through the shell', async () => {
+ const tool = createRunCommandTool(fakePermissions({ allowed: true, lane: 'shell' }), () => '/work', () => {});
+ const out = await run(tool, { command: 'git log | head -5' });
+ expect(out).toBe('shell-output');
+ expect(execFile).not.toHaveBeenCalled();
+ const [cmd, , opts] = vi.mocked(spawn).mock.calls[0] as unknown as [string, string[], any];
+ expect(cmd).toBe('git log | head -5');
+ expect(opts.shell).toBe(true);
+ });
+
+ it('never falls back to a shell for an argv-lane approval it cannot execute directly', async () => {
+ setPinnedBinariesForTest({});
+ const tool = createRunCommandTool(fakePermissions({ allowed: true, lane: 'argv' }), () => '/work', () => {});
+ const out = await run(tool, { command: 'cat README.md' });
+ expect(out).toMatch(/requires approval/);
+ expect(spawn).not.toHaveBeenCalled();
+ expect(execFile).not.toHaveBeenCalled();
+ });
+
+ it('cd runs in-process and executes nothing', async () => {
+ const setCwd = vi.fn();
+ const tool = createRunCommandTool(fakePermissions({ allowed: true, lane: 'argv' }), () => process.cwd(), setCwd);
+ const out = await run(tool, { command: 'cd src' });
+ expect(out).toMatch(/Changed directory to/);
+ expect(setCwd).toHaveBeenCalledOnce();
+ expect(spawn).not.toHaveBeenCalled();
+ expect(execFile).not.toHaveBeenCalled();
+ });
+
+ it('denied commands execute nothing', async () => {
+ const tool = createRunCommandTool(fakePermissions({ allowed: false, reason: 'User denied: rm -rf x' }), () => '/work', () => {});
+ expect(await run(tool, { command: 'rm -rf x' })).toBe('Error: User denied: rm -rf x');
+ expect(spawn).not.toHaveBeenCalled();
+ expect(execFile).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/capabilities/shell/run-command.test.ts b/src/capabilities/shell/run-command.test.ts
index 9fcebe92..3dcef336 100644
--- a/src/capabilities/shell/run-command.test.ts
+++ b/src/capabilities/shell/run-command.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { executeCommand } from './run-command.js';
+import { executeCommand, executeArgv } from './run-command.js';
+import { pinnedPath } from './argv-lane.js';
// Portable long-running child: Node itself, printing a line every 200 ms.
const TICKER = `${JSON.stringify(process.execPath)} -e "let n=0;setInterval(()=>{console.log('tick',++n);},200)"`;
@@ -49,4 +50,20 @@ describe('run_command executor (ROADMAP P1.8)', () => {
const bad = await executeCommand(`${JSON.stringify(process.execPath)} -e "process.exit(3)"`, process.cwd(), 5_000);
expect(bad.exitCode).toBe(3);
});
+
+ it('argv lane: executeArgv runs without a shell and with the minimal env', async () => {
+ process.env.MERCURY_TEST_SECRET = 'leak-me';
+ const result = await executeArgv(
+ process.execPath,
+ ['-e', 'console.log(JSON.stringify({ path: process.env.PATH, secret: process.env.MERCURY_TEST_SECRET ?? null })); console.log(process.argv[1])', '$HOME;echo pwned'],
+ process.cwd(),
+ 5_000,
+ );
+ delete process.env.MERCURY_TEST_SECRET;
+ expect(result.exitCode).toBe(0);
+ const [json, arg] = result.stdout.trim().split('\n');
+ expect(JSON.parse(json)).toEqual({ path: pinnedPath(), secret: null });
+ // Arguments reach the program verbatim: no expansion, no command separator.
+ expect(arg).toBe('$HOME;echo pwned');
+ });
});
diff --git a/src/capabilities/shell/run-command.ts b/src/capabilities/shell/run-command.ts
index 08ee5b98..ddab761a 100644
--- a/src/capabilities/shell/run-command.ts
+++ b/src/capabilities/shell/run-command.ts
@@ -1,13 +1,14 @@
import { tool, zodSchema } from 'ai';
import { z } from 'zod';
-import { spawn } from 'node:child_process';
+import { spawn, execFile, type ChildProcess } from 'node:child_process';
import { resolve, isAbsolute } from 'node:path';
-import { existsSync } from 'node:fs';
+import { existsSync, statSync } from 'node:fs';
import { homedir } from 'node:os';
import type { PermissionManager } from '../permissions.js';
import { redactSecrets } from '../../utils/redact.js';
import { logger } from '../../utils/logger.js';
import { pulseProgress, TOOL_PULSE_INTERVAL_MS } from '../../core/progress-pulse.js';
+import { planArgvExecution, minimalEnv, type ArgvPlan } from './argv-lane.js';
const DEFAULT_TIMEOUT_MS = 120_000;
const MAX_BUFFER = 1024 * 1024;
@@ -31,7 +32,36 @@ interface ExecOptions {
onActivity?: () => void;
}
+/**
+ * Approval-lane executor: runs the exact string the user approved through
+ * the platform shell.
+ */
export function executeCommand(command: string, cwd: string, timeoutMs: number, options: ExecOptions = {}): Promise<ExecResult> {
+ return superviseChild(() => spawn(command, [], {
+ cwd,
+ shell: true,
+ stdio: ['pipe', 'pipe', 'pipe'],
+ }), timeoutMs, options);
+}
+
+/**
+ * Argv-lane executor: `execFile(absBinary, args)` with no shell and a
+ * minimal environment (pinned PATH, no secrets). Used only for commands the
+ * argv lane auto-approved.
+ */
+export function executeArgv(file: string, args: readonly string[], cwd: string, timeoutMs: number, options: ExecOptions = {}): Promise<ExecResult> {
+ return superviseChild(() => execFile(file, [...args], {
+ cwd,
+ env: minimalEnv(),
+ shell: false,
+ windowsHide: true,
+ // Output is bounded by the stream handlers below; execFile's own buffer
+ // limit would kill a long but legitimate listing.
+ maxBuffer: Number.MAX_SAFE_INTEGER,
+ }, () => { /* results are collected from the streams */ }), timeoutMs, options);
+}
+
+function superviseChild(start: () => ChildProcess, timeoutMs: number, options: ExecOptions): Promise<ExecResult> {
return new Promise((resolve) => {
let stdout = '';
let stderr = '';
@@ -41,11 +71,13 @@ export function executeCommand(command: string, cwd: string, timeoutMs: number,
let pulseHandle: ReturnType<typeof setInterval> | undefined;
const { signal, onActivity } = options;
- const child = spawn(command, [], {
- cwd,
- shell: true,
- stdio: ['pipe', 'pipe', 'pipe'],
- });
+ let child: ChildProcess;
+ try {
+ child = start();
+ } catch (err: any) {
+ resolve({ stdout: '', stderr: `Process error: ${err?.message ?? String(err)}`, exitCode: null, timedOut: false, aborted: false });
+ return;
+ }
const onAbort = () => terminate('abort');
@@ -71,7 +103,7 @@ export function executeCommand(command: string, cwd: string, timeoutMs: number,
finish(null, reason === 'timeout', reason === 'abort');
};
- child.stdout.on('data', (chunk: Buffer) => {
+ child.stdout?.on('data', (chunk: Buffer) => {
onActivity?.();
if (stdout.length < MAX_BUFFER) {
stdout += chunk.toString();
@@ -81,7 +113,7 @@ export function executeCommand(command: string, cwd: string, timeoutMs: number,
}
});
- child.stderr.on('data', (chunk: Buffer) => {
+ child.stderr?.on('data', (chunk: Buffer) => {
onActivity?.();
if (stderr.length < MAX_BUFFER) {
stderr += chunk.toString();
@@ -125,28 +157,40 @@ export function createRunCommandTool(permissions: PermissionManager, getCwd: ()
return tool({
description: `Run a shell command in the current working directory. Use the cd tool to change directories first — cd commands within this tool only affect chained commands (e.g., "cd /path && ls"), not subsequent calls.
Blocked commands (sudo, rm -rf /, etc.) are never executed.
-Auto-approved commands (ls, cat, git status, curl, etc.) run without asking.
-Other commands prompt the user for approval before execution.
+Simple read-only commands (ls, cat, grep, find, git status/log/diff, ...) with no pipes, redirection, variables or globs run without asking, executed directly (no shell).
+Everything else — including pipelines and && chains — prompts the user for approval before execution.
The optional timeout parameter sets how long (in seconds) the command can run before being killed (default 120, max 600). For very long builds or test suites, set a higher timeout or use /bg to run the command in the background.`,
inputSchema: zodSchema(z.object({
command: z.string().describe('The shell command to execute'),
timeout: z.number().min(10).max(600).default(120).optional().describe('Timeout in seconds (default 120, max 600). Increase for long-running commands like builds or test suites.'),
})),
execute: async ({ command, timeout }, toolOptions?: { abortSignal?: AbortSignal }) => {
- const check = await permissions.checkShellCommand(command);
+ const cwd = getCwd();
+ const check = await permissions.checkShellCommand(command, { cwd });
if (!check.allowed) {
return `Error: ${check.reason}`;
}
- const cwd = getCwd();
const timeoutMs = (timeout ?? 120) * 1000;
+ // Any command the argv lane can express runs through execFile, whichever
+ // lane approved it; only commands that need a shell reach one.
+ const plan = planArgvExecution(command);
+ if (plan?.kind === 'builtin') {
+ return runBuiltin(plan, cwd, setCwd);
+ }
+ if (check.lane === 'argv' && !plan) {
+ // Classified for the argv lane but no longer executable that way
+ // (e.g. the binary vanished): never fall back to a shell unapproved.
+ return 'Error: command could not be executed without a shell; it requires approval.';
+ }
+
try {
- logger.info({ cmd: command, cwd, timeoutMs }, 'Executing shell command');
- const result = await executeCommand(command, cwd, timeoutMs, {
- signal: toolOptions?.abortSignal,
- onActivity: pulseProgress,
- });
+ logger.info({ cmd: command, cwd, timeoutMs, lane: plan ? 'argv' : 'shell' }, 'Executing command');
+ const execOptions = { signal: toolOptions?.abortSignal, onActivity: pulseProgress };
+ const result = plan
+ ? await executeArgv(plan.file, plan.args, cwd, timeoutMs, execOptions)
+ : await executeCommand(command, cwd, timeoutMs, execOptions);
if (result.stdout || result.stderr) {
detectCd(command, cwd, setCwd);
@@ -202,6 +246,19 @@ The optional timeout parameter sets how long (in seconds) the command can run be
});
}
+/** `cd` in the argv lane: change the tool cwd in-process (it is a shell builtin). */
+function runBuiltin(plan: Extract<ArgvPlan, { kind: 'builtin' }>, cwd: string, setCwd: (dir: string) => void): string {
+ const target = plan.argv[1] ?? homedir();
+ const resolved = isAbsolute(target) ? resolve(target) : resolve(cwd, target);
+ try {
+ if (!statSync(resolved).isDirectory()) return `Error: Not a directory: ${resolved}`;
+ } catch {
+ return `Error: Directory not found: ${resolved}`;
+ }
+ setCwd(resolved);
+ return `Changed directory to ${resolved}`;
+}
+
function detectCd(command: string, currentCwd: string, setCwd: (dir: string) => void): void {
const trimmed = command.trim();
diff --git a/src/core/background-tasks.ts b/src/core/background-tasks.ts
index 0afcc35a..c6fff93b 100644
--- a/src/core/background-tasks.ts
+++ b/src/core/background-tasks.ts
@@ -1,4 +1,5 @@
import { spawn, type ChildProcess } from 'node:child_process';
+import { planArgvExecution, minimalEnv } from '../capabilities/shell/argv-lane.js';
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { logger } from '../utils/logger.js';
@@ -150,11 +151,17 @@ export class BackgroundTaskManager {
this.save();
try {
- const child = spawn(command, [], {
- cwd,
- shell: true,
- stdio: ['pipe', 'pipe', 'pipe'],
- });
+ // Same lane split as run_command: a command the argv lane can express
+ // runs via execFile from the pinned PATH with a minimal env; only the
+ // rest (already approved by the caller's checkShellCommand) uses a shell.
+ const plan = planArgvExecution(command);
+ const child = plan?.kind === 'exec'
+ ? spawn(plan.file, plan.args, { cwd, env: minimalEnv(), shell: false, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true })
+ : spawn(command, [], {
+ cwd,
+ shell: true,
+ stdio: ['pipe', 'pipe', 'pipe'],
+ });
task.pid = child.pid ?? undefined;
this.processes.set(id, child);