惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园_首页
博客园 - Franky
大猫的无限游戏
大猫的无限游戏
博客园 - 三生石上(FineUI控件)
量子位
博客园 - 聂微东
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
S
SegmentFault 最新的问题
Apple Machine Learning Research
Apple Machine Learning Research
爱范儿
爱范儿
V
Visual Studio Blog
雷峰网
雷峰网
T
Tailwind CSS Blog
宝玉的分享
宝玉的分享
Blog — PlanetScale
Blog — PlanetScale
有赞技术团队
有赞技术团队
博客园 - 叶小钗
Microsoft Azure Blog
Microsoft Azure Blog
T
The Blog of Author Tim Ferriss
U
Unit 42
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
小众软件
小众软件
阮一峰的网络日志
阮一峰的网络日志
Y
Y Combinator Blog

Recent Commits to openclaw:main

test: merge chat side-result checks · openclaw/openclaw@ddd2c2a test: merge cron history checks · openclaw/openclaw@f7eb746 test: merge responsive navigation shell checks · openclaw/openclaw@c2e4b47 docs(changelog): add codex oauth fixes · openclaw/openclaw@628e6cd test: merge navigation routing cases · openclaw/openclaw@5d8cecb Tests: mock channel registry bundled fallback · openclaw/openclaw@2b08233 Secrets: avoid broad web search discovery for single plugin config · openclaw/openclaw@a464f59 test: merge config view browser checks · openclaw/openclaw@20cf511 fix(status): align oauth health with runtime · openclaw/openclaw@eed7116 feat: add macOS screen snapshots for monitor preview (#67954) thanks … · openclaw/openclaw@f377db1 fix: report shared auth scopes in hello-ok (#67810) thanks @BunsDev · openclaw/openclaw@0b6c39b Auto-reply: avoid eager bundled route fallback · openclaw/openclaw@3ea1bf4 Tests: narrow session binding contract setup · openclaw/openclaw@54e4e16 fix(macOS): enable undo/redo in webchat composer text input (#34962) · openclaw/openclaw@00951dc Tests: speed up channel setup promotion · openclaw/openclaw@82b529a Docs: refresh agent instructions · openclaw/openclaw@5775fe2 fix(auth): serialize OAuth refresh across agents to fix #26322 (#67876) · openclaw/openclaw@8e79080 test: allow ollama public surface boundary test · openclaw/openclaw@7d4f1a6 Docs: add test performance guardrails · openclaw/openclaw@89706d3 Tests: restore context-engine usage proof · openclaw/openclaw@e4c4f95 Tests: slim context engine runtime coverage · openclaw/openclaw@74c198f ci: retry failed custom checkouts · openclaw/openclaw@0ee5baf test: trim duplicate provider auth onboarding cases · openclaw/openclaw@1ffc02e matrix: fix sessions_spawn --thread subagent session spawning (#67643) · openclaw/openclaw@1ce2596 test: reduce auth choice fixture churn · openclaw/openclaw@857b9cd test: mock health status config boundaries · openclaw/openclaw@9d5ab4a test: mock onboard config io boundary · openclaw/openclaw@299694d test: mock legacy state plugin boundaries · openclaw/openclaw@2713089 test: mock channel install boundaries · openclaw/openclaw@b945248 test: mock doctor preview channel boundaries · openclaw/openclaw@b1a3ad4
fix(process): wrap Windows command shims · openclaw/openc...
vincentkoc · 2026-06-20 · via Recent Commits to openclaw:main
Original file line numberDiff line numberDiff line change

@@ -11,50 +11,18 @@ import {

1111

decodeWindowsOutputBuffer,

1212

resolveWindowsConsoleEncoding,

1313

} from "../infra/windows-encoding.js";

14-

import { getWindowsInstallRoots } from "../infra/windows-install-roots.js";

1514

import { logDebug, logError } from "../logger.js";

1615

import { killProcessTree as terminateProcessTree } from "./kill-tree.js";

1716

import { resolveCommandStdio } from "./spawn-utils.js";

18-

import { resolveWindowsCommandShim } from "./windows-command.js";

17+

import {

18+

buildWindowsCmdExeCommandLine,

19+

isWindowsBatchCommand,

20+

resolveTrustedWindowsCmdExe,

21+

resolveWindowsCommandShim,

22+

} from "./windows-command.js";

1923
2024

const execFileAsync = promisify(execFile);

2125
22-

const WINDOWS_UNSAFE_CMD_CHARS_RE = /[&|<>^%\r\n]/;

23-
24-

function isWindowsBatchCommand(resolvedCommand: string): boolean {

25-

if (process.platform !== "win32") {

26-

return false;

27-

}

28-

const ext = normalizeLowercaseStringOrEmpty(path.extname(resolvedCommand));

29-

return ext === ".cmd" || ext === ".bat";

30-

}

31-
32-

function escapeForCmdExe(arg: string): string {

33-

// Reject cmd metacharacters to avoid injection when we must pass a single command line.

34-

if (WINDOWS_UNSAFE_CMD_CHARS_RE.test(arg)) {

35-

throw new Error(

36-

`Unsafe Windows cmd.exe argument detected: ${JSON.stringify(arg)}. ` +

37-

"Pass an explicit shell-wrapper argv at the call site instead.",

38-

);

39-

}

40-

// Quote when needed; double inner quotes for cmd parsing.

41-

if (!arg.includes(" ") && !arg.includes('"')) {

42-

return arg;

43-

}

44-

return `"${arg.replace(/"/g, '""')}"`;

45-

}

46-
47-

function buildCmdExeCommandLine(resolvedCommand: string, args: string[]): string {

48-

return [escapeForCmdExe(resolvedCommand), ...args.map(escapeForCmdExe)].join(" ");

49-

}

50-
51-

function resolveTrustedWindowsCmdExe(): string {

52-

if (process.platform !== "win32") {

53-

return "cmd.exe";

54-

}

55-

return path.win32.join(getWindowsInstallRoots().systemRoot, "System32", "cmd.exe");

56-

}

57-
5826

function assignChildEnvValue(params: {

5927

env: NodeJS.ProcessEnv;

6028

key: string;

@@ -154,7 +122,7 @@ function resolveChildProcessInvocation(params: {

154122

return {

155123

command: useCmdWrapper ? resolveTrustedWindowsCmdExe() : resolvedCommand,

156124

args: useCmdWrapper

157-

? ["/d", "/s", "/c", buildCmdExeCommandLine(resolvedCommand, finalArgv.slice(1))]

125+

? ["/d", "/s", "/c", buildWindowsCmdExeCommandLine(resolvedCommand, finalArgv.slice(1))]

158126

: finalArgv.slice(1),

159127

usesWindowsExitCodeShim:

160128

process.platform === "win32" && (useCmdWrapper || finalArgv !== params.argv),

@@ -460,11 +428,7 @@ export async function runCommandWithTimeout(

460428

} else {

461429

killIssuedByAbort = true;

462430

}

463-

if (

464-

killProcessTree &&

465-

typeof child.pid === "number" &&

466-

child.pid > 0

467-

) {

431+

if (killProcessTree && typeof child.pid === "number" && child.pid > 0) {

468432

if (process.platform === "win32") {

469433

try {

470434

spawn("taskkill", ["/PID", String(child.pid), "/T"], {

Original file line numberDiff line numberDiff line change

@@ -295,6 +295,24 @@ describe("windows command wrapper behavior", () => {

295295

});

296296

});

297297
298+

it("escapes caret arguments in Windows command wrappers", async () => {

299+

spawnMock.mockImplementation(

300+

(_command: string, _args: string[], _options: Record<string, unknown>) => createMockChild(),

301+

);

302+
303+

await withMockedWindowsPlatform(async () => {

304+

const result = await runCommandWithTimeout(

305+

["pnpm", "exec", "vitest", "-t", "@scope/pkg@^1.2.3"],

306+

{ timeoutMs: 1000 },

307+

);

308+

expect(result.code).toBe(0);

309+

const captured = requireSpawnCall(0);

310+

expect(captured[1].slice(0, 3)).toEqual(["/d", "/s", "/c"]);

311+

expect(captured[1][3]).toBe("pnpm.cmd exec vitest -t @scope/pkg@^^1.2.3");

312+

expect(captured[2].windowsVerbatimArguments).toBe(true);

313+

});

314+

});

315+
298316

it("keeps child exitCode when close reports null on Windows npm shims", async () => {

299317

const child = createMockChild({ closeCode: null, exitCode: 0 });

300318

@@ -397,6 +415,35 @@ describe("windows command wrapper behavior", () => {

397415

});

398416

});

399417
418+

it("wraps spaced .cmd command paths in an outer cmd.exe command line", async () => {

419+

const expectedComSpec = expectedTrustedCmdExe();

420+
421+

execFileMock.mockImplementation(

422+

(

423+

_command: string,

424+

_args: string[],

425+

_options: Record<string, unknown>,

426+

cb: (err: Error | null, stdout: string, stderr: string) => void,

427+

) => {

428+

cb(null, "ok", "");

429+

},

430+

);

431+
432+

await withMockedWindowsPlatform(async () => {

433+

await runExec("C:\\Program Files\\pnpm\\pnpm.cmd", ["--version"], 1000);

434+

const captured = requireExecFileCall(0);

435+

expect(captured[0]).toBe(expectedComSpec);

436+

expect(captured[1]).toEqual([

437+

"/d",

438+

"/s",

439+

"/c",

440+

'""C:\\Program Files\\pnpm\\pnpm.cmd" --version"',

441+

]);

442+

expect(captured[2].windowsHide).toBe(true);

443+

expect(captured[2].windowsVerbatimArguments).toBe(true);

444+

});

445+

});

446+
400447

it("sets windowsHide on direct runExec invocations too", async () => {

401448

execFileMock.mockImplementation(

402449

(

Original file line numberDiff line numberDiff line change

@@ -1,8 +1,13 @@

11

// Child adapter tests cover adapting child processes to supervisor runs.

22

import type { ChildProcess } from "node:child_process";

33

import { EventEmitter } from "node:events";

4+

import path from "node:path";

45

import { PassThrough } from "node:stream";

56

import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";

7+

import {

8+

getWindowsInstallRoots,

9+

resetWindowsInstallRootsForTests,

10+

} from "../../../infra/windows-install-roots.js";

611

import {

712

expectRealExitWinsOverSigkillFallback,

813

expectWaitStaysPendingUntilSigkillFallback,

@@ -83,6 +88,8 @@ type SpawnWithFallbackParams = {

8388

detached?: boolean;

8489

env?: NodeJS.ProcessEnv | Record<string, string>;

8590

stdio?: string[];

91+

windowsHide?: boolean;

92+

windowsVerbatimArguments?: boolean;

8693

};

8794

fallbacks?: Array<{ options?: { detached?: boolean } }>;

8895

};

@@ -107,6 +114,10 @@ function firstMockArg(mock: { mock: { calls: readonly unknown[][] } }, label: st

107114

return call[0];

108115

}

109116
117+

function expectedTrustedCmdExe(): string {

118+

return path.win32.join(getWindowsInstallRoots().systemRoot, "System32", "cmd.exe");

119+

}

120+
110121

describe("createChildAdapter", () => {

111122

const originalServiceMarker = process.env.OPENCLAW_SERVICE_MARKER;

112123

const originalPlatformDescriptor = Object.getOwnPropertyDescriptor(process, "platform");

@@ -123,6 +134,7 @@ describe("createChildAdapter", () => {

123134

});

124135
125136

beforeEach(() => {

137+

resetWindowsInstallRootsForTests({ queryRegistryValue: () => null });

126138

spawnWithFallbackMock.mockClear();

127139

signalProcessTreeMock.mockClear();

128140

createWindowsOutputDecoderMock.mockClear();

@@ -390,6 +402,28 @@ describe("createChildAdapter", () => {

390402

expect(spawnArgs.options?.env).toBeUndefined();

391403

});

392404
405+

it("wraps Windows command shims through trusted cmd.exe", async () => {

406+

setPlatform("win32");

407+
408+

await createAdapterHarness({

409+

pid: 3335,

410+

argv: ["pnpm", "--version"],

411+

});

412+
413+

const spawnArgs = firstSpawnWithFallbackParams();

414+

expect(spawnArgs.argv).toEqual([

415+

expectedTrustedCmdExe(),

416+

"/d",

417+

"/s",

418+

"/c",

419+

"pnpm.cmd --version",

420+

]);

421+

expect(spawnArgs.options?.detached).toBe(false);

422+

expect(spawnArgs.options?.windowsHide).toBe(true);

423+

expect(spawnArgs.options?.windowsVerbatimArguments).toBe(true);

424+

expect(spawnArgs.fallbacks).toStrictEqual([]);

425+

});

426+
393427

it("wraps Linux child spawns and strips shell-init env", async () => {

394428

const originalBashEnv = process.env.BASH_ENV;

395429

const originalEnv = process.env.ENV;

Original file line numberDiff line numberDiff line change

@@ -4,7 +4,12 @@ import { createWindowsOutputDecoder } from "../../../infra/windows-encoding.js";

44

import { signalProcessTree } from "../../kill-tree.js";

55

import { prepareOomScoreAdjustedSpawn } from "../../linux-oom-score.js";

66

import { spawnWithFallback } from "../../spawn-utils.js";

7-

import { resolveWindowsCommandShim } from "../../windows-command.js";

7+

import {

8+

buildWindowsCmdExeCommandLine,

9+

isWindowsBatchCommand,

10+

resolveTrustedWindowsCmdExe,

11+

resolveWindowsCommandShim,

12+

} from "../../windows-command.js";

813

import type { ManagedRunStdin, SpawnProcessAdapter } from "../types.js";

914

import { toStringEnv } from "./env.js";

1015

@@ -18,6 +23,27 @@ function resolveCommand(command: string): string {

1823

});

1924

}

2025
26+

function resolveChildInvocation(params: { argv: string[]; windowsVerbatimArguments?: boolean }): {

27+

args: string[];

28+

command: string;

29+

windowsVerbatimArguments?: boolean;

30+

} {

31+

const resolvedCommand = resolveCommand(params.argv[0] ?? "");

32+

const args = params.argv.slice(1);

33+

if (!isWindowsBatchCommand(resolvedCommand)) {

34+

return {

35+

command: resolvedCommand,

36+

args,

37+

windowsVerbatimArguments: params.windowsVerbatimArguments,

38+

};

39+

}

40+

return {

41+

command: resolveTrustedWindowsCmdExe(),

42+

args: ["/d", "/s", "/c", buildWindowsCmdExeCommandLine(resolvedCommand, args)],

43+

windowsVerbatimArguments: true,

44+

};

45+

}

46+
2147

export type ChildAdapter = SpawnProcessAdapter<NodeJS.Signals | null>;

2248
2349

function isServiceManagedRuntime(): boolean {

@@ -32,10 +58,12 @@ export async function createChildAdapter(params: {

3258

input?: string;

3359

stdinMode?: "inherit" | "pipe-open" | "pipe-closed";

3460

}): Promise<ChildAdapter> {

35-

const resolvedArgv = [...params.argv];

36-

resolvedArgv[0] = resolveCommand(resolvedArgv[0] ?? "");

61+

const invocation = resolveChildInvocation({

62+

argv: params.argv,

63+

windowsVerbatimArguments: params.windowsVerbatimArguments,

64+

});

3765

const baseEnv = params.env ? toStringEnv(params.env) : undefined;

38-

const preparedSpawn = prepareOomScoreAdjustedSpawn(resolvedArgv[0] ?? "", resolvedArgv.slice(1), {

66+

const preparedSpawn = prepareOomScoreAdjustedSpawn(invocation.command, invocation.args, {

3967

env: baseEnv,

4068

});

4169

@@ -52,7 +80,7 @@ export async function createChildAdapter(params: {

5280

stdio: ["pipe", "pipe", "pipe"],

5381

detached: useDetached,

5482

windowsHide: true,

55-

windowsVerbatimArguments: params.windowsVerbatimArguments,

83+

windowsVerbatimArguments: invocation.windowsVerbatimArguments,

5684

};

5785

if (stdinMode === "inherit") {

5886

options.stdio = ["inherit", "pipe", "pipe"];

Original file line numberDiff line numberDiff line change

@@ -2,6 +2,47 @@

22

import path from "node:path";

33

import process from "node:process";

44

import { normalizeLowercaseStringOrEmpty } from "@openclaw/normalization-core/string-coerce";

5+

import { getWindowsInstallRoots } from "../infra/windows-install-roots.js";

6+
7+

const WINDOWS_UNSAFE_CMD_CHARS_RE = /[&|<>%\r\n]/;

8+
9+

export function isWindowsBatchCommand(

10+

resolvedCommand: string,

11+

platform: NodeJS.Platform = process.platform,

12+

): boolean {

13+

if (platform !== "win32") {

14+

return false;

15+

}

16+

const ext = normalizeLowercaseStringOrEmpty(path.extname(resolvedCommand));

17+

return ext === ".cmd" || ext === ".bat";

18+

}

19+
20+

function escapeForWindowsCmdExe(arg: string): string {

21+

if (WINDOWS_UNSAFE_CMD_CHARS_RE.test(arg)) {

22+

throw new Error(

23+

`Unsafe Windows cmd.exe argument detected: ${JSON.stringify(arg)}. ` +

24+

"Pass an explicit shell-wrapper argv at the call site instead.",

25+

);

26+

}

27+

const escaped = arg.replace(/\^/g, "^^");

28+

if (!escaped.includes(" ") && !escaped.includes('"')) {

29+

return escaped;

30+

}

31+

return `"${escaped.replace(/"/g, '""')}"`;

32+

}

33+
34+

export function buildWindowsCmdExeCommandLine(command: string, args: readonly string[]): string {

35+

const escapedCommand = escapeForWindowsCmdExe(command);

36+

const commandLine = [escapedCommand, ...args.map(escapeForWindowsCmdExe)].join(" ");

37+

return escapedCommand.startsWith('"') ? `"${commandLine}"` : commandLine;

38+

}

39+
40+

export function resolveTrustedWindowsCmdExe(platform: NodeJS.Platform = process.platform): string {

41+

if (platform !== "win32") {

42+

return "cmd.exe";

43+

}

44+

return path.win32.join(getWindowsInstallRoots().systemRoot, "System32", "cmd.exe");

45+

}

546
647

/**

748

* Resolve package-manager commands that Windows exposes through .cmd shims.