openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
2,634 lines • 89.2 kB
JavaScript
import "./redact-BDinS1q9.js";
import "./errors-BxyFnvP3.js";
import "./unhandled-rejections-CDJ8dOVP.js";
import "./logger-kwZIqwuw.js";
import { _ as resolveStateDir } from "./paths-ViKUYWUK.js";
import "./tmp-openclaw-dir-idKIOMmb.js";
import { r as theme, t as colorize } from "./theme-CdOoMzRk.js";
import "./globals-DBUMOBZ8.js";
import { m as defaultRuntime } from "./subsystem-DISldKSB.js";
import "./ansi-BEJF8NKS.js";
import "./boolean-C3GkJetE.js";
import "./env-Dnra1IpT.js";
import "./warning-filter-CBhOcgHd.js";
import "./utils-CS0Ikux6.js";
import { t as formatDocsLink } from "./links-8xRhWBQL.js";
import "./paths-C4Oy7wjk.js";
import "./auth-profiles-DRuJBw5y.js";
import { i as resolveAgentConfig } from "./agent-scope-bjWqU22i.js";
import "./boundary-path-Dm0QJ7-y.js";
import { t as sameFileIdentity } from "./file-identity-D_ydQ7JC.js";
import "./boundary-file-read-DcZxlWD8.js";
import { a as logWarn } from "./logger-BmpSCz93.js";
import "./exec-B5_AYfQG.js";
import "./workspace-D4K6QX9X.js";
import "./model-selection-BnFtDmP7.js";
import { K as analyzeArgvCommand, Q as resolvePlannedSegmentArgv, St as resolveInlineCommandMatch, Tt as normalizeExecutableToken, bt as POSIX_INLINE_COMMAND_FLAGS, ft as resolveExecutableFromPathEnv, it as resolveApprovalAuditCandidatePath, mt as POSIX_SHELL_WRAPPERS, ot as resolveCommandResolutionFromArgv, s as loadConfig, wt as unwrapKnownDispatchWrapperInvocation, yt as unwrapKnownShellMultiplexerInvocation } from "./io-y3Az_Onx.js";
import { d as sanitizeHostExecEnv, p as sanitizeSystemRunEnvOverrides, s as inspectHostExecEnvOverrides } from "./shell-env-BOu7XeT_.js";
import "./safe-text-yavot2qw.js";
import { n as VERSION } from "./version-CD3oP1-d.js";
import "./env-substitution-O6uabUmO.js";
import "./includes-Bj3eLUWH.js";
import "./zod-schema.providers-core-COy5nBQ0.js";
import "./legacy-web-search-BB-ZHEhz.js";
import { t as splitShellArgs } from "./shell-argv-DBxSfCs1.js";
import "./registry-C5UkPpaO.js";
import "./config-state-Br0ucqMb.js";
import "./min-host-version-RMBWtIAR.js";
import "./manifest-registry-B5JNQdOM.js";
import "./runtime-guard-PhQ6PwQa.js";
import "./avatar-policy-B5nOfso_.js";
import "./ip-Ce8EDTBZ.js";
import "./zod-schema.agent-runtime-Dtg4Jy6G.js";
import "./zod-schema.core-BuVz8Rk7.js";
import "./config-D4zN4BRl.js";
import "./file-lock-DEiVq2ow.js";
import "./audit-fs-DTQIjp2r.js";
import "./resolve-B7S4PlnO.js";
import "./profiles-COPO-hHI.js";
import { t as formatCliCommand } from "./command-format-DBQUhADm.js";
import { _ as resolveNodeWindowsTaskName, c as formatNodeServiceDescription, g as resolveNodeSystemdServiceName, h as resolveNodeLaunchAgentLabel } from "./constants-BYFJPaZy.js";
import { a as resolveNodeProgramArguments, n as resolveDaemonInstallRuntimeInputs, r as resolveDaemonNodeBinDir, t as emitDaemonInstallRuntimeWarning } from "./daemon-install-plan.shared-DlNoT_tA.js";
import { c as buildNodeServiceEnvironment } from "./runtime-paths-DOEOEFe-.js";
import { r as isGatewayDaemonRuntime, t as DEFAULT_GATEWAY_DAEMON_RUNTIME } from "./daemon-runtime-lubXrOfs.js";
import "./tailscale-CxY-91GZ.js";
import "./tailnet-DHiKSG7V.js";
import "./net-JAg9zL0G.js";
import "./auth-Buq0Niri.js";
import "./credentials-D8pfRimu.js";
import { h as GATEWAY_CLIENT_NAMES, m as GATEWAY_CLIENT_MODES } from "./message-channel-BliByQBl.js";
import "./store-C5UK26Ce.js";
import "./runtime-Iz8uZ7EU.js";
import "./plugins-B09-vgme.js";
import "./sessions-D9ZgHCHb.js";
import "./paths-rhN9LKM_.js";
import "./session-write-lock-va3qZE6f.js";
import { r as writeJsonAtomic } from "./json-files-2-D1jkJB.js";
import { dn as loadOrCreateDeviceIdentity, u as GatewayClient } from "./method-scopes-BiEi0X2g.js";
import "./call-CQbSO4Fr.js";
import "./prompt-style-C4CV4Y_p.js";
import "./ports-lsof-BLEgL_Gn.js";
import "./restart-stale-pids-BsPvlGJd.js";
import "./runtime-parse-BUn1nl6s.js";
import "./launchd-yOx8f787.js";
import "./service-DdJ2Qk7P.js";
import "./ports-FldL_Lhq.js";
import "./systemd-bGhJCG6J.js";
import { f as buildDaemonServiceSnapshot, h as installDaemonServiceAndEmit, n as createDaemonInstallActionContext, r as failIfNixDaemonInstallMode, t as createCliStatusTextStyles, u as resolveRuntimeStatusColor } from "./shared-CaPOEZsR.js";
import { c as buildPlatformRuntimeLogHints, l as buildPlatformServiceStartHints, u as formatRuntimeStatus } from "./systemd-hints-DvBn5bxv.js";
import "./logging-CznuqaMu.js";
import { t as parsePort } from "./parse-port-BdJPfG31.js";
import "./commands-C6oAw_H-.js";
import "./issue-format-BtLIwOtN.js";
import { i as runServiceUninstall, r as runServiceStop, t as runServiceRestart } from "./lifecycle-core-DUBuppms.js";
import { t as formatHelpExamples } from "./help-format-C_5MeE_w.js";
import "./identity-Dp-UIak4.js";
import "./heartbeat-Bdfr_onc.js";
import { Ap as formatExecCommand, Ip as normalizeSystemRunApprovalPlan, g as withTimeout, iC as getMachineDisplayName, jp as resolveSystemRunCommandRequest } from "./pi-embedded-CbCYZxIb.js";
import "./internal-hooks-CIUghoK4.js";
import "./multimodal-B8yEZcl5.js";
import "./memory-search-B_aq08y5.js";
import "./provider-catalog-rVN7ZbR5.js";
import "./secret-input-DXoOLNgb.js";
import "./bindings-CFudGB9Z.js";
import "./resolve-route-DwFWP4JW.js";
import "./routing-zOQ0wwtV.js";
import "./identity-file-DVLib087.js";
import "./outbound-runtime-m-y0nd6F.js";
import "./provider-env-vars-CpUJqT5v.js";
import "./provider-auth-input-Bus9W_qh.js";
import "./provider-model-minimax-DSmX4BNO.js";
import "./provider-models-BKjzpTsb.js";
import "./anthropic-vertex-provider-B2x4YywE.js";
import "./provider-catalog-BTgF8VyO.js";
import "./provider-catalog-D0IlX18O.js";
import "./provider-catalog-BTmUX0Mp.js";
import "./provider-catalog-sph_Rl63.js";
import "./provider-catalog-C7tUyBwV.js";
import "./provider-catalog-C8dPZpHW.js";
import "./provider-catalog-BJNff1VI.js";
import "./provider-catalog-IAdymoqT.js";
import "./provider-catalog-Bjc7evzh.js";
import "./models-config.providers.discovery-CjkO08q6.js";
import "./text-runtime-DVXt5xhi.js";
import "./tool-catalog-BjSY4C4F.js";
import "./docker-Bhjg8g2t.js";
import "./sandbox-DTlKNieF.js";
import "./common-zReYuoMM.js";
import "./image-ops-By4YfyWa.js";
import "./thinking-CJoSRIGR.js";
import "./path-alias-guards-CwRM04O1.js";
import "./sandbox-paths-Cn8i8Jxm.js";
import "./channel-actions-fV93bLjV.js";
import { t as detectMime } from "./mime-CsUtzcn2.js";
import "./ssrf-0bPJMoZR.js";
import "./fetch-guard-CYl1q2XH.js";
import "./provider-web-search-COZNygbd.js";
import "./manager-Bw8JrihM.js";
import "./config-schema-CPzP2Ds6.js";
import "./channel-plugin-common-ClptUZHU.js";
import "./status-helpers-Cflmo90d.js";
import "./conversation-runtime-nmWgJSXS.js";
import "./runtime-whatsapp-boundary-XjdkYMz_.js";
import "./pairing-store-BGKLrjo6.js";
import "./json-store--JDX3zNL.js";
import "./secret-file-Bif7RlZ-.js";
import "./channel-config-schema-CgpS17zB.js";
import "./setup-binary-C2MYZTCc.js";
import "./archive-pOxyr9r4.js";
import "./fs-safe-DZyOgpPN.js";
import "./signal-cli-install-fVOL9FvX.js";
import "./setup-wizard-proxy-DoOpOF8S.js";
import "./setup-BI3ohdrT.js";
import "./dm-policy-shared-DtcQProI.js";
import "./runtime-env-DQOYrXVl.js";
import "./temp-path-B91lt0LF.js";
import "./diagnostic-CDTtMQBT.js";
import "./logging-CCTKg_fh.js";
import "./config-runtime-BYNizC50.js";
import "./level-overrides-DzIzQ3ZY.js";
import { D as requestJsonlSocket, S as evaluateShellAllowlist, T as resolveAllowAlwaysPatterns, b as saveExecApprovals, c as normalizeExecApprovals, f as readExecApprovalsSnapshot, g as resolveExecApprovals, h as requiresExecApproval, n as addAllowlistEntry, o as mergeExecApprovalsSocketDefaults, p as recordAllowlistUse, r as ensureExecApprovals, x as evaluateExecAllowlist } from "./exec-approvals-BF_Qfdq8.js";
import "./webhook-ingress-D-H5frou.js";
import "./system-events-BU_NYynX.js";
import "./ssrf-policy-DYINyIKC.js";
import "./hook-runtime-BUYmDbaA.js";
import "./templating-BDXRiJUh.js";
import "./channel-reply-pipeline-BxH4-AP2.js";
import "./reply-history-n7nOPLta.js";
import "./commands-registry.data-BFXJWoqi.js";
import "./commands-registry-Bh9pJ817.js";
import "./frontmatter-CP5371Rm.js";
import "./env-overrides-BNSo89u5.js";
import "./skills-M0AZJeXx.js";
import "./skills-remote-BHxDA4Jw.js";
import "./workspace-dirs-DqDLiRvZ.js";
import "./pairing-token-DAszGmwD.js";
import "./skill-commands-D73dGR_l.js";
import { n as resolveBrowserConfig } from "./config-CLRQPUSt.js";
import { _ as startBrowserControlServiceFromConfig, f as redactCdpUrl, g as createBrowserControlContext, h as createBrowserRouteDispatcher } from "./routes-XT2JfvT-.js";
import "./ssh-tunnel-LM52qY6N.js";
import "./server-middleware-BP59C6FL.js";
import "./provider-auth-ref-CQEp9sp3.js";
import "./provider-auth-helpers-Do3RFvdi.js";
import "./provider-api-key-auth-BEeRW3dq.js";
import "./pairing-labels-D27Y4Vv6.js";
import "./directory-runtime-D9Y42mW-.js";
import "./read-only-account-inspect-CJPRBFj7.js";
import "./src-BoNU6eQs.js";
import "./web-media-PKy3RbRG.js";
import "./media-understanding-BDOSvuM9.js";
import "./web-media-CiSbdGPs.js";
import "./state-paths-Dvb3Mfl3.js";
import "./llm-task-Br6Ixjlh.js";
import "./pi-model-discovery-DO3tFksS.js";
import { i as isInterpreterLikeSafeBin, n as detectInterpreterInlineEvalArgv, o as resolveExecSafeBinRuntimePolicy, t as describeInterpreterInlineEval } from "./exec-inline-eval-CpmxWJsW.js";
import "./target-registry-9OUOvlxj.js";
import "./external-content-DZI9vlJn.js";
import "./brave-onFD06fq.js";
import "./duckduckgo-CZuAOfiQ.js";
import "./exa-5bwgY04k.js";
import "./security-runtime-xlw0Fxx2.js";
import "./provider-usage-ClxTGn5c.js";
import "./provider-models-Bjv0V4OP.js";
import "./media-understanding-provider-DllGbg-v.js";
import "./media-understanding-provider-BDq4rFL-.js";
import "./provider-onboard-CSnPvkMM.js";
import "./onboard-BU8aRvq7.js";
import "./perplexity-web-search-provider-CI38RNUU.js";
import "./perplexity-CMZbsreI.js";
import "./model-definitions-CLagLj0g.js";
import "./onboard-0P7GBI2D.js";
import "./provider-catalog-CKHo9CRM.js";
import "./provider-models-Dmjtw6kn.js";
import "./stream-C-KGzzT0.js";
import "./web-search-CO1hvu_l.js";
import "./stagger-CFqdtCYL.js";
import "./command-secret-targets-DLs8jC2H.js";
import "./delivery-queue-DHURMSqX.js";
import "./channel-summary-Ctrv7moa.js";
import "./follow-redirects-CVAaqIk4.js";
import "./tool-policy-match-DQWWRSN4.js";
import "./runtime-CAdCdG-M.js";
import "./channel-status-BfM90KqH.js";
import "./discord-core-DLbIyXWy.js";
import "./cli-runtime-Cx1v7N7v.js";
import "./config-presence-DA3j8Nmi.js";
import "./query-expansion-BOJBTXsp.js";
import "./search-manager-DNBHwaee.js";
import "./acp-runtime-BHZj-SLU.js";
import "./telegram-core-DD8gCuaX.js";
import "./audit-BI48Fi3j.js";
import "./gateway-runtime-Dn2qAGY7.js";
import { t as resolveGatewayConnectionAuth } from "./connection-auth-Nl2a3tDb.js";
import "./mcp-config-CDIWSqVk.js";
import { t as ensureOpenClawCliOnPath } from "./path-env-BjkQG0S1.js";
import { n as normalizeBrowserRequestPath, r as resolveRequestedBrowserProfile, t as isPersistentBrowserProfileMutation } from "./request-policy-Z4bqaQ0G.js";
import { i as NODE_SYSTEM_RUN_COMMANDS, n as NODE_EXEC_APPROVALS_COMMANDS, t as NODE_BROWSER_PROXY_COMMAND } from "./node-commands-BWlu9FbU.js";
import { t as resolveNodeService } from "./node-service-D4mvvQIK.js";
import fs from "node:fs";
import path from "node:path";
import { spawn, spawnSync } from "node:child_process";
import fs$1 from "node:fs/promises";
import crypto from "node:crypto";
//#region src/node-host/config.ts
const NODE_HOST_FILE = "node.json";
function resolveNodeHostConfigPath() {
return path.join(resolveStateDir(), NODE_HOST_FILE);
}
function normalizeConfig(config) {
const base = {
version: 1,
nodeId: "",
token: config?.token,
displayName: config?.displayName,
gateway: config?.gateway
};
if (config?.version === 1 && typeof config.nodeId === "string") base.nodeId = config.nodeId.trim();
if (!base.nodeId) base.nodeId = crypto.randomUUID();
return base;
}
async function loadNodeHostConfig() {
const filePath = resolveNodeHostConfigPath();
try {
const raw = await fs$1.readFile(filePath, "utf8");
return normalizeConfig(JSON.parse(raw));
} catch {
return null;
}
}
async function saveNodeHostConfig(config) {
await writeJsonAtomic(resolveNodeHostConfigPath(), config, { mode: 384 });
}
async function ensureNodeHostConfig() {
const normalized = normalizeConfig(await loadNodeHostConfig());
await saveNodeHostConfig(normalized);
return normalized;
}
//#endregion
//#region src/infra/exec-host.ts
async function requestExecHostViaSocket(params) {
const { socketPath, token, request } = params;
if (!socketPath || !token) return null;
const timeoutMs = params.timeoutMs ?? 2e4;
const requestJson = JSON.stringify(request);
const nonce = crypto.randomBytes(16).toString("hex");
const ts = Date.now();
const hmac = crypto.createHmac("sha256", token).update(`${nonce}:${ts}:${requestJson}`).digest("hex");
return await requestJsonlSocket({
socketPath,
payload: JSON.stringify({
type: "exec",
id: crypto.randomUUID(),
nonce,
ts,
hmac,
requestJson
}),
timeoutMs,
accept: (value) => {
const msg = value;
if (msg?.type !== "exec-res") return;
if (msg.ok === true && msg.payload) return {
ok: true,
payload: msg.payload
};
if (msg.ok === false && msg.error) return {
ok: false,
error: msg.error
};
return null;
}
});
}
//#endregion
//#region src/node-host/invoke-browser.ts
const BROWSER_PROXY_MAX_FILE_BYTES = 10 * 1024 * 1024;
const DEFAULT_BROWSER_PROXY_TIMEOUT_MS = 2e4;
const BROWSER_PROXY_STATUS_TIMEOUT_MS = 750;
function normalizeProfileAllowlist(raw) {
return Array.isArray(raw) ? raw.map((entry) => entry.trim()).filter(Boolean) : [];
}
function resolveBrowserProxyConfig() {
const proxy = loadConfig().nodeHost?.browserProxy;
const allowProfiles = normalizeProfileAllowlist(proxy?.allowProfiles);
return {
enabled: proxy?.enabled !== false,
allowProfiles
};
}
let browserControlReady = null;
async function ensureBrowserControlService() {
if (browserControlReady) return browserControlReady;
browserControlReady = (async () => {
const cfg = loadConfig();
if (!resolveBrowserConfig(cfg.browser, cfg).enabled) throw new Error("browser control disabled");
if (!await startBrowserControlServiceFromConfig()) throw new Error("browser control disabled");
})();
return browserControlReady;
}
function isProfileAllowed(params) {
const { allowProfiles, profile } = params;
if (!allowProfiles.length) return true;
if (!profile) return false;
return allowProfiles.includes(profile.trim());
}
function collectBrowserProxyPaths(payload) {
const paths = /* @__PURE__ */ new Set();
const obj = typeof payload === "object" && payload !== null ? payload : null;
if (!obj) return [];
if (typeof obj.path === "string" && obj.path.trim()) paths.add(obj.path.trim());
if (typeof obj.imagePath === "string" && obj.imagePath.trim()) paths.add(obj.imagePath.trim());
const download = obj.download;
if (download && typeof download === "object") {
const dlPath = download.path;
if (typeof dlPath === "string" && dlPath.trim()) paths.add(dlPath.trim());
}
return [...paths];
}
async function readBrowserProxyFile(filePath) {
const stat = await fs$1.stat(filePath).catch(() => null);
if (!stat || !stat.isFile()) return null;
if (stat.size > BROWSER_PROXY_MAX_FILE_BYTES) throw new Error(`browser proxy file exceeds ${Math.round(BROWSER_PROXY_MAX_FILE_BYTES / (1024 * 1024))}MB`);
const buffer = await fs$1.readFile(filePath);
const mimeType = await detectMime({
buffer,
filePath
});
return {
path: filePath,
base64: buffer.toString("base64"),
mimeType
};
}
function decodeParams$1(raw) {
if (!raw) throw new Error("INVALID_REQUEST: paramsJSON required");
return JSON.parse(raw);
}
function resolveBrowserProxyTimeout(timeoutMs) {
return typeof timeoutMs === "number" && Number.isFinite(timeoutMs) ? Math.max(1, Math.floor(timeoutMs)) : DEFAULT_BROWSER_PROXY_TIMEOUT_MS;
}
function isBrowserProxyTimeoutError(err) {
return String(err).includes("browser proxy request timed out");
}
function isWsBackedBrowserProxyPath(path) {
return path === "/act" || path === "/navigate" || path === "/pdf" || path === "/screenshot" || path === "/snapshot";
}
async function readBrowserProxyStatus(params) {
const query = params.profile ? { profile: params.profile } : {};
try {
const response = await withTimeout((signal) => params.dispatcher.dispatch({
method: "GET",
path: "/",
query,
signal
}), BROWSER_PROXY_STATUS_TIMEOUT_MS, "browser proxy status");
if (response.status >= 400 || !response.body || typeof response.body !== "object") return null;
const body = response.body;
return {
running: body.running,
transport: body.transport,
cdpHttp: body.cdpHttp,
cdpReady: body.cdpReady,
cdpUrl: body.cdpUrl
};
} catch {
return null;
}
}
function formatBrowserProxyTimeoutMessage(params) {
const parts = [`browser proxy timed out for ${params.method} ${params.path} after ${params.timeoutMs}ms`, params.wsBacked ? "ws-backed browser action" : "browser action"];
if (params.profile) parts.push(`profile=${params.profile}`);
if (params.status) {
const statusParts = [
`running=${String(params.status.running)}`,
`cdpHttp=${String(params.status.cdpHttp)}`,
`cdpReady=${String(params.status.cdpReady)}`
];
if (typeof params.status.transport === "string" && params.status.transport.trim()) statusParts.push(`transport=${params.status.transport}`);
if (typeof params.status.cdpUrl === "string" && params.status.cdpUrl.trim()) statusParts.push(`cdpUrl=${redactCdpUrl(params.status.cdpUrl)}`);
parts.push(`status(${statusParts.join(", ")})`);
}
return parts.join("; ");
}
async function runBrowserProxyCommand(paramsJSON) {
const params = decodeParams$1(paramsJSON);
const pathValue = typeof params.path === "string" ? params.path.trim() : "";
if (!pathValue) throw new Error("INVALID_REQUEST: path required");
const proxyConfig = resolveBrowserProxyConfig();
if (!proxyConfig.enabled) throw new Error("UNAVAILABLE: node browser proxy disabled");
await ensureBrowserControlService();
const cfg = loadConfig();
const resolved = resolveBrowserConfig(cfg.browser, cfg);
const method = typeof params.method === "string" ? params.method.toUpperCase() : "GET";
const path = normalizeBrowserRequestPath(pathValue);
const body = params.body;
const requestedProfile = resolveRequestedBrowserProfile({
query: params.query,
body,
profile: params.profile
}) ?? "";
const allowedProfiles = proxyConfig.allowProfiles;
if (allowedProfiles.length > 0) {
if (isPersistentBrowserProfileMutation(method, path)) throw new Error("INVALID_REQUEST: browser.proxy cannot create or delete persistent browser profiles when allowProfiles is configured");
if (path !== "/profiles") {
if (!isProfileAllowed({
allowProfiles: allowedProfiles,
profile: requestedProfile || resolved.defaultProfile
})) throw new Error("INVALID_REQUEST: browser profile not allowed");
} else if (requestedProfile) {
if (!isProfileAllowed({
allowProfiles: allowedProfiles,
profile: requestedProfile
})) throw new Error("INVALID_REQUEST: browser profile not allowed");
}
}
const timeoutMs = resolveBrowserProxyTimeout(params.timeoutMs);
const query = {};
const rawQuery = params.query ?? {};
for (const [key, value] of Object.entries(rawQuery)) {
if (value === void 0 || value === null) continue;
query[key] = typeof value === "string" ? value : String(value);
}
if (requestedProfile) query.profile = requestedProfile;
const dispatcher = createBrowserRouteDispatcher(createBrowserControlContext());
let response;
try {
response = await withTimeout((signal) => dispatcher.dispatch({
method: method === "DELETE" ? "DELETE" : method === "POST" ? "POST" : "GET",
path,
query,
body,
signal
}), timeoutMs, "browser proxy request");
} catch (err) {
if (!isBrowserProxyTimeoutError(err)) throw err;
const profileForStatus = requestedProfile || resolved.defaultProfile;
const status = await readBrowserProxyStatus({
dispatcher,
profile: path === "/profiles" ? void 0 : profileForStatus
});
throw new Error(formatBrowserProxyTimeoutMessage({
method,
path,
profile: path === "/profiles" ? void 0 : profileForStatus || void 0,
timeoutMs,
wsBacked: isWsBackedBrowserProxyPath(path),
status
}), { cause: err });
}
if (response.status >= 400) {
const message = response.body && typeof response.body === "object" && "error" in response.body ? String(response.body.error) : `HTTP ${response.status}`;
throw new Error(message);
}
const result = response.body;
if (allowedProfiles.length > 0 && path === "/profiles") {
const obj = typeof result === "object" && result !== null ? result : {};
obj.profiles = (Array.isArray(obj.profiles) ? obj.profiles : []).filter((entry) => {
if (!entry || typeof entry !== "object") return false;
const name = entry.name;
return typeof name === "string" && allowedProfiles.includes(name);
});
}
let files;
const paths = collectBrowserProxyPaths(result);
if (paths.length > 0) {
const loaded = await Promise.all(paths.map(async (p) => {
try {
const file = await readBrowserProxyFile(p);
if (!file) throw new Error("file not found");
return file;
} catch (err) {
throw new Error(`browser proxy file read failed for ${p}: ${String(err)}`, { cause: err });
}
}));
if (loaded.length > 0) files = loaded;
}
const payload = files ? {
result,
files
} : { result };
return JSON.stringify(payload);
}
//#endregion
//#region src/node-host/exec-policy.ts
function resolveExecApprovalDecision(value) {
if (value === "allow-once" || value === "allow-always") return value;
return null;
}
function formatSystemRunAllowlistMissMessage(params) {
if (params?.windowsShellWrapperBlocked) return "SYSTEM_RUN_DENIED: allowlist miss (Windows shell wrappers like cmd.exe /c require approval; approve once/always or run with --ask on-miss|always)";
if (params?.shellWrapperBlocked) return "SYSTEM_RUN_DENIED: allowlist miss (shell wrappers like sh/bash/zsh -c require approval; approve once/always or run with --ask on-miss|always)";
return "SYSTEM_RUN_DENIED: allowlist miss";
}
function evaluateSystemRunPolicy(params) {
const shellWrapperBlocked = params.security === "allowlist" && params.shellWrapperInvocation;
const windowsShellWrapperBlocked = shellWrapperBlocked && params.isWindows && params.cmdInvocation;
const analysisOk = shellWrapperBlocked ? false : params.analysisOk;
const allowlistSatisfied = shellWrapperBlocked ? false : params.allowlistSatisfied;
const approvedByAsk = params.approvalDecision !== null || params.approved === true;
if (params.security === "deny") return {
allowed: false,
eventReason: "security=deny",
errorMessage: "SYSTEM_RUN_DISABLED: security=deny",
analysisOk,
allowlistSatisfied,
shellWrapperBlocked,
windowsShellWrapperBlocked,
requiresAsk: false,
approvalDecision: params.approvalDecision,
approvedByAsk
};
const requiresAsk = requiresExecApproval({
ask: params.ask,
security: params.security,
analysisOk,
allowlistSatisfied
});
if (requiresAsk && !approvedByAsk) return {
allowed: false,
eventReason: "approval-required",
errorMessage: "SYSTEM_RUN_DENIED: approval required",
analysisOk,
allowlistSatisfied,
shellWrapperBlocked,
windowsShellWrapperBlocked,
requiresAsk,
approvalDecision: params.approvalDecision,
approvedByAsk
};
if (params.security === "allowlist" && (!analysisOk || !allowlistSatisfied) && !approvedByAsk) return {
allowed: false,
eventReason: "allowlist-miss",
errorMessage: formatSystemRunAllowlistMissMessage({
shellWrapperBlocked,
windowsShellWrapperBlocked
}),
analysisOk,
allowlistSatisfied,
shellWrapperBlocked,
windowsShellWrapperBlocked,
requiresAsk,
approvalDecision: params.approvalDecision,
approvedByAsk
};
return {
allowed: true,
analysisOk,
allowlistSatisfied,
shellWrapperBlocked,
windowsShellWrapperBlocked,
requiresAsk,
approvalDecision: params.approvalDecision,
approvedByAsk
};
}
//#endregion
//#region src/node-host/invoke-system-run-allowlist.ts
function evaluateSystemRunAllowlist(params) {
if (params.shellCommand) {
const allowlistEval = evaluateShellAllowlist({
command: params.shellCommand,
allowlist: params.approvals.allowlist,
safeBins: params.safeBins,
safeBinProfiles: params.safeBinProfiles,
cwd: params.cwd,
env: params.env,
trustedSafeBinDirs: params.trustedSafeBinDirs,
skillBins: params.skillBins,
autoAllowSkills: params.autoAllowSkills,
platform: process.platform
});
return {
analysisOk: allowlistEval.analysisOk,
allowlistMatches: allowlistEval.allowlistMatches,
allowlistSatisfied: params.security === "allowlist" && allowlistEval.analysisOk ? allowlistEval.allowlistSatisfied : false,
segments: allowlistEval.segments
};
}
const analysis = analyzeArgvCommand({
argv: params.argv,
cwd: params.cwd,
env: params.env
});
const allowlistEval = evaluateExecAllowlist({
analysis,
allowlist: params.approvals.allowlist,
safeBins: params.safeBins,
safeBinProfiles: params.safeBinProfiles,
cwd: params.cwd,
trustedSafeBinDirs: params.trustedSafeBinDirs,
skillBins: params.skillBins,
autoAllowSkills: params.autoAllowSkills
});
return {
analysisOk: analysis.ok,
allowlistMatches: allowlistEval.allowlistMatches,
allowlistSatisfied: params.security === "allowlist" && analysis.ok ? allowlistEval.allowlistSatisfied : false,
segments: analysis.segments
};
}
function resolvePlannedAllowlistArgv(params) {
if (params.security !== "allowlist" || params.policy.approvedByAsk || params.shellCommand || !params.policy.analysisOk || !params.policy.allowlistSatisfied || params.segments.length !== 1) return;
const plannedAllowlistArgv = resolvePlannedSegmentArgv(params.segments[0]);
return plannedAllowlistArgv && plannedAllowlistArgv.length > 0 ? plannedAllowlistArgv : null;
}
function resolveSystemRunExecArgv(params) {
let execArgv = params.plannedAllowlistArgv ?? params.argv;
if (params.security === "allowlist" && params.isWindows && !params.policy.approvedByAsk && params.shellCommand && params.policy.analysisOk && params.policy.allowlistSatisfied && params.segments.length === 1 && params.segments[0]?.argv.length > 0) execArgv = params.segments[0].argv;
return execArgv;
}
function applyOutputTruncation(result) {
if (!result.truncated) return;
const suffix = "... (truncated)";
if (result.stderr.trim().length > 0) result.stderr = `${result.stderr}\n${suffix}`;
else result.stdout = `${result.stdout}\n${suffix}`;
}
//#endregion
//#region src/node-host/invoke-system-run-plan.ts
const MUTABLE_ARGV1_INTERPRETER_PATTERNS = [
/^(?:node|nodejs)$/,
/^perl$/,
/^php$/,
/^python(?:\d+(?:\.\d+)*)?$/,
/^ruby$/
];
const GENERIC_MUTABLE_SCRIPT_RUNNERS = new Set([
"esno",
"jiti",
"ts-node",
"ts-node-esm",
"tsx",
"vite-node"
]);
const BUN_SUBCOMMANDS = new Set([
"add",
"audit",
"completions",
"create",
"exec",
"help",
"init",
"install",
"link",
"outdated",
"patch",
"pm",
"publish",
"remove",
"repl",
"run",
"test",
"unlink",
"update",
"upgrade",
"x"
]);
const BUN_OPTIONS_WITH_VALUE = new Set([
"--backend",
"--bunfig",
"--conditions",
"--config",
"--console-depth",
"--cwd",
"--define",
"--elide-lines",
"--env-file",
"--extension-order",
"--filter",
"--hot",
"--inspect",
"--inspect-brk",
"--inspect-wait",
"--install",
"--jsx-factory",
"--jsx-fragment",
"--jsx-import-source",
"--loader",
"--origin",
"--port",
"--preload",
"--smol",
"--tsconfig-override",
"-c",
"-e",
"-p",
"-r"
]);
const DENO_RUN_OPTIONS_WITH_VALUE = new Set([
"--cached-only",
"--cert",
"--config",
"--env-file",
"--ext",
"--harmony-import-attributes",
"--import-map",
"--inspect",
"--inspect-brk",
"--inspect-wait",
"--location",
"--log-level",
"--lock",
"--node-modules-dir",
"--no-check",
"--preload",
"--reload",
"--seed",
"--strace-ops",
"--unstable-bare-node-builtins",
"--v8-flags",
"--watch",
"--watch-exclude",
"-L"
]);
const NODE_OPTIONS_WITH_FILE_VALUE = new Set([
"-r",
"--experimental-loader",
"--import",
"--loader",
"--require"
]);
const RUBY_UNSAFE_APPROVAL_FLAGS = new Set([
"-I",
"-r",
"--require"
]);
const PERL_UNSAFE_APPROVAL_FLAGS = new Set([
"-I",
"-M",
"-m"
]);
const POSIX_SHELL_OPTIONS_WITH_VALUE = new Set([
"--init-file",
"--rcfile",
"--startup-script",
"-o"
]);
const NPM_EXEC_OPTIONS_WITH_VALUE = new Set([
"--cache",
"--package",
"--prefix",
"--script-shell",
"--userconfig",
"--workspace",
"-p",
"-w"
]);
const NPM_EXEC_FLAG_OPTIONS = new Set([
"--no",
"--quiet",
"--ws",
"--workspaces",
"--yes",
"-q",
"-y"
]);
const PNPM_OPTIONS_WITH_VALUE = new Set([
"--config",
"--dir",
"--filter",
"--reporter",
"--stream",
"--test-pattern",
"--workspace-concurrency",
"-C"
]);
const PNPM_FLAG_OPTIONS = new Set([
"--aggregate-output",
"--color",
"--recursive",
"--silent",
"--workspace-root",
"-r"
]);
function normalizeString(value) {
if (typeof value !== "string") return null;
const trimmed = value.trim();
return trimmed ? trimmed : null;
}
function pathComponentsFromRootSync(targetPath) {
const absolute = path.resolve(targetPath);
const parts = [];
let cursor = absolute;
while (true) {
parts.unshift(cursor);
const parent = path.dirname(cursor);
if (parent === cursor) return parts;
cursor = parent;
}
}
function isWritableByCurrentProcessSync(candidate) {
try {
fs.accessSync(candidate, fs.constants.W_OK);
return true;
} catch {
return false;
}
}
function hasMutableSymlinkPathComponentSync(targetPath) {
for (const component of pathComponentsFromRootSync(targetPath)) try {
if (!fs.lstatSync(component).isSymbolicLink()) continue;
if (isWritableByCurrentProcessSync(path.dirname(component))) return true;
} catch {
return true;
}
return false;
}
function shouldPinExecutableForApproval(params) {
if (params.shellCommand !== null) return false;
return (params.wrapperChain?.length ?? 0) === 0;
}
function hashFileContentsSync(filePath) {
return crypto.createHash("sha256").update(fs.readFileSync(filePath)).digest("hex");
}
function looksLikePathToken(token) {
return token.startsWith(".") || token.startsWith("/") || token.startsWith("\\") || token.includes("/") || token.includes("\\") || path.extname(token).length > 0;
}
function resolvesToExistingFileSync(rawOperand, cwd) {
if (!rawOperand) return false;
try {
return fs.statSync(path.resolve(cwd ?? process.cwd(), rawOperand)).isFile();
} catch {
return false;
}
}
function unwrapArgvForMutableOperand(argv) {
let current = argv;
let baseIndex = 0;
while (true) {
const dispatchUnwrap = unwrapKnownDispatchWrapperInvocation(current);
if (dispatchUnwrap.kind === "unwrapped") {
baseIndex += current.length - dispatchUnwrap.argv.length;
current = dispatchUnwrap.argv;
continue;
}
const shellMultiplexerUnwrap = unwrapKnownShellMultiplexerInvocation(current);
if (shellMultiplexerUnwrap.kind === "unwrapped") {
baseIndex += current.length - shellMultiplexerUnwrap.argv.length;
current = shellMultiplexerUnwrap.argv;
continue;
}
const packageManagerUnwrap = unwrapKnownPackageManagerExecInvocation(current);
if (packageManagerUnwrap) {
baseIndex += current.length - packageManagerUnwrap.length;
current = packageManagerUnwrap;
continue;
}
return {
argv: current,
baseIndex
};
}
}
function unwrapKnownPackageManagerExecInvocation(argv) {
switch (normalizePackageManagerExecToken(argv[0] ?? "")) {
case "npm": return unwrapNpmExecInvocation(argv);
case "npx":
case "bunx": return unwrapDirectPackageExecInvocation(argv);
case "pnpm": return unwrapPnpmExecInvocation(argv);
default: return null;
}
}
function normalizePackageManagerExecToken(token) {
const normalized = normalizeExecutableToken(token);
if (!normalized) return normalized;
return normalized.replace(/\.(?:c|m)?js$/i, "");
}
function unwrapPnpmExecInvocation(argv) {
let idx = 1;
while (idx < argv.length) {
const token = argv[idx]?.trim() ?? "";
if (!token) {
idx += 1;
continue;
}
if (token === "--") {
idx += 1;
continue;
}
if (!token.startsWith("-")) {
if (token === "exec") {
if (idx + 1 >= argv.length) return null;
const tail = argv.slice(idx + 1);
return tail[0] === "--" ? tail.length > 1 ? tail.slice(1) : null : tail;
}
if (token === "node") {
const tail = argv.slice(idx + 1);
return ["node", ...tail[0] === "--" ? tail.slice(1) : tail];
}
return null;
}
const [flag] = token.toLowerCase().split("=", 2);
if (PNPM_OPTIONS_WITH_VALUE.has(flag)) {
idx += token.includes("=") ? 1 : 2;
continue;
}
if (PNPM_FLAG_OPTIONS.has(flag)) {
idx += 1;
continue;
}
return null;
}
return null;
}
function unwrapDirectPackageExecInvocation(argv) {
let idx = 1;
while (idx < argv.length) {
const token = argv[idx]?.trim() ?? "";
if (!token) {
idx += 1;
continue;
}
if (!token.startsWith("-")) return argv.slice(idx);
const [flag] = token.toLowerCase().split("=", 2);
if (flag === "-c" || flag === "--call") return null;
if (NPM_EXEC_OPTIONS_WITH_VALUE.has(flag)) {
idx += token.includes("=") ? 1 : 2;
continue;
}
if (NPM_EXEC_FLAG_OPTIONS.has(flag)) {
idx += 1;
continue;
}
return null;
}
return null;
}
function unwrapNpmExecInvocation(argv) {
let idx = 1;
while (idx < argv.length) {
const token = argv[idx]?.trim() ?? "";
if (!token) {
idx += 1;
continue;
}
if (!token.startsWith("-")) {
if (token !== "exec") return null;
idx += 1;
break;
}
if ((token === "-C" || token === "--prefix" || token === "--userconfig") && !token.includes("=")) {
idx += 2;
continue;
}
idx += 1;
}
if (idx >= argv.length) return null;
const tail = argv.slice(idx);
if (tail[0] === "--") return tail.length > 1 ? tail.slice(1) : null;
return unwrapDirectPackageExecInvocation(["npx", ...tail]);
}
function resolvePosixShellScriptOperandIndex(argv) {
if (resolveInlineCommandMatch(argv, POSIX_INLINE_COMMAND_FLAGS, { allowCombinedC: true }).valueTokenIndex !== null) return null;
let afterDoubleDash = false;
for (let i = 1; i < argv.length; i += 1) {
const token = argv[i]?.trim() ?? "";
if (!token) continue;
if (token === "-") return null;
if (!afterDoubleDash && token === "--") {
afterDoubleDash = true;
continue;
}
if (!afterDoubleDash && token === "-s") return null;
if (!afterDoubleDash && token.startsWith("-")) {
const [flag] = token.toLowerCase().split("=", 2);
if (POSIX_SHELL_OPTIONS_WITH_VALUE.has(flag)) {
if (!token.includes("=")) i += 1;
continue;
}
continue;
}
return i;
}
return null;
}
function resolveOptionFilteredFileOperandIndex(params) {
let afterDoubleDash = false;
for (let i = params.startIndex; i < params.argv.length; i += 1) {
const token = params.argv[i]?.trim() ?? "";
if (!token) continue;
if (afterDoubleDash) return resolvesToExistingFileSync(token, params.cwd) ? i : null;
if (token === "--") {
afterDoubleDash = true;
continue;
}
if (token === "-") return null;
if (token.startsWith("-")) {
if (!token.includes("=") && params.optionsWithValue?.has(token)) i += 1;
continue;
}
return resolvesToExistingFileSync(token, params.cwd) ? i : null;
}
return null;
}
function resolveOptionFilteredPositionalIndex(params) {
let afterDoubleDash = false;
for (let i = params.startIndex; i < params.argv.length; i += 1) {
const token = params.argv[i]?.trim() ?? "";
if (!token) continue;
if (afterDoubleDash) return i;
if (token === "--") {
afterDoubleDash = true;
continue;
}
if (token === "-") return null;
if (token.startsWith("-")) {
if (!token.includes("=") && params.optionsWithValue?.has(token)) i += 1;
continue;
}
return i;
}
return null;
}
function collectExistingFileOperandIndexes(params) {
let afterDoubleDash = false;
const hits = [];
for (let i = params.startIndex; i < params.argv.length; i += 1) {
const token = params.argv[i]?.trim() ?? "";
if (!token) continue;
if (afterDoubleDash) {
if (resolvesToExistingFileSync(token, params.cwd)) hits.push(i);
continue;
}
if (token === "--") {
afterDoubleDash = true;
continue;
}
if (token === "-") return {
hits: [],
sawOptionValueFile: false
};
if (token.startsWith("-")) {
const [flag, inlineValue] = token.split("=", 2);
if (params.optionsWithFileValue?.has(flag.toLowerCase())) {
if (inlineValue && resolvesToExistingFileSync(inlineValue, params.cwd)) {
hits.push(i);
return {
hits,
sawOptionValueFile: true
};
}
const nextToken = params.argv[i + 1]?.trim() ?? "";
if (!inlineValue && nextToken && resolvesToExistingFileSync(nextToken, params.cwd)) {
hits.push(i + 1);
return {
hits,
sawOptionValueFile: true
};
}
}
continue;
}
if (resolvesToExistingFileSync(token, params.cwd)) hits.push(i);
}
return {
hits,
sawOptionValueFile: false
};
}
function resolveGenericInterpreterScriptOperandIndex(params) {
const collection = collectExistingFileOperandIndexes({
argv: params.argv,
startIndex: 1,
cwd: params.cwd,
optionsWithFileValue: params.optionsWithFileValue
});
if (collection.sawOptionValueFile) return null;
return collection.hits.length === 1 ? collection.hits[0] : null;
}
function resolveBunScriptOperandIndex(params) {
const directIndex = resolveOptionFilteredPositionalIndex({
argv: params.argv,
startIndex: 1,
optionsWithValue: BUN_OPTIONS_WITH_VALUE
});
if (directIndex === null) return null;
const directToken = params.argv[directIndex]?.trim() ?? "";
if (directToken === "run") return resolveOptionFilteredFileOperandIndex({
argv: params.argv,
startIndex: directIndex + 1,
cwd: params.cwd,
optionsWithValue: BUN_OPTIONS_WITH_VALUE
});
if (BUN_SUBCOMMANDS.has(directToken)) return null;
if (!looksLikePathToken(directToken)) return null;
return directIndex;
}
function resolveDenoRunScriptOperandIndex(params) {
if ((params.argv[1]?.trim() ?? "") !== "run") return null;
return resolveOptionFilteredFileOperandIndex({
argv: params.argv,
startIndex: 2,
cwd: params.cwd,
optionsWithValue: DENO_RUN_OPTIONS_WITH_VALUE
});
}
function hasRubyUnsafeApprovalFlag(argv) {
let afterDoubleDash = false;
for (let i = 1; i < argv.length; i += 1) {
const token = argv[i]?.trim() ?? "";
if (!token) continue;
if (afterDoubleDash) return false;
if (token === "--") {
afterDoubleDash = true;
continue;
}
if (token === "-I" || token === "-r") return true;
if (token.startsWith("-I") || token.startsWith("-r")) return true;
if (RUBY_UNSAFE_APPROVAL_FLAGS.has(token.toLowerCase())) return true;
}
return false;
}
function hasPerlUnsafeApprovalFlag(argv) {
let afterDoubleDash = false;
for (let i = 1; i < argv.length; i += 1) {
const token = argv[i]?.trim() ?? "";
if (!token) continue;
if (afterDoubleDash) return false;
if (token === "--") {
afterDoubleDash = true;
continue;
}
if (token === "-I" || token === "-M" || token === "-m") return true;
if (token.startsWith("-I") || token.startsWith("-M") || token.startsWith("-m")) return true;
if (PERL_UNSAFE_APPROVAL_FLAGS.has(token)) return true;
}
return false;
}
function isMutableScriptRunner(executable) {
return GENERIC_MUTABLE_SCRIPT_RUNNERS.has(executable) || isInterpreterLikeSafeBin(executable);
}
function resolveMutableFileOperandIndex(argv, cwd) {
const unwrapped = unwrapArgvForMutableOperand(argv);
const executable = normalizeExecutableToken(unwrapped.argv[0] ?? "");
if (!executable) return null;
if (POSIX_SHELL_WRAPPERS.has(executable)) {
const shellIndex = resolvePosixShellScriptOperandIndex(unwrapped.argv);
return shellIndex === null ? null : unwrapped.baseIndex + shellIndex;
}
if (MUTABLE_ARGV1_INTERPRETER_PATTERNS.some((pattern) => pattern.test(executable))) {
const operand = unwrapped.argv[1]?.trim() ?? "";
if (operand && operand !== "-" && !operand.startsWith("-")) return unwrapped.baseIndex + 1;
}
if (executable === "bun") {
const bunIndex = resolveBunScriptOperandIndex({
argv: unwrapped.argv,
cwd
});
if (bunIndex !== null) return unwrapped.baseIndex + bunIndex;
}
if (executable === "deno") {
const denoIndex = resolveDenoRunScriptOperandIndex({
argv: unwrapped.argv,
cwd
});
if (denoIndex !== null) return unwrapped.baseIndex + denoIndex;
}
if (executable === "ruby" && hasRubyUnsafeApprovalFlag(unwrapped.argv)) return null;
if (executable === "perl" && hasPerlUnsafeApprovalFlag(unwrapped.argv)) return null;
if (!isMutableScriptRunner(executable)) return null;
const genericIndex = resolveGenericInterpreterScriptOperandIndex({
argv: unwrapped.argv,
cwd,
optionsWithFileValue: executable === "node" || executable === "nodejs" ? NODE_OPTIONS_WITH_FILE_VALUE : void 0
});
return genericIndex === null ? null : unwrapped.baseIndex + genericIndex;
}
function shellPayloadNeedsStableBinding(shellCommand, cwd) {
const argv = splitShellArgs(shellCommand);
if (!argv || argv.length === 0) return false;
const snapshot = resolveMutableFileOperandSnapshotSync({
argv,
cwd,
shellCommand: null
});
if (!snapshot.ok) return true;
if (snapshot.snapshot) return true;
return resolvesToExistingFileSync(argv[0]?.trim() ?? "", cwd);
}
function requiresStableInterpreterApprovalBindingWithShellCommand(params) {
if (params.shellCommand !== null) return shellPayloadNeedsStableBinding(params.shellCommand, params.cwd);
const executable = normalizeExecutableToken(unwrapArgvForMutableOperand(params.argv).argv[0] ?? "");
if (!executable) return false;
if (POSIX_SHELL_WRAPPERS.has(executable)) return false;
return isMutableScriptRunner(executable);
}
function resolveMutableFileOperandSnapshotSync(params) {
const argvIndex = resolveMutableFileOperandIndex(params.argv, params.cwd);
if (argvIndex === null) {
if (requiresStableInterpreterApprovalBindingWithShellCommand({
argv: params.argv,
shellCommand: params.shellCommand,
cwd: params.cwd
})) return {
ok: false,
message: "SYSTEM_RUN_DENIED: approval cannot safely bind this interpreter/runtime command"
};
return {
ok: true,
snapshot: null
};
}
const rawOperand = params.argv[argvIndex]?.trim();
if (!rawOperand) return {
ok: false,
message: "SYSTEM_RUN_DENIED: approval requires a stable script operand"
};
const resolvedPath = path.resolve(params.cwd ?? process.cwd(), rawOperand);
let realPath;
let stat;
try {
realPath = fs.realpathSync(resolvedPath);
stat = fs.statSync(realPath);
} catch {
return {
ok: false,
message: "SYSTEM_RUN_DENIED: approval requires an existing script operand"
};
}
if (!stat.isFile()) return {
ok: false,
message: "SYSTEM_RUN_DENIED: approval requires a file script operand"
};
return {
ok: true,
snapshot: {
argvIndex,
path: realPath,
sha256: hashFileContentsSync(realPath)
}
};
}
function resolveCanonicalApprovalCwdSync(cwd) {
const requestedCwd = path.resolve(cwd);
let cwdLstat;
let cwdStat;
let cwdReal;
let cwdRealStat;
try {
cwdLstat = fs.lstatSync(requestedCwd);
cwdStat = fs.statSync(requestedCwd);
cwdReal = fs.realpathSync(requestedCwd);
cwdRealStat = fs.statSync(cwdReal);
} catch {
return {
ok: false,
message: "SYSTEM_RUN_DENIED: approval requires an existing canonical cwd"
};
}
if (!cwdStat.isDirectory()) return {
ok: false,
message: "SYSTEM_RUN_DENIED: approval requires cwd to be a directory"
};
if (hasMutableSymlinkPathComponentSync(requestedCwd)) return {
ok: false,
message: "SYSTEM_RUN_DENIED: approval requires canonical cwd (no symlink path components)"
};
if (cwdLstat.isSymbolicLink()) return {
ok: false,
message: "SYSTEM_RUN_DENIED: approval requires canonical cwd (no symlink cwd)"
};
if (!sameFileIdentity(cwdStat, cwdLstat) || !sameFileIdentity(cwdStat, cwdRealStat) || !sameFileIdentity(cwdLstat, cwdRealStat)) return {
ok: false,
message: "SYSTEM_RUN_DENIED: approval cwd identity mismatch"
};
return {
ok: true,
snapshot: {
cwd: cwdReal,
stat: cwdStat
}
};
}
function revalidateApprovedCwdSnapshot(params) {
const current = resolveCanonicalApprovalCwdSync(params.snapshot.cwd);
if (!current.ok) return false;
return sameFileIdentity(params.snapshot.stat, current.snapshot.stat);
}
function revalidateApprovedMutableFileOperand(params) {
const operand = params.argv[params.snapshot.argvIndex]?.trim();
if (!operand) return false;
const resolvedPath = path.resolve(params.cwd ?? process.cwd(), operand);
let realPath;
try {
realPath = fs.realpathSync(resolvedPath);
} catch {
return false;
}
if (realPath !== params.snapshot.path) return false;
try {
return hashFileContentsSync(realPath) === params.snapshot.sha256;
} catch {
return false;
}
}
function hardenApprovedExecutionPaths(params) {
if (!params.approvedByAsk) return {
ok: true,
argv: params.argv,
argvChanged: false,
cwd: params.cwd,
approvedCwdSnapshot: void 0
};
let hardenedCwd = params.cwd;
let approvedCwdSnapshot;
if (hardenedCwd) {
const canonicalCwd = resolveCanonicalApprovalCwdSync(hardenedCwd);
if (!canonicalCwd.ok) return canonicalCwd;
hardenedCwd = canonicalCwd.snapshot.cwd;
approvedCwdSnapshot = canonicalCwd.snapshot;
}
if (params.argv.length === 0) return {
ok: true,
argv: params.argv,
argvChanged: false,
cwd: hardenedCwd,
approvedCwdSnapshot
};
const resolution = resolveCommandResolutionFromArgv(params.argv, hardenedCwd);
if (!shouldPinExecutableForApproval({
shellCommand: params.shellCommand,
wrapperChain: resolution?.wrapperChain
})) return {
ok: true,
argv: params.argv,
argvChanged: false,
cwd: hardenedCwd,
approvedCwdSnapshot
};
const pinnedExecutable = resolution?.execution.resolvedRealPath ?? resolution?.execution.resolvedPath;
if (!pinnedExecutable) return {
ok: false,
message: "SYSTEM_RUN_DENIED: approval requires a stable executable path"
};
if (pinnedExecutable === params.argv[0]) return {
ok: true,
argv: params.argv,
argvChanged: false,
cwd: hardenedCwd,
approvedCwdSnapshot
};
const argv = [...params.argv];
argv[0] = pinnedExecutable;
return {
ok: true,
argv,
argvChanged: true,
cwd: hardenedCwd,
approvedCwdSnapshot
};
}
function buildSystemRunApprovalPlan(params) {
const command = resolveSystemRunCommandRequest({
command: params.command,
rawCommand: params.rawCommand
});
if (!command.ok) return {
ok: false,
message: command.message
};
if (command.argv.length === 0) return {
ok: false,
message: "command required"
};
const hardening = hardenApprovedExecutionPaths({
approvedByAsk: true,
argv: command.argv,
shellCommand: command.shellPayload,
cwd: normalizeString(params.cwd) ?? void 0
});
if (!hardening.ok) return {
ok: false,
message: hardening.message
};
const commandText = formatExecCommand(hardening.argv);
const commandPreview = command.previewText?.trim() && command.previewText.trim() !== commandText ? command.previewText.trim() : null;
const mutableFileOperand = resolveMutableFileOperandSnapshotSync({
argv: hardening.argv,
cwd: hardening.cwd,
shellCommand: command.shellPayload
});
if (!mutableFileOperand.ok) return {
ok: false,
message: mutableFileOperand.message
};
return {
ok: true,
plan: {
argv: hardening.argv,
cwd: hardening.cwd ?? null,
commandText,
commandPreview,
agentId: normalizeString(params.agentId),
sessionKey: normalizeString(params.sessionKey),
mutableFileOperand: mutableFileOperand.snapshot ?? void 0
}
};
}
//#endregion
//#region src/node-host/invoke-system-run.ts
const safeBinTrustedDirWarningCache = /* @__PURE__ */ new Set();
const APPROVAL_CWD_DRIFT_DENIED_MESSAGE = "SYSTEM_RUN_DENIED: approval cwd changed before execution";
const APPROVAL_SCRIPT_OPERAND_BINDING_DENIED_MESSAGE = "SYSTEM_RUN_DENIED: approval missing script operand binding";
const APPROVAL_SCRIPT_OPERAND_DRIFT_DENIED_MESSAGE = "SYSTEM_RUN_DENIED: approval script operand changed before execution";
function warnWritableTrustedDirOnce(message) {
if (safeBinTrustedDirWarningCache.has(message)) return;
safeBinTrustedDirWarningCache.add(message);
logWarn(message);
}
function normalizeDeniedReason(reason) {
switch (reason) {
case "security=deny":
case "approval-required":
case "allowlist-miss":
case "execution-plan-miss":
case "companion-unavailable":
case "permission:screenRecording": return reason;
default: return "approval-required";
}
}
async function sendSystemRunDenied(opts, execution, params) {
await opts.sendNodeEvent(opts.client, "exec.denied", opts.buildExecEventPayload({
sessionKey: execution.sessionKey,
runId: execution.runId,
host: "node",
command: execution.commandText,
reason: params.reason,
suppressNotifyOnExit: execution.suppressNotifyOnExit
}));
await opts.sendInvokeResult({
ok: false,
error: {
code: "UNAVAILABLE",
message: params.message
}
});
}
async function sendSystemRunCompleted(opts, execution, result, payloadJSON) {
await opts.sendExecFinishedEvent({
sessionKey: execution.sessionKey,
runId: execution.runId,
commandText: execution.commandText,
result,
suppressNotifyOnExit: execution.suppressNotifyOnExit
});
await opts.sendInvokeResult({
ok: true,
payloadJSON
});
}
async function parseSystemRunPhase(opts) {
const command = resolveSystemRunCommandRequest({
command: opts.params.command,
rawCommand: opts.params.rawCommand
});
if (!command.ok) {
await opts.sendInvokeResult({
ok: false,
error: {
code: "INVALID_REQUEST",
message: command.message
}
});
return null;
}
if (command.argv.length === 0) {
await opts.sendInvokeResult({
ok: false,
error: {
code: "INVALID_REQUEST",
message: "command required"
}
});
return null;
}
const shellPayload = command.shellPayload;
const commandText = command.commandText;
const approvalPlan = opts.params.systemRunPlan === void 0 ? null : normalizeSystemRunApprovalPlan(opts.params.systemRunPlan);
if (opts.params.systemRunPlan !== void 0 && !approvalPlan) {
await opts.sendInvokeResult({
ok: false,
error: {
code: "INVALID_REQUEST",
message: "systemRunPlan invalid"
}
});
return null;
}
const agentId = opts.params.agentId?.trim() || void 0;
const sessionKey = opts.params.sessionKey?.trim() || "node";
const runId = opts.params.runId?.trim() || crypto.randomUUID();
const suppressNotifyOnExit = opts.params.suppressNotifyOnExit === true;
const envOverrideDiagnostics = inspectHostExecEnvOverrides({
overrides: opts.params.env ?? void 0,
blockPathOverrides: true
});
if (envOverrideDiagnostics.rejectedOverrideBlockedKeys.length > 0 || envOverrideDiagnostics.rejectedOverrideInvalidKeys.length > 0) {
const details = [];
if (envOverrideDiagnostics.rejectedOverrideBlockedKeys.length > 0) details.push(`blocked override keys: ${envOverrideDiagnostics.rejectedOverrideBlockedKeys.join(", ")}`);
if (envOverrideDiagnostics.rejectedOverrideInvalidKeys.length > 0) details.push(`invalid non-portable override keys: ${envOverrideDiagnostics.rejectedOverrideInvalidKeys.join(", ")}`);
await opts.sendInvokeResult({
ok: false,
error: {
code: "INVALID_REQUEST",
message: `SYSTEM_RUN_DENIED: environment override rejected (${details.join("; ")})`
}
});
return null;
}
const envOverrides = sanitizeSystemRunEnvOverrides({
overrides: opts.params.env ?? void 0,
shellWrapper: shellPayload !== null
});
return {
argv: command.argv,
shellPayload,
commandText,
commandPreview: command.previewText,
approvalPlan,
agentId,
sessionKey,
runId,
execution: {
sessionKey,
runId,
commandText,
suppressNotifyOnExit
},
approvalDecision: resolveExecApprovalDecision(opts.params.approvalDecision),
envOverrides,
env: opts.sanitizeEnv(envOverrides),
cwd: opts.params.cwd?.trim() || void 0,
timeoutMs: opts.params.timeoutMs ?? void 0,
needsScreenRecording: opts.params.needsScreenRecording === true,
approved: opts.params.approved === true,
suppressNotifyOnExit
};
}
async function evaluateSystemRunPolicyPhase(opts, parsed) {
const cfg = loadConfig();
const agentExec = parsed.agentId ? resolveAgentConfig(cfg, parsed.agentId)?.tools?.exec : void 0;
const configuredSecurity = opts.resolveExecSecurity(agentExec?.security ?? cfg.tools?.exec?.security);
const configuredAsk = opts.resolveExecAsk(agentExec?.ask ?? cfg.tools?.exec?.ask);
const approvals = resolveExecApprovals(parsed.agentId, {
security: configuredSecurity,
ask: configuredAsk
});
const security = approvals.agent.security;
const ask = approvals.agent.ask;
const autoAllowSkills = approvals.agent.autoAllowSkills;
const { safeBins, safeBinProfiles, trustedSafeBinDirs } = resolveExecSafeBinRuntimePolicy({
global: cfg.tools?.exec,
local: agentExec,
onWarning: warnWritableTrustedDirOnce
});
const bins = autoAllowSkills ? await opts.skillBins.current() : [];
let { analysisOk, allowlistMatches, allowlistSatisfied, segments } = evaluateSystemRunAllowlist({
shellCommand: parsed.shellPayload,
argv: parsed.argv,
approvals,
security,
safeBins,
safeBinProfiles,
trustedSafeBinDirs,
cwd: parsed.cwd,
env: parsed.env,
skillBins: bins,
autoAllowSkills
});
const inlineEvalHit = agentExec?.strictInlineEval === true || cfg.tools?.exec?.strictInlineEval === true ? segments.map((segment) => detectInterpreterInlineEvalArgv(segment.resolution?.effectiveArgv ?? segment.argv)).find((entry) => entry !== null) ?? null : null;
const isWindows = process.platform === "win32";
const cmdInvocation = parsed.shellPayload ? opts.isCmdExeInvocation(segments[0]?.argv ?? []) : opts.isCmdExeInvocation(parsed.argv);
const policy = evaluateSystemRunPolicy({
security,
ask,
analysisOk,
allowlistSatisfied,
approvalDecision: parsed.approvalDecision,
approved: parsed.approved,
isWindows,
cmdInvocation,
shellWrapperInvocation: parsed.shellPayload !== null
});
analysisOk = policy.analysisOk;
allowlistSatisfied = policy.allowlistSatisfied;
if (!policy.allowed) {
await sendSystemRunDenied(opts, parsed.execution, {
reason: policy.eventReason,
message: policy.errorMessage
});
return null;
}
if (inlineEvalHit && !policy.approvedByAsk) {
await sendSystemRunDenied(opts, parsed.execution, {
reason: "approval-required",
message: `SYSTEM_RUN_DENIED: approval required (${describeInterpreterInlineEval(inlineEvalHit)} requires explicit approval in strictInlineEval mode)`
});
return null;
}
if (security === "allowlist" && parsed.shellPayload && !policy.approvedByAsk) {
await sendSystemRunDenied(opts, parsed.execution, {
reason: "approval-required",
message: "SYSTEM_RUN_DENIED: approval required"
});
return null;
}
const hardenedPaths = hardenApprovedExecutionPaths({
approvedByAsk: policy.approvedByAsk,
argv: parsed.argv,
shellCommand: parsed.shellPayload,
cwd: parsed.cwd
});
if (!hardenedPaths.ok) {
await sendSystemRunDenied(opts, parsed.execution, {
reason: "approval-required",
message: hardenedPaths.message
});
return null;
}
const approvedCwdSnapshot = policy.approvedByAsk ? hardenedPaths.approvedCwdSnapshot : void 0;
if (policy.approvedByAsk && hardenedPaths.cwd && !approvedCwdSnapshot) {
await sendSystemRunDenied(opts, parsed.execution, {
reason: "approval-required",
message: APPROVAL_CWD_DRIFT_DENIED_MESSAGE
});
return null;
}
const plannedAllowlistArgv = resolvePlannedAllowlistArgv({
security,
shellCommand: parsed.shellPayload,
policy,
segments
});
if (plannedAllowlistArgv === null) {
await sendSystemRunDenied(opts, parsed.execution, {
reason: "execution-plan-miss",
message: "SYSTEM_RUN_DENIED: execution plan mismatch"
});
return null;
}
return {
...parsed,
argv: hardenedPaths.argv,
cwd: hardenedPaths.cwd,
approvals,
security,
policy,
inlineEvalHit,
allowlistMatches,
analysisOk,
allowlistSatisfied,
segments,
plannedAllowlistArgv: plannedAllowlistArgv ?? void 0,
isWindows,
approvedCwdSnapshot
};
}
async function executeSystemRunPhase(opts, phase) {
if (phase.approvedCwdSnapshot && !revalidateApprovedCwdSnapshot({ snapshot: phase.approvedCwdSnapshot })) {
logWarn(`security: system.run approval cwd drift blocked (runId=${phase.runId})`);
await sendSystemRunDenied(opts, phase.execution, {
reason: "approval-required",
message: APPROVAL_CWD_DRIFT_DENIED_MESSAGE
});
return;
}
const expectedMutableFileOperand = phase.approvalPlan ? resolveMutableFileOperandSnapshotSync({
argv: phase.argv,
cwd: phase.cwd,
shellCommand: phase.shellPayload
}) : null;
if (expectedMutableFileOperand && !expectedMutableFileOperand.ok) {
logWarn(`security: system.run approval script binding blocked (runId=${phase.runId})`);
await sendSystemRunDenied(opts, phase.execution, {
reason: "approval-required",
message: expectedMutableFileOperand.message
});
return;
}
if (expectedMutableFileOperand?.snapshot && !phase.approvalPlan?.mutableFileOperand) {
logWarn(`security: system.run approval script binding missing (runId=${phase.runId})`);
await sendSystemRunDenied(opts, phase.execution, {
reason: "approval-required",
message: APPROVAL_SCRIPT_OPERAND_BINDING_DENIED_MESSAGE
});
return;
}
if (phase.approvalPlan?.mutableFileOperand && !revalidateApprovedMutableFileOperand({
snapshot: phase.approvalPlan.mutableFileOperand,
argv: phase.argv,
cwd: phase.cwd
})) {
logWarn(`security: system.run approval script drift blocked (runId=${phase.runId})`);
await sendSystemRunDenied(opts, phase.execution, {
reason: "approval-required",
message: APPROVAL_SCRIPT_OPERAND_DRIFT_DENIED_MESSAGE
});
return;
}
if (opts.preferMacAppExecHost) {
const execRequest = {
command: phase.plannedAllowlistArgv ?? phase.argv,
rawCommand: phase.commandText || null,
cwd: phase.cwd ?? null,
env: phase.envOverrides ?? null,
timeoutMs: phase.timeoutMs ?? null,
needsScreenRecording: phase.needsScreenRecording,
agentId: phase.agentId ?? null,
sessionKey: phase.sessionKey ?? null,
approvalDecision: phase.approvalDecision
};
const response = await opts.runViaMacAppExecHost({
approvals: phase.approvals,
request: execRequest
});
if (!response) {
if (opts.execHostEnforced || !opts.execHostFallbackAllowed) {
await sendSystemRunDenied(opts, phase.execution, {
reason: "companion-unavailable",
message: "COMPANION_APP_UNAVAILABLE: macOS app exec host unreachable"
});
return;
}
} else if (!response.ok) {
await sendSystemRunDenied(opts, phase.execution, {
reason: normalizeDeniedReason(response.error.reason),
message: response.error.message
});
return;
} else {
const result = response.payload;
await sendSystemRunCompleted(opts, phase.execution, result, JSON.stringify(result));
return;
}
}
if (phase.policy.approvalDecision === "allow-always" && phase.security === "allowlist" && phase.inlineEvalHit === null) {
if (phase.policy.analysisOk) {
const patterns = resolveAllowAlwaysPatterns({
segments: phase.segments,
cwd: phase.cwd,
env: phase.env,
platform: process.platform
});
for (const pattern of patterns) if (pattern) addAllowlistEntry(phase.approvals.file, phase.agentId, pattern);
}
}
if (phase.allowlistMatches.length > 0) {
const seen = /* @__PURE__ */ new Set();
for (const match of phase.allowlistMatches) {
if (!match?.pattern || seen.has(match.pattern)) continue;
seen.add(match.pattern);
recordAllowlistUse(phase.approvals.file, phase.agentId, match, phase.commandText, resolveApprovalAuditCandidatePath(phase.segments[0]?.resolution ?? null, phase.cwd));
}
}
if (phase.needsScreenRecording) {
await sendSystemRunDenied(opts, phase.execution, {
reason: "permission:screenRecording",
message: "PERMISSION_MISSING: screenRecording"
});
return;
}
const execArgv = resolveSystemRunExecArgv({
plannedAllowlistArgv: phase.plannedAllowlistArgv,
argv: phase.argv,
security: phase.security,
isWindows: phase.isWindows,
policy: phase.policy,
shellCommand: phase.shellPayload,
segments: phase.segments
});
const result = await opts.runCommand(execArgv, phase.cwd, phase.env, phase.timeoutMs);
applyOutputTruncation(result);
await sendSystemRunCompleted(opts, phase.execution, result, JSON.stringify({
exitCode: result.exitCode,
timedOut: result.timedOut,
success: result.success,
stdout: result.stdout,
stderr: result.stderr,
error: result.error ?? null
}));
}
async function handleSystemRunInvoke(opts) {
const parsed = await parseSystemRunPhase(opts);
if (!parsed) return;
const policyPhase = await evaluateSystemRunPolicyPhase(opts, parsed);
if (!policyPhase) return;
await executeSystemRunPhase(opts, policyPhase);
}
//#endregion
//#region src/node-host/invoke.ts
const OUTPUT_CAP = 2e5;
const OUTPUT_EVENT_TAIL = 2e4;
const DEFAULT_NODE_PATH$1 = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
const WINDOWS_CODEPAGE_ENCODING_MAP = {
65001: "utf-8",
54936: "gb18030",
936: "gbk",
950: "big5",
932: "shift_jis",
949: "euc-kr",
1252: "windows-1252"
};
let cachedWindowsConsoleEncoding;
const execHostEnforced = process.env.OPENCLAW_NODE_EXEC_HOST?.trim().toLowerCase() === "app";
const execHostFallbackAllowed = process.env.OPENCLAW_NODE_EXEC_FALLBACK?.trim().toLowerCase() !== "0";
const preferMacAppExecHost = process.platform === "darwin" && execHostEnforced;
function resolveExecSecurity(value) {
return value === "deny" || value === "allowlist" || value === "full" ? value : "allowlist";
}
function isCmdExeInvocation(argv) {
const token = argv[0]?.trim();
if (!token) return false;
const base = path.win32.basename(token).toLowerCase();
return base === "cmd.exe" || base === "cmd";
}
function resolveExecAsk(value) {
return value === "off" || value === "on-miss" || value === "always" ? value : "on-miss";
}
function sanitizeEnv(overrides) {
return sanitizeHostExecEnv({
overrides,
blockPathOverrides: true
});
}
function truncateOutput(raw, maxChars) {
if (raw.length <= maxChars) return {
text: raw,
truncated: false
};
return {
text: `... (truncated) ${raw.slice(raw.length - maxChars)}`,
truncated: true
};
}
function parseWindowsCodePage(raw) {
if (!raw) return null;
const match = raw.match(/\b(\d{3,5})\b/);
if (!match?.[1]) return null;
const codePage = Number.parseInt(match[1], 10);
if (!Number.isFinite(codePage) || codePage <= 0) return null;
return codePage;
}
function resolveWindowsConsoleEncoding() {
if (process.platform !== "win32") return null;
if (cachedWindowsConsoleEncoding !== void 0) return cachedWindowsConsoleEncoding;
try {
const result = spawnSync("cmd.exe", [
"/d",
"/s",
"/c",
"chcp"
], {
windowsHide: true,
encoding: "utf8",
stdio: [
"ignore",
"pipe",
"pipe"
]
});
const codePage = parseWindowsCodePage(`${result.stdout ?? ""}\n${result.stderr ?? ""}`);
cachedWindowsConsoleEncoding = codePage !== null ? WINDOWS_CODEPAGE_ENCODING_MAP[codePage] ?? null : null;
} catch {
cachedWindowsConsoleEncoding = null;
}
return cachedWindowsConsoleEncoding;
}
function decodeCapturedOutputBuffer(params) {
const utf8 = params.buffer.toString("utf8");
if ((params.platform ?? process.platform) !== "win32") return utf8;
const encoding = params.windowsEncoding ?? resolveWindowsConsoleEncoding();
if (!encoding || encoding.toLowerCase() === "utf-8") return utf8;
try {
return new TextDecoder(encoding).decode(params.buffer);
} catch {
return utf8;
}
}
function redactExecApprovals(file) {
const socketPath = file.socket?.path?.trim();
return {
...file,
socket: socketPath ? { path: socketPath } : void 0
};
}
function requireExecApprovalsBaseHash(params, snapshot) {
if (!snapshot.exists) return;
if (!snapshot.hash) throw new Error("INVALID_REQUEST: exec approvals base hash unavailable; reload and retry");
const baseHash = typeof params.baseHash === "string" ? params.baseHash.trim() : "";
if (!baseHash) throw new Error("INVALID_REQUEST: exec approvals base hash required; reload and retry");
if (baseHash !== snapshot.hash) throw new Error("INVALID_REQUEST: exec approvals changed; reload and retry");
}
async function runCommand(argv, cwd, env, timeoutMs) {
return await new Promise((resolve) => {
const stdoutChunks = [];
const stderrChunks = [];
let outputLen = 0;
let truncated = false;
let timedOut = false;
let settled = false;
const windowsEncoding = resolveWindowsConsoleEncoding();
const child = spawn(argv[0], argv.slice(1), {
cwd,
env,
stdio: [
"ignore",
"pipe",
"pipe"
],
windowsHide: true
});
const onChunk = (chunk, target) => {
if (outputLen >= OUTPUT_CAP) {
truncated = true;
return;
}
const remaining = OUTPUT_CAP - outputLen;
const slice = chunk.length > remaining ? chunk.subarray(0, remaining) : chunk;
outputLen += slice.length;
if (target === "stdout") stdoutChunks.push(slice);
else stderrChunks.push(slice);
if (chunk.length > remaining) truncated = true;
};
child.stdout?.on("data", (chunk) => onChunk(chunk, "stdout"));
child.stderr?.on("data", (chunk) => onChunk(chunk, "stderr"));
let timer;
if (timeoutMs && timeoutMs > 0) timer = setTimeout(() => {
timedOut = true;
try {
child.kill("SIGKILL");
} catch {}
}, timeoutMs);
const finalize = (exitCode, error) => {
if (settled) return;
settled = true;
if (timer) clearTimeout(timer);
const stdout = decodeCapturedOutputBuffer({
buffer: Buffer.concat(stdoutChunks),
windowsEncoding
});
const stderr = decodeCapturedOutputBuffer({
buffer: Buffer.concat(stderrChunks),
windowsEncoding
});
resolve({
exitCode,
timedOut,
success: exitCode === 0 && !timedOut && !error,
stdout,
stderr,
error: error ?? null,
truncated
});
};
child.on("error", (err) => {
finalize(void 0, err.message);
});
child.on("exit", (code) => {
finalize(code === null ? void 0 : code, null);
});
});
}
function resolveEnvPath(env) {
return (env?.PATH ?? env?.Path ?? process.env.PATH ?? process.env.Path ?? DEFAULT_NODE_PATH$1).split(path.delimiter).filter(Boolean);
}
function resolveExecutable(bin, env) {
if (bin.includes("/") || bin.includes("\\")) return null;
const extensions = process.platform === "win32" ? (process.env.PATHEXT ?? process.env.PathExt ?? ".EXE;.CMD;.BAT;.COM").split(";").map((ext) => ext.toLowerCase()) : [""];
for (const dir of resolveEnvPath(env)) for (const ext of extensions) {
const candidate = path.join(dir, bin + ext);
if (fs.existsSync(candidate)) return candidate;
}
return null;
}
async function handleSystemWhich(params, env) {
const bins = params.bins.map((bin) => bin.trim()).filter(Boolean);
const found = {};
for (const bin of bins) {
const path = resolveExecutable(bin, env);
if (path) found[bin] = path;
}
return { bins: found };
}
function buildExecEventPayload(payload) {
if (!payload.output) return payload;
const trimmed = payload.output.trim();
if (!trimmed) return payload;
const { text } = truncateOutput(trimmed, OUTPUT_EVENT_TAIL);
return {
...payload,
output: text
};
}
async function sendExecFinishedEvent(params) {
const combined = [
params.result.stdout,
params.result.stderr,
params.result.error
].filter(Boolean).join("\n");
await sendNodeEvent(params.client, "exec.finished", buildExecEventPayload({
sessionKey: params.sessionKey,
runId: params.runId,
host: "node",
command: params.commandText,
exitCode: params.result.exitCode ?? void 0,
timedOut: params.result.timedOut,
success: params.result.success,
output: combined,
suppressNotifyOnExit: params.suppressNotifyOnExit
}));
}
async function runViaMacAppExecHost(params) {
const { approvals, request } = params;
return await requestExecHostViaSocket({
socketPath: approvals.socketPath,
token: approvals.token,
request
});
}
async function sendJsonPayloadResult(client, frame, payload) {
await sendInvokeResult(client, frame, {
ok: true,
payloadJSON: JSON.stringify(payload)
});
}
async function sendRawPayloadResult(client, frame, payloadJSON) {
await sendInvokeResult(client, frame, {
ok: true,
payloadJSON
});
}
async function sendErrorResult(client, frame, code, message) {
await sendInvokeResult(client, frame, {
ok: false,
error: {
code,
message
}
});
}
async function sendInvalidRequestResult(client, frame, err) {
await sendErrorResult(client, frame, "INVALID_REQUEST", String(err));
}
async function handleInvoke(frame, client, skillBins) {
const command = String(frame.command ?? "");
if (command === "system.execApprovals.get") {
try {
ensureExecApprovals();
const snapshot = readExecApprovalsSnapshot();
await sendJsonPayloadResult(client, frame, {
path: snapshot.path,
exists: snapshot.exists,
hash: snapshot.hash,
file: redactExecApprovals(snapshot.file)
});
} catch (err) {
const message = String(err);
await sendErrorResult(client, frame, message.toLowerCase().includes("timed out") ? "TIMEOUT" : "INVALID_REQUEST", message);
}
return;
}
if (command === "system.execApprovals.set") {
try {
const params = decodeParams(frame.paramsJSON);
if (!params.file || typeof params.file !== "object") throw new Error("INVALID_REQUEST: exec approvals file required");
ensureExecApprovals();
const snapshot = readExecApprovalsSnapshot();
requireExecApprovalsBaseHash(params, snapshot);
saveExecApprovals(mergeExecApprovalsSocketDefaults({
normalized: normalizeExecApprovals(params.file),
current: snapshot.file
}));
const nextSnapshot = readExecApprovalsSnapshot();
await sendJsonPayloadResult(client, frame, {
path: nextSnapshot.path,
exists: nextSnapshot.exists,
hash: nextSnapshot.hash,
file: redactExecApprovals(nextSnapshot.file)
});
} catch (err) {
await sendInvalidRequestResult(client, frame, err);
}
return;
}
if (command === "system.which") {
try {
const params = decodeParams(frame.paramsJSON);
if (!Array.isArray(params.bins)) throw new Error("INVALID_REQUEST: bins required");
await sendJsonPayloadResult(client, frame, await handleSystemWhich(params, sanitizeEnv(void 0)));
} catch (err) {
await sendInvalidRequestResult(client, frame, err);
}
return;
}
if (command === "browser.proxy") {
try {
await sendRawPayloadResult(client, frame, await runBrowserProxyCommand(frame.paramsJSON));
} catch (err) {
await sendInvalidRequestResult(client, frame, err);
}
return;
}
if (command === "system.run.prepare") {
try {
const prepared = buildSystemRunApprovalPlan(decodeParams(frame.paramsJSON));
if (!prepared.ok) {
await sendErrorResult(client, frame, "INVALID_REQUEST", prepared.message);
return;
}
await sendJsonPayloadResult(client, frame, { plan: prepared.plan });
} catch (err) {
await sendInvalidRequestResult(client, frame, err);
}
return;
}
if (command !== "system.run") {
await sendErrorResult(client, frame, "UNAVAILABLE", "command not supported");
return;
}
let params;
try {
params = decodeParams(frame.paramsJSON);
} catch (err) {
await sendInvalidRequestResult(client, frame, err);
return;
}
if (!Array.isArray(params.command) || params.command.length === 0) {
await sendErrorResult(client, frame, "INVALID_REQUEST", "command required");
return;
}
await handleSystemRunInvoke({
client,
params,
skillBins,
execHostEnforced,
execHostFallbackAllowed,
resolveExecSecurity,
resolveExecAsk,
isCmdExeInvocation,
sanitizeEnv,
runCommand,
runViaMacAppExecHost,
sendNodeEvent,
buildExecEventPayload,
sendInvokeResult: async (result) => {
await sendInvokeResult(client, frame, result);
},
sendExecFinishedEvent: async ({ sessionKey, runId, commandText, result }) => {
await sendExecFinishedEvent({
client,
sessionKey,
runId,
commandText,
result
});
},
preferMacAppExecHost
});
}
function decodeParams(raw) {
if (!raw) throw new Error("INVALID_REQUEST: paramsJSON required");
return JSON.parse(raw);
}
function coerceNodeInvokePayload(payload) {
if (!payload || typeof payload !== "object") return null;
const obj = payload;
const id = typeof obj.id === "string" ? obj.id.trim() : "";
const nodeId = typeof obj.nodeId === "string" ? obj.nodeId.trim() : "";
const command = typeof obj.command === "string" ? obj.command.trim() : "";
if (!id || !nodeId || !command) return null;
return {
id,
nodeId,
command,
paramsJSON: typeof obj.paramsJSON === "string" ? obj.paramsJSON : obj.params !== void 0 ? JSON.stringify(obj.params) : null,
timeoutMs: typeof obj.timeoutMs === "number" ? obj.timeoutMs : null,
idempotencyKey: typeof obj.idempotencyKey === "string" ? obj.idempotencyKey : null
};
}
async function sendInvokeResult(client, frame, result) {
try {
await client.request("node.invoke.result", buildNodeInvokeResultParams(frame, result));
} catch {}
}
function buildNodeInvokeResultParams(frame, result) {
const params = {
id: frame.id,
nodeId: frame.nodeId,
ok: result.ok
};
if (result.payload !== void 0) params.payload = result.payload;
if (typeof result.payloadJSON === "string") params.payloadJSON = result.payloadJSON;
if (result.error) params.error = result.error;
return params;
}
async function sendNodeEvent(client, event, payload) {
try {
await client.request("node.event", {
event,
payloadJSON: payload ? JSON.stringify(payload) : null
});
} catch {}
}
//#endregion
//#region src/node-host/runner.ts
const DEFAULT_NODE_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
function resolveExecutablePathFromEnv(bin, pathEnv) {
if (bin.includes("/") || bin.includes("\\")) return null;
return resolveExecutableFromPathEnv(bin, pathEnv) ?? null;
}
function resolveSkillBinTrustEntries(bins, pathEnv) {
const trustEntries = [];
const seen = /* @__PURE__ */ new Set();
for (const bin of bins) {
const name = bin.trim();
if (!name) continue;
const resolvedPath = resolveExecutablePathFromEnv(name, pathEnv);
if (!resolvedPath) continue;
const key = `${name}\u0000${resolvedPath}`;
if (seen.has(key)) continue;
seen.add(key);
trustEntries.push({
name,
resolvedPath
});
}
return trustEntries.toSorted((left, right) => left.name.localeCompare(right.name) || left.resolvedPath.localeCompare(right.resolvedPath));
}
var SkillBinsCache = class {
constructor(fetch, pathEnv) {
this.bins = [];
this.lastRefresh = 0;
this.ttlMs = 9e4;
this.fetch = fetch;
this.pathEnv = pathEnv;
}
async current(force = false) {
if (force || Date.now() - this.lastRefresh > this.ttlMs) await this.refresh();
return this.bins;
}
async refresh() {
try {
this.bins = resolveSkillBinTrustEntries(await this.fetch(), this.pathEnv);
this.lastRefresh = Date.now();
} catch {
if (!this.lastRefresh) this.bins = [];
}
}
};
function ensureNodePathEnv() {
ensureOpenClawCliOnPath({ pathEnv: process.env.PATH ?? "" });
const current = process.env.PATH ?? "";
if (current.trim()) return current;
process.env.PATH = DEFAULT_NODE_PATH;
return DEFAULT_NODE_PATH;
}
async function resolveNodeHostGatewayCredentials(params) {
return await resolveGatewayConnectionAuth({
config: (params.config.gateway?.mode === "remote" ? "remote" : "local") === "local" ? buildNodeHostLocalAuthConfig(params.config) : params.config,
env: params.env,
localTokenPrecedence: "env-first",
localPasswordPrecedence: "env-first",
remoteTokenPrecedence: "env-first",
remotePasswordPrecedence: "env-first"
});
}
function buildNodeHostLocalAuthConfig(config) {
if (!config.gateway?.remote?.token && !config.gateway?.remote?.password) return config;
const nextConfig = structuredClone(config);
if (nextConfig.gateway?.remote) {
nextConfig.gateway.remote.token = void 0;
nextConfig.gateway.remote.password = void 0;
}
return nextConfig;
}
async function runNodeHost(opts) {
const config = await ensureNodeHostConfig();
const nodeId = opts.nodeId?.trim() || config.nodeId;
if (nodeId !== config.nodeId) config.nodeId = nodeId;
const displayName = opts.displayName?.trim() || config.displayName || await getMachineDisplayName();
config.displayName = displayName;
const gateway = {
host: opts.gatewayHost,
port: opts.gatewayPort,
tls: opts.gatewayTls ?? loadConfig().gateway?.tls?.enabled ?? false,
tlsFingerprint: opts.gatewayTlsFingerprint
};
config.gateway = gateway;
await saveNodeHostConfig(config);
const cfg = loadConfig();
const resolvedBrowser = resolveBrowserConfig(cfg.browser, cfg);
const browserProxyEnabled = cfg.nodeHost?.browserProxy?.enabled !== false && resolvedBrowser.enabled;
const { token, password } = await resolveNodeHostGatewayCredentials({
config: cfg,
env: process.env
});
const host = gateway.host ?? "127.0.0.1";
const port = gateway.port ?? 18789;
const url = `${gateway.tls ? "wss" : "ws"}://${host}:${port}`;
const pathEnv = ensureNodePathEnv();
const client = new GatewayClient({
url,
token: token || void 0,
password: password || void 0,
instanceId: nodeId,
clientName: GATEWAY_CLIENT_NAMES.NODE_HOST,
clientDisplayName: displayName,
clientVersion: VERSION,
platform: process.platform,
mode: GATEWAY_CLIENT_MODES.NODE,
role: "node",
scopes: [],
caps: ["system", ...browserProxyEnabled ? ["browser"] : []],
commands: [
...NODE_SYSTEM_RUN_COMMANDS,
...NODE_EXEC_APPROVALS_COMMANDS,
...browserProxyEnabled ? [NODE_BROWSER_PROXY_COMMAND] : []
],
pathEnv,
permissions: void 0,
deviceIdentity: loadOrCreateDeviceIdentity(),
tlsFingerprint: gateway.tlsFingerprint,
onEvent: (evt) => {
if (evt.event !== "node.invoke.request") return;
const payload = coerceNodeInvokePayload(evt.payload);
if (!payload) return;
handleInvoke(payload, client, skillBins);
},
onConnectError: (err) => {
console.error(`node host gateway connect failed: ${err.message}`);
},
onClose: (code, reason) => {
console.error(`node host gateway closed (${code}): ${reason}`);
}
});
const skillBins = new SkillBinsCache(async () => {
const res = await client.request("skills.bins", {});
return Array.isArray(res?.bins) ? res.bins.map((bin) => String(bin)) : [];
}, pathEnv);
client.start();
await new Promise(() => {});
}
//#endregion
//#region src/commands/node-daemon-install-helpers.ts
async function buildNodeInstallPlan(params) {
const { devMode, nodePath } = await resolveDaemonInstallRuntimeInputs({
env: params.env,
runtime: params.runtime,
devMode: params.devMode,
nodePath: params.nodePath
});
const { programArguments, workingDirectory } = await resolveNodeProgramArguments({
host: params.host,
port: params.port,
tls: params.tls,
tlsFingerprint: params.tlsFingerprint,
nodeId: params.nodeId,
displayName: params.displayName,
dev: devMode,
runtime: params.runtime,
nodePath
});
await emitDaemonInstallRuntimeWarning({
env: params.env,
runtime: params.runtime,
programArguments,
warn: params.warn,
title: "Node daemon runtime"
});
const environment = buildNodeServiceEnvironment({
env: params.env,
extraPathDirs: resolveDaemonNodeBinDir(nodePath)
});
return {
programArguments,
workingDirectory,
environment,
description: formatNodeServiceDescription({ version: environment.OPENCLAW_SERVICE_VERSION })
};
}
//#endregion
//#region src/commands/node-daemon-runtime.ts
const DEFAULT_NODE_DAEMON_RUNTIME = DEFAULT_GATEWAY_DAEMON_RUNTIME;
function isNodeDaemonRuntime(value) {
return isGatewayDaemonRuntime(value);
}
//#endregion
//#region src/cli/node-cli/daemon.ts
function renderNodeServiceStartHints() {
return buildPlatformServiceStartHints({
installCommand: formatCliCommand("openclaw node install"),
startCommand: formatCliCommand("openclaw node start"),
launchAgentPlistPath: `~/Library/LaunchAgents/${resolveNodeLaunchAgentLabel()}.plist`,
systemdServiceName: resolveNodeSystemdServiceName(),
windowsTaskName: resolveNodeWindowsTaskName()
});
}
function buildNodeRuntimeHints(env = process.env) {
return buildPlatformRuntimeLogHints({
env,
systemdServiceName: resolveNodeSystemdServiceName(),
windowsTaskName: resolveNodeWindowsTaskName()
});
}
function resolveNodeDefaults(opts, config) {
const host = opts.host?.trim() || config?.gateway?.host || "127.0.0.1";
const portOverride = parsePort(opts.port);
if (opts.port !== void 0 && portOverride === null) return {
host,
port: null
};
return {
host,
port: portOverride ?? config?.gateway?.port ?? 18789
};
}
async function runNodeDaemonInstall(opts) {
const { json, stdout, warnings, emit, fail } = createDaemonInstallActionContext(opts.json);
if (failIfNixDaemonInstallMode(fail)) return;
const config = await loadNodeHostConfig();
const { host, port } = resolveNodeDefaults(opts, config);
if (!Number.isFinite(port ?? NaN) || (port ?? 0) <= 0) {
fail("Invalid port");
return;
}
const runtimeRaw = opts.runtime ? String(opts.runtime) : DEFAULT_NODE_DAEMON_RUNTIME;
if (!isNodeDaemonRuntime(runtimeRaw)) {
fail("Invalid --runtime (use \"node\" or \"bun\")");
return;
}
const service = resolveNodeService();
let loaded = false;
try {
loaded = await service.isLoaded({ env: process.env });
} catch (err) {
fail(`Node service check failed: ${String(err)}`);
return;
}
if (loaded && !opts.force) {
emit({
ok: true,
result: "already-installed",
message: `Node service already ${service.loadedText}.`,
service: buildDaemonServiceSnapshot(service, loaded),
warnings: warnings.length ? warnings : void 0
});
if (!json) {
defaultRuntime.log(`Node service already ${service.loadedText}.`);
defaultRuntime.log(`Reinstall with: ${formatCliCommand("openclaw node install --force")}`);
}
return;
}
const tlsFingerprint = opts.tlsFingerprint?.trim() || config?.gateway?.tlsFingerprint;
const tls = Boolean(opts.tls) || Boolean(tlsFingerprint) || Boolean(config?.gateway?.tls);
const { programArguments, workingDirectory, environment, description } = await buildNodeInstallPlan({
env: process.env,
host,
port: port ?? 18789,
tls,
tlsFingerprint: tlsFingerprint || void 0,
nodeId: opts.nodeId,
displayName: opts.displayName,
runtime: runtimeRaw,
warn: (message) => {
if (json) warnings.push(message);
else defaultRuntime.log(message);
}
});
await installDaemonServiceAndEmit({
serviceNoun: "Node",
service,
warnings,
emit,
fail,
install: async () => {
await service.install({
env: process.env,
stdout,
programArguments,
workingDirectory,
environment,
description
});
}
});
}
async function runNodeDaemonUninstall(opts = {}) {
return await runServiceUninstall({
serviceNoun: "Node",
service: resolveNodeService(),
opts,
stopBeforeUninstall: false,
assertNotLoadedAfterUninstall: false
});
}
async function runNodeDaemonRestart(opts = {}) {
await runServiceRestart({
serviceNoun: "Node",
service: resolveNodeService(),
renderStartHints: renderNodeServiceStartHints,
opts
});
}
async function runNodeDaemonStop(opts = {}) {
return await runServiceStop({
serviceNoun: "Node",
service: resolveNodeService(),
opts
});
}
async function runNodeDaemonStatus(opts = {}) {
const json = Boolean(opts.json);
const service = resolveNodeService();
const [loaded, command, runtime] = await Promise.all([
service.isLoaded({ env: process.env }).catch(() => false),
service.readCommand(process.env).catch(() => null),
service.readRuntime(process.env).catch((err) => ({
status: "unknown",
detail: String(err)
}))
]);
const payload = { service: {
...buildDaemonServiceSnapshot(service, loaded),
command,
runtime
} };
if (json) {
defaultRuntime.writeJson(payload);
return;
}
const { rich, label, accent, infoText, okText, warnText, errorText } = createCliStatusTextStyles();
const serviceStatus = loaded ? okText(service.loadedText) : warnText(service.notLoadedText);
defaultRuntime.log(`${label("Service:")} ${accent(service.label)} (${serviceStatus})`);
if (command?.programArguments?.length) defaultRuntime.log(`${label("Command:")} ${infoText(command.programArguments.join(" "))}`);
if (command?.sourcePath) defaultRuntime.log(`${label("Service file:")} ${infoText(command.sourcePath)}`);
if (command?.workingDirectory) defaultRuntime.log(`${label("Working dir:")} ${infoText(command.workingDirectory)}`);
const runtimeLine = formatRuntimeStatus(runtime);
if (runtimeLine) {
const runtimeColor = resolveRuntimeStatusColor(runtime?.status);
defaultRuntime.log(`${label("Runtime:")} ${colorize(rich, runtimeColor, runtimeLine)}`);
}
if (!loaded) {
defaultRuntime.log("");
for (const hint of renderNodeServiceStartHints()) defaultRuntime.log(`${warnText("Start with:")} ${infoText(hint)}`);
return;
}
const baseEnv = {
...process.env,
...command?.environment ?? void 0
};
const hintEnv = {
...baseEnv,
OPENCLAW_LOG_PREFIX: baseEnv.OPENCLAW_LOG_PREFIX ?? "node"
};
if (runtime?.missingUnit) {
defaultRuntime.error(errorText("Service unit not found."));
for (const hint of buildNodeRuntimeHints(hintEnv)) defaultRuntime.error(errorText(hint));
return;
}
if (runtime?.status === "stopped") {
defaultRuntime.error(errorText("Service is loaded but not running."));
for (const hint of buildNodeRuntimeHints(hintEnv)) defaultRuntime.error(errorText(hint));
}
}
//#endregion
//#region src/cli/node-cli/register.ts
function parsePortWithFallback(value, fallback) {
return parsePort(value) ?? fallback;
}
function registerNodeCli(program) {
const node = program.command("node").description("Run and manage the headless node host service").addHelpText("after", () => `\n${theme.heading("Examples:")}\n${formatHelpExamples([
["openclaw node run --host 127.0.0.1 --port 18789", "Run the node host in the foreground."],
["openclaw node status", "Check node host service status."],
["openclaw node install", "Install the node host service."],
["openclaw node restart", "Restart the installed node host service."]
])}\n\n${theme.muted("Docs:")} ${formatDocsLink("/cli/node", "docs.openclaw.ai/cli/node")}\n`);
node.command("run").description("Run the headless node host (foreground)").option("--host <host>", "Gateway host").option("--port <port>", "Gateway port").option("--tls", "Use TLS for the gateway connection", false).option("--tls-fingerprint <sha256>", "Expected TLS certificate fingerprint (sha256)").option("--node-id <id>", "Override node id (clears pairing token)").option("--display-name <name>", "Override node display name").action(async (opts) => {
const existing = await loadNodeHostConfig();
await runNodeHost({
gatewayHost: opts.host?.trim() || existing?.gateway?.host || "127.0.0.1",
gatewayPort: parsePortWithFallback(opts.port, existing?.gateway?.port ?? 18789),
gatewayTls: Boolean(opts.tls) || Boolean(opts.tlsFingerprint),
gatewayTlsFingerprint: opts.tlsFingerprint,
nodeId: opts.nodeId,
displayName: opts.displayName
});
});
node.command("status").description("Show node host status").option("--json", "Output JSON", false).action(async (opts) => {
await runNodeDaemonStatus(opts);
});
node.command("install").description("Install the node host service (launchd/systemd/schtasks)").option("--host <host>", "Gateway host").option("--port <port>", "Gateway port").option("--tls", "Use TLS for the gateway connection", false).option("--tls-fingerprint <sha256>", "Expected TLS certificate fingerprint (sha256)").option("--node-id <id>", "Override node id (clears pairing token)").option("--display-name <name>", "Override node display name").option("--runtime <runtime>", "Service runtime (node|bun). Default: node").option("--force", "Reinstall/overwrite if already installed", false).option("--json", "Output JSON", false).action(async (opts) => {
await runNodeDaemonInstall(opts);
});
node.command("uninstall").description("Uninstall the node host service (launchd/systemd/schtasks)").option("--json", "Output JSON", false).action(async (opts) => {
await runNodeDaemonUninstall(opts);
});
node.command("stop").description("Stop the node host service (launchd/systemd/schtasks)").option("--json", "Output JSON", false).action(async (opts) => {
await runNodeDaemonStop(opts);
});
node.command("restart").description("Restart the node host service (launchd/systemd/schtasks)").option("--json", "Output JSON", false).action(async (opts) => {
await runNodeDaemonRestart(opts);
});
}
//#endregion
export { registerNodeCli };