mirror of
https://github.com/openclaw/openclaw.git
synced 2026-05-31 16:48:38 +00:00
* refactor: share talk event metric extraction * refactor: reuse shared coercion helpers * refactor: reuse shared primitive guards * refactor: reuse shared record guard * refactor: reuse shared primitive helpers * refactor: reuse shared string guards * refactor: reuse shared non-empty string guard * refactor: share plugin primitive coercion helpers * refactor: reuse plugin coercion helpers * refactor: reuse plugin coercion helpers in more plugins * refactor: reuse channel coercion helpers * refactor: reuse monitor coercion helpers * refactor: reuse provider coercion helpers * refactor: reuse core coercion helpers * refactor: reuse runtime coercion helpers * refactor: reuse helper coercion in codex paths * refactor: reuse helper coercion in runtime paths * refactor: reuse codex app-server coercion helpers * refactor: reuse codex record helpers * refactor: reuse migration and qa record helpers * refactor: reuse feishu and core helper guards * refactor: reuse browser and policy coercion helpers * refactor: reuse memory wiki record helper * refactor: share boolean coercion helpers * refactor: reuse finite number coercion * refactor: reuse trimmed string list helpers * refactor: reuse string list normalization * refactor: reuse remaining string list helpers * refactor: reuse string entry normalizer * refactor: share sorted string helpers * refactor: share string list normalization * test: preserve command registry browser imports * refactor: reuse trimmed list helpers * refactor: reuse string dedupe helpers * refactor: reuse local dedupe helpers * refactor: reuse more string dedupe helpers * refactor: reuse command string dedupe helpers * refactor: dedupe memory path lists with helper * refactor: expose string dedupe helpers to plugins * refactor: reuse core string dedupe helpers * refactor: reuse shared unique value helpers * refactor: reuse unique helpers in agent utilities * refactor: reuse unique helpers in config plumbing * refactor: reuse unique helpers in extensions * refactor: reuse unique helpers in core utilities * refactor: reuse unique helpers in qa plugins * refactor: reuse unique helpers in memory plugins * refactor: reuse unique helpers in channel plugins * refactor: reuse unique helpers in core tails * refactor: reuse unique helper in comfy workflow * refactor: reuse unique helpers in test utilities * refactor: expose unique value helper to plugins * refactor: reuse unique helpers for numeric lists * refactor: replace index dedupe filters * refactor: reuse string entry normalization * refactor: reuse string normalization in plugin helpers * refactor: reuse string normalization in extension helpers * refactor: reuse string normalization in channel parsers * refactor: reuse string normalization in memory search * refactor: reuse string normalization in provider parsers * refactor: reuse string normalization in qa helpers * refactor: reuse string normalization in infra parsers * refactor: reuse string normalization in messaging parsers * refactor: reuse string normalization in core parsers * refactor: reuse string normalization in extension parsers * refactor: reuse string normalization in remaining parsers * refactor: reuse string normalization in final parser spots * refactor: reuse string normalization in qa media helpers * refactor: reuse normalization in provider and media lists * refactor: reuse normalization for remaining set filters * refactor: reuse normalization in policy allowlists * refactor: reuse normalization in session and owner lists * refactor: centralize primitive string lists * refactor: reuse lowercase entry helpers * refactor: reuse sorted string helpers * refactor: reuse unique trimmed helpers * refactor: reuse string normalization helpers * refactor: reuse catalog string helpers * refactor: reuse remaining string helpers * refactor: simplify remaining list normalization * refactor: reuse codex auth order normalization * chore: refresh plugin sdk api baseline * fix: make shared string sorting deterministic * chore: refresh plugin sdk api baseline * fix: align host env security ordering
381 lines
11 KiB
TypeScript
381 lines
11 KiB
TypeScript
import { readFileSync, statSync } from "node:fs";
|
|
import path from "node:path";
|
|
import {
|
|
normalizeLowercaseStringOrEmpty,
|
|
normalizeOptionalString,
|
|
} from "../shared/string-coerce.js";
|
|
import { normalizeStringEntries } from "../shared/string-normalization.js";
|
|
|
|
export type WindowsSpawnResolution =
|
|
| "direct"
|
|
| "node-entrypoint"
|
|
| "exe-entrypoint"
|
|
| "shell-fallback";
|
|
|
|
export type WindowsSpawnCandidateResolution = Exclude<WindowsSpawnResolution, "shell-fallback">;
|
|
export type WindowsSpawnProgramCandidate = {
|
|
command: string;
|
|
leadingArgv: string[];
|
|
resolution: WindowsSpawnCandidateResolution | "unresolved-wrapper";
|
|
windowsHide?: boolean;
|
|
};
|
|
|
|
export type WindowsSpawnProgram = {
|
|
command: string;
|
|
leadingArgv: string[];
|
|
resolution: WindowsSpawnResolution;
|
|
shell?: boolean;
|
|
windowsHide?: boolean;
|
|
};
|
|
|
|
export type WindowsSpawnInvocation = {
|
|
command: string;
|
|
argv: string[];
|
|
resolution: WindowsSpawnResolution;
|
|
shell?: boolean;
|
|
windowsHide?: boolean;
|
|
};
|
|
|
|
export type ResolveWindowsSpawnProgramParams = {
|
|
command: string;
|
|
platform?: NodeJS.Platform;
|
|
env?: NodeJS.ProcessEnv;
|
|
execPath?: string;
|
|
packageName?: string;
|
|
/** Trusted compatibility escape hatch for callers that intentionally accept shell-mediated wrapper execution. */
|
|
allowShellFallback?: boolean;
|
|
};
|
|
export type ResolveWindowsSpawnProgramCandidateParams = Omit<
|
|
ResolveWindowsSpawnProgramParams,
|
|
"allowShellFallback"
|
|
>;
|
|
export type WindowsSpawnCommandInlineArgs = {
|
|
executable: string;
|
|
arguments: string;
|
|
};
|
|
|
|
const INLINE_ARGUMENT_EXECUTABLES = new Set([
|
|
"node",
|
|
"node.exe",
|
|
"npm",
|
|
"npm.cmd",
|
|
"npm.exe",
|
|
"npx",
|
|
"npx.cmd",
|
|
"npx.exe",
|
|
"pnpm",
|
|
"pnpm.cmd",
|
|
"pnpm.exe",
|
|
"yarn",
|
|
"yarn.cmd",
|
|
"yarn.exe",
|
|
]);
|
|
|
|
function isFilePath(candidate: string): boolean {
|
|
try {
|
|
return statSync(candidate).isFile();
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
function readCommandToken(command: string): { token: string; rest: string } | null {
|
|
const trimmed = command.trim();
|
|
if (!trimmed) {
|
|
return null;
|
|
}
|
|
if (trimmed.startsWith('"')) {
|
|
const closeIndex = trimmed.indexOf('"', 1);
|
|
if (closeIndex <= 0) {
|
|
return null;
|
|
}
|
|
return {
|
|
token: trimmed.slice(1, closeIndex),
|
|
rest: trimmed.slice(closeIndex + 1).trim(),
|
|
};
|
|
}
|
|
const match = trimmed.match(/^(\S+)\s+(.+)$/);
|
|
if (!match) {
|
|
return null;
|
|
}
|
|
return {
|
|
token: match[1] ?? "",
|
|
rest: (match[2] ?? "").trim(),
|
|
};
|
|
}
|
|
|
|
export function detectWindowsSpawnCommandInlineArgs(
|
|
command: string,
|
|
): WindowsSpawnCommandInlineArgs | null {
|
|
const parsed = readCommandToken(command);
|
|
if (!parsed?.rest) {
|
|
return null;
|
|
}
|
|
const normalizedToken = parsed.token.replace(/\\/g, "/");
|
|
const executable = normalizeLowercaseStringOrEmpty(path.posix.basename(normalizedToken));
|
|
if (!INLINE_ARGUMENT_EXECUTABLES.has(executable)) {
|
|
return null;
|
|
}
|
|
return {
|
|
executable: parsed.token,
|
|
arguments: parsed.rest,
|
|
};
|
|
}
|
|
|
|
/** Resolve a Windows command name through PATH and PATHEXT so wrapper inspection sees the real file. */
|
|
export function resolveWindowsExecutablePath(command: string, env: NodeJS.ProcessEnv): string {
|
|
if (command.includes("/") || command.includes("\\") || path.isAbsolute(command)) {
|
|
return command;
|
|
}
|
|
|
|
const pathValue = env.PATH ?? env.Path ?? process.env.PATH ?? process.env.Path ?? "";
|
|
const pathEntries = normalizeStringEntries(pathValue.split(";"));
|
|
const hasExtension = path.extname(command).length > 0;
|
|
const pathExtRaw =
|
|
env.PATHEXT ??
|
|
env.Pathext ??
|
|
process.env.PATHEXT ??
|
|
process.env.Pathext ??
|
|
".EXE;.CMD;.BAT;.COM";
|
|
const pathExt = hasExtension
|
|
? [""]
|
|
: normalizeStringEntries(pathExtRaw.split(";")).map((ext) =>
|
|
ext.startsWith(".") ? ext : `.${ext}`,
|
|
);
|
|
|
|
for (const dir of pathEntries) {
|
|
for (const ext of pathExt) {
|
|
const normalizedExt = normalizeLowercaseStringOrEmpty(ext);
|
|
const uppercaseExt = ext.toUpperCase();
|
|
for (const candidateExt of [ext, normalizedExt, uppercaseExt]) {
|
|
const candidate = path.join(dir, `${command}${candidateExt}`);
|
|
if (isFilePath(candidate)) {
|
|
return candidate;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return command;
|
|
}
|
|
|
|
function resolveEntrypointFromCmdShim(wrapperPath: string): string | null {
|
|
if (!isFilePath(wrapperPath)) {
|
|
return null;
|
|
}
|
|
|
|
try {
|
|
const content = readFileSync(wrapperPath, "utf8");
|
|
const candidates: string[] = [];
|
|
for (const match of content.matchAll(/"([^"\r\n]*)"/g)) {
|
|
const token = match[1] ?? "";
|
|
const relMatch = token.match(/%~?dp0%?\s*[\\/]*(.*)$/i);
|
|
const relative = relMatch?.[1]?.trim();
|
|
if (!relative) {
|
|
continue;
|
|
}
|
|
const normalizedRelative = relative.replace(/[\\/]+/g, path.sep).replace(/^[\\/]+/, "");
|
|
const candidate = path.resolve(path.dirname(wrapperPath), normalizedRelative);
|
|
if (isFilePath(candidate)) {
|
|
candidates.push(candidate);
|
|
}
|
|
}
|
|
const nonNode = candidates.find((candidate) => {
|
|
const base = normalizeLowercaseStringOrEmpty(path.basename(candidate));
|
|
return base !== "node.exe" && base !== "node";
|
|
});
|
|
return nonNode ?? null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function resolveBinEntry(
|
|
packageName: string | undefined,
|
|
binField: string | Record<string, string> | undefined,
|
|
): string | null {
|
|
if (typeof binField === "string") {
|
|
const trimmed = normalizeOptionalString(binField);
|
|
return trimmed || null;
|
|
}
|
|
if (!binField || typeof binField !== "object") {
|
|
return null;
|
|
}
|
|
|
|
if (packageName) {
|
|
const preferred = binField[packageName];
|
|
const normalizedPreferred =
|
|
typeof preferred === "string" ? normalizeOptionalString(preferred) : undefined;
|
|
if (normalizedPreferred) {
|
|
return normalizedPreferred;
|
|
}
|
|
}
|
|
|
|
for (const value of Object.values(binField)) {
|
|
const normalizedValue = typeof value === "string" ? normalizeOptionalString(value) : undefined;
|
|
if (normalizedValue) {
|
|
return normalizedValue;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function resolveEntrypointFromPackageJson(
|
|
wrapperPath: string,
|
|
packageName?: string,
|
|
): string | null {
|
|
if (!packageName) {
|
|
return null;
|
|
}
|
|
|
|
const wrapperDir = path.dirname(wrapperPath);
|
|
const packageDirs = [
|
|
path.resolve(wrapperDir, "..", packageName),
|
|
path.resolve(wrapperDir, "node_modules", packageName),
|
|
];
|
|
|
|
for (const packageDir of packageDirs) {
|
|
const packageJsonPath = path.join(packageDir, "package.json");
|
|
if (!isFilePath(packageJsonPath)) {
|
|
continue;
|
|
}
|
|
try {
|
|
const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8")) as {
|
|
bin?: string | Record<string, string>;
|
|
};
|
|
const entryRel = resolveBinEntry(packageName, packageJson.bin);
|
|
if (!entryRel) {
|
|
continue;
|
|
}
|
|
const entryPath = path.resolve(packageDir, entryRel);
|
|
if (isFilePath(entryPath)) {
|
|
return entryPath;
|
|
}
|
|
} catch {
|
|
// Ignore malformed package metadata.
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
/** Resolve the safest direct spawn candidate for Windows wrappers, scripts, and binaries. */
|
|
export function resolveWindowsSpawnProgramCandidate(
|
|
params: ResolveWindowsSpawnProgramCandidateParams,
|
|
): WindowsSpawnProgramCandidate {
|
|
const platform = params.platform ?? process.platform;
|
|
const env = params.env ?? process.env;
|
|
const execPath = params.execPath ?? process.execPath;
|
|
|
|
if (platform !== "win32") {
|
|
return {
|
|
command: params.command,
|
|
leadingArgv: [],
|
|
resolution: "direct",
|
|
};
|
|
}
|
|
const inlineArgs = detectWindowsSpawnCommandInlineArgs(params.command);
|
|
if (inlineArgs) {
|
|
throw new Error(
|
|
`Windows spawn command must be an executable path only; "${inlineArgs.executable}" was configured with inline arguments "${inlineArgs.arguments}". Put arguments in the caller's args array instead.`,
|
|
);
|
|
}
|
|
|
|
const resolvedCommand = resolveWindowsExecutablePath(params.command, env);
|
|
const ext = normalizeLowercaseStringOrEmpty(path.extname(resolvedCommand));
|
|
if (ext === ".js" || ext === ".cjs" || ext === ".mjs") {
|
|
return {
|
|
command: execPath,
|
|
leadingArgv: [resolvedCommand],
|
|
resolution: "node-entrypoint",
|
|
windowsHide: true,
|
|
};
|
|
}
|
|
|
|
if (ext === ".cmd" || ext === ".bat") {
|
|
const entrypoint =
|
|
resolveEntrypointFromCmdShim(resolvedCommand) ??
|
|
resolveEntrypointFromPackageJson(resolvedCommand, params.packageName);
|
|
if (entrypoint) {
|
|
const entryExt = normalizeLowercaseStringOrEmpty(path.extname(entrypoint));
|
|
if (entryExt === ".exe") {
|
|
return {
|
|
command: entrypoint,
|
|
leadingArgv: [],
|
|
resolution: "exe-entrypoint",
|
|
windowsHide: true,
|
|
};
|
|
}
|
|
return {
|
|
command: execPath,
|
|
leadingArgv: [entrypoint],
|
|
resolution: "node-entrypoint",
|
|
windowsHide: true,
|
|
};
|
|
}
|
|
|
|
return {
|
|
command: resolvedCommand,
|
|
leadingArgv: [],
|
|
resolution: "unresolved-wrapper",
|
|
};
|
|
}
|
|
|
|
return {
|
|
command: resolvedCommand,
|
|
leadingArgv: [],
|
|
resolution: "direct",
|
|
};
|
|
}
|
|
|
|
/** Apply shell-fallback policy when Windows wrapper resolution could not find a direct entrypoint. */
|
|
export function applyWindowsSpawnProgramPolicy(params: {
|
|
candidate: WindowsSpawnProgramCandidate;
|
|
allowShellFallback?: boolean;
|
|
}): WindowsSpawnProgram {
|
|
if (params.candidate.resolution !== "unresolved-wrapper") {
|
|
return {
|
|
command: params.candidate.command,
|
|
leadingArgv: params.candidate.leadingArgv,
|
|
resolution: params.candidate.resolution,
|
|
windowsHide: params.candidate.windowsHide,
|
|
};
|
|
}
|
|
if (params.allowShellFallback === true) {
|
|
return {
|
|
command: params.candidate.command,
|
|
leadingArgv: [],
|
|
resolution: "shell-fallback",
|
|
shell: true,
|
|
};
|
|
}
|
|
throw new Error(
|
|
`${path.basename(params.candidate.command)} wrapper resolved, but no executable/Node entrypoint could be resolved without shell execution.`,
|
|
);
|
|
}
|
|
|
|
/** Resolve the final Windows spawn program after candidate discovery and fallback policy. */
|
|
export function resolveWindowsSpawnProgram(
|
|
params: ResolveWindowsSpawnProgramParams,
|
|
): WindowsSpawnProgram {
|
|
const candidate = resolveWindowsSpawnProgramCandidate(params);
|
|
return applyWindowsSpawnProgramPolicy({
|
|
candidate,
|
|
allowShellFallback: params.allowShellFallback,
|
|
});
|
|
}
|
|
|
|
/** Combine a resolved Windows spawn program with call-site argv for actual process launch. */
|
|
export function materializeWindowsSpawnProgram(
|
|
program: WindowsSpawnProgram,
|
|
argv: string[],
|
|
): WindowsSpawnInvocation {
|
|
return {
|
|
command: program.command,
|
|
argv: [...program.leadingArgv, ...argv],
|
|
resolution: program.resolution,
|
|
shell: program.shell,
|
|
windowsHide: program.windowsHide,
|
|
};
|
|
}
|