File size: 36,091 Bytes
fcd8223 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 | /** Node-host command dispatcher for system commands, approvals, env policy, and plugin commands. */
import fs from "node:fs";
import path from "node:path";
import { isRecord } from "@openclaw/normalization-core/record-coerce";
import {
normalizeLowercaseStringOrEmpty,
normalizeOptionalString,
} from "@openclaw/normalization-core/string-coerce";
import { normalizeStringEntries } from "@openclaw/normalization-core/string-normalization";
import { sliceUtf16Safe, truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
import { DEFAULT_ASK, DEFAULT_SECURITY } from "../infra/exec-approvals-config.js";
import {
analyzeArgvCommand,
createExecApprovalPolicySnapshot,
ensureExecApprovalsSnapshot,
mergeExecApprovalsSocketDefaults,
minSecurity,
maxAsk,
normalizeExecApprovals,
readExecApprovalsSnapshot,
redactExecApprovals,
resolveAllowAlwaysPatternCoverage,
resolveExecApprovalsFromFile,
updateExecApprovals,
type ExecAsk,
type ExecApprovalsFile,
type ExecApprovalsResolved,
type ExecSecurity,
} from "../infra/exec-approvals.js";
import { planShellAuthorization } from "../infra/exec-authorization-plan.js";
import {
requestExecHostViaSocket,
type ExecHostRequest,
type ExecHostResponse,
} from "../infra/exec-host.js";
import {
extractShellWrapperCommand,
isShellWrapperInvocation,
} from "../infra/exec-wrapper-resolution.js";
import {
inspectHostExecEnvOverrides,
sanitizeHostExecEnv,
sanitizeSystemRunEnvOverrides,
} from "../infra/host-env-security.js";
import {
NODE_AGENT_CLI_CLAUDE_RUN_COMMAND,
NODE_DEVICE_APPS_COMMAND,
NODE_MCP_TOOLS_CALL_COMMAND,
NODE_WORKER_DESKTOP_COMPUTER_COMMAND,
} from "../infra/node-commands.js";
import { logWarn } from "../logger.js";
import { runCommandWithTimeout } from "../process/exec.js";
import { NODE_DESKTOP_STREAM_COMMAND } from "../shared/node-desktop-stream.js";
import type { NodeHostClient } from "./client.js";
import { invokeNodeWorkerComputerCommand, type NodeWorkerComputer } from "./computer-command.js";
import { invokeNodeDesktopStream } from "./desktop-stream-command.js";
import {
handleClaudeCliNodeInvoke,
type NodeHostInvokeRuntime,
} from "./invoke-agent-cli-claude-handler.js";
import { invokeDeviceApps } from "./invoke-device-apps.js";
import { invokeNodeFileCommand } from "./invoke-file-commands.js";
import { boundMcpToolResultPayload } from "./invoke-mcp-result.js";
import {
buildSystemRunApprovalPlan,
handleSystemRunInvoke,
resolveEffectiveSystemRunExecPolicy,
} from "./invoke-system-run.js";
import type {
ExecEventPayload,
ExecFinishedEventParams,
NodeInvokeRequestPayload,
RunResult,
SkillBinsProvider,
SystemRunParams,
} from "./invoke-types.js";
import { NodeHostMcpError, type NodeHostMcpManager } from "./mcp.js";
import { buildNodeEventParams } from "./node-event-params.js";
import type { NodeWorkerBundleInstallerControl } from "./node-worker-bundle-installer.js";
import { invokeNodeWorkerSupervisorCommand } from "./node-worker-supervisor-commands.js";
import type { NodeWorkerSupervisorControl } from "./node-worker-supervisor-contract.js";
import type { NodeWorkerWorkspaceRuntime } from "./node-worker-workspace.js";
import { invokeRegisteredNodeHostCommand as invokePlugin } from "./plugin-node-host.js";
import { resolveNodeHostedSkillDirectory } from "./skills.js";
const OUTPUT_CAP = 200_000;
const MCP_ERROR_MESSAGE_MAX_CHARS = 1_024;
const OUTPUT_EVENT_TAIL = 20_000;
const DEFAULT_NODE_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
type NodeHostPrivateInvokeRuntime = NodeHostInvokeRuntime & {
canReportAbortedFailure?: (error: unknown) => boolean;
flushPluginCommandIo?: () => Promise<void>;
workerBundleInstaller?: NodeWorkerBundleInstallerControl;
workerSupervisor?: NodeWorkerSupervisorControl;
workerWorkspace?: NodeWorkerWorkspaceRuntime;
workerComputer?: NodeWorkerComputer;
};
const execHostEnforced =
normalizeLowercaseStringOrEmpty(process.env.OPENCLAW_NODE_EXEC_HOST ?? "") === "app";
const execHostFallbackAllowed =
normalizeLowercaseStringOrEmpty(process.env.OPENCLAW_NODE_EXEC_FALLBACK ?? "") !== "0";
const preferMacAppExecHost = process.platform === "darwin" && execHostEnforced;
type SystemWhichParams = {
bins: string[];
};
type McpToolsCallParams = {
server: string;
tool: string;
arguments?: Record<string, unknown>;
};
type SystemExecApprovalsSetParams = {
file: ExecApprovalsFile;
baseHash?: string | null;
};
type SystemRunPrepareParams = {
security?: ExecSecurity;
ask?: ExecAsk;
command?: unknown;
rawCommand?: unknown;
cwd?: unknown;
env?: Record<string, string> | null;
agentId?: unknown;
sessionKey?: unknown;
strictInlineEval?: unknown;
};
type SystemRunPrepareEnv =
| {
ok: true;
env: Record<string, string>;
}
| {
ok: false;
message: string;
};
function resolveNodeSkillCwdParam<T extends { cwd?: unknown }>(params: T, nodeId: string): T {
if (typeof params.cwd !== "string") {
return params;
}
// Resolve before approval planning so the plan, policy, and spawn all bind
// the same canonical node-local directory instead of trusting a URI at exec time.
const resolved = resolveNodeHostedSkillDirectory(params.cwd, nodeId);
return resolved ? { ...params, cwd: resolved } : params;
}
function buildEnvOverrideRejectionMessage(params: {
rejectedOverrideBlockedKeys: string[];
rejectedOverrideInvalidKeys: string[];
}): string {
const details: string[] = [];
if (params.rejectedOverrideBlockedKeys.length > 0) {
details.push(`blocked override keys: ${params.rejectedOverrideBlockedKeys.join(", ")}`);
}
if (params.rejectedOverrideInvalidKeys.length > 0) {
details.push(
`invalid non-portable override keys: ${params.rejectedOverrideInvalidKeys.join(", ")}`,
);
}
return `SYSTEM_RUN_DENIED: environment override rejected (${details.join("; ")})`;
}
function buildSystemRunPrepareCoverageEnv(params: {
argv: string[];
env?: Record<string, string> | null;
}): SystemRunPrepareEnv {
const diagnostics = inspectHostExecEnvOverrides({
overrides: params.env ?? undefined,
blockPathOverrides: true,
});
if (
diagnostics.rejectedOverrideBlockedKeys.length > 0 ||
diagnostics.rejectedOverrideInvalidKeys.length > 0
) {
return {
ok: false,
message: buildEnvOverrideRejectionMessage(diagnostics),
};
}
const envOverrides = sanitizeSystemRunEnvOverrides({
overrides: params.env ?? undefined,
shellWrapper: isShellWrapperInvocation(params.argv),
});
return {
ok: true,
// Prepared coverage is durable approval evidence, so keep this in parity
// with the env passed to `system.run` policy and execution.
env: sanitizeEnv(envOverrides),
};
}
async function buildSystemRunAllowAlwaysCoverage(params: {
argv: string[];
rawCommand?: string | null;
cwd: string | null | undefined;
env: Record<string, string> | undefined;
strictInlineEval?: boolean;
}) {
const cwd = params.cwd ?? undefined;
const shellWrapper = extractShellWrapperCommand(params.argv, params.rawCommand);
if (shellWrapper.isWrapper) {
if (!shellWrapper.command) {
return { complete: false, patterns: [] };
}
const authorizationPlan = await planShellAuthorization({
command: shellWrapper.command,
cwd,
env: params.env,
platform: process.platform,
});
if (!authorizationPlan.ok) {
return { complete: false, patterns: [] };
}
const candidates = authorizationPlan.groups.flatMap((group) => group.candidates);
const reusableSegments = candidates
.filter((candidate) => candidate.allowAlways)
.map((candidate) => candidate.sourceSegment);
const coverage = resolveAllowAlwaysPatternCoverage({
segments: reusableSegments,
cwd,
env: params.env,
platform: process.platform,
strictInlineEval: params.strictInlineEval,
});
return {
...coverage,
complete: coverage.complete && reusableSegments.length === candidates.length,
};
}
const analysis = analyzeArgvCommand({ argv: params.argv, cwd, env: params.env });
if (!analysis.ok) {
return { complete: false, patterns: [] };
}
return resolveAllowAlwaysPatternCoverage({
segments: analysis.segments,
cwd,
env: params.env,
platform: process.platform,
strictInlineEval: params.strictInlineEval,
});
}
type ExecApprovalsSnapshot = {
path: string;
exists: boolean;
hash: string;
file: ExecApprovalsFile;
};
export type { NodeInvokeRequestPayload, SkillBinsProvider } from "./invoke-types.js";
function resolveExecSecurity(value?: string): ExecSecurity {
return value === "deny" || value === "allowlist" || value === "full" ? value : DEFAULT_SECURITY;
}
function isCmdExeInvocation(argv: string[]): boolean {
const token = argv[0]?.trim();
if (!token) {
return false;
}
const base = normalizeLowercaseStringOrEmpty(path.win32.basename(token));
return base === "cmd.exe" || base === "cmd";
}
function resolveExecAsk(value?: string): ExecAsk {
return value === "off" || value === "on-miss" || value === "always" ? value : DEFAULT_ASK;
}
/** Builds a sanitized execution environment with controlled PATH and approved overrides. */
function sanitizeEnv(overrides?: Record<string, string> | null): Record<string, string> {
return sanitizeHostExecEnv({ overrides, blockPathOverrides: true });
}
function truncateOutput(raw: string, maxChars: number): { text: string; truncated: boolean } {
if (raw.length <= maxChars) {
return { text: raw, truncated: false };
}
return { text: `... (truncated) ${sliceUtf16Safe(raw, raw.length - maxChars)}`, truncated: true };
}
function requireExecApprovalsBaseHash(
params: SystemExecApprovalsSetParams,
snapshot: ExecApprovalsSnapshot,
) {
const baseHash = typeof params.baseHash === "string" ? params.baseHash.trim() : "";
if (!snapshot.exists) {
if (baseHash && baseHash !== snapshot.hash) {
throw new Error("INVALID_REQUEST: exec approvals changed; reload and retry");
}
return;
}
if (!snapshot.hash) {
throw new Error("INVALID_REQUEST: exec approvals base hash unavailable; reload and retry");
}
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");
}
}
// libuv reports a failed pre-exec `chdir(cwd)` as `spawn <argv0> ENOENT`, which
// blames the shell/command instead of the missing working directory (#85202).
// When the spawn cwd is set but is not a usable directory, name the real cause.
// Diagnostic only: the run still fails closed — the cwd is never dropped to fall
// back to the node's default directory.
function clarifyNodeExecCwdSpawnError(
error: NodeJS.ErrnoException,
cwd: string | undefined,
): string {
const message = error.message;
if (!cwd || (error.code && error.code !== "ENOENT" && error.code !== "ENOTDIR")) {
return message;
}
let reason: "does not exist" | "is not a directory";
try {
const stats = fs.statSync(cwd);
// An existing directory means the cwd is fine and the ENOENT is about the
// executable itself; leave the original message untouched.
if (stats.isDirectory()) {
return message;
}
reason = "is not a directory";
} catch (statError) {
const statCode = (statError as NodeJS.ErrnoException).code;
if (statCode !== "ENOENT" && statCode !== "ENOTDIR") {
return message;
}
reason =
statCode === "ENOTDIR" || error.code === "ENOTDIR" ? "is not a directory" : "does not exist";
}
return `node exec working directory ${reason} on the node host: ${cwd} (os reported: ${message})`;
}
async function runCommand(
argv: string[],
cwd: string | undefined,
env: Record<string, string> | undefined,
timeoutMs: number | undefined,
signal?: AbortSignal,
assertCurrent?: () => void,
): Promise<RunResult> {
assertCurrent?.();
try {
const result = await runCommandWithTimeout(argv, {
baseEnv: env,
cwd,
killProcessTree: true,
maxCombinedOutputBytes: OUTPUT_CAP,
maxOutputBytes: OUTPUT_CAP,
outputCapture: "head",
input: Buffer.alloc(0),
signal,
timeoutMs: timeoutMs && timeoutMs > 0 ? timeoutMs : undefined,
});
const timedOut = result.termination === "timeout";
const exitCode = result.code ?? undefined;
return {
exitCode,
timedOut,
success: exitCode === 0 && !timedOut,
stdout: result.stdout,
stderr: result.stderr,
error: null,
truncated: Boolean(result.stdoutTruncatedBytes || result.stderrTruncatedBytes),
};
} catch (err) {
return {
exitCode: undefined,
timedOut: false,
success: false,
stdout: "",
stderr: "",
error: clarifyNodeExecCwdSpawnError(err as NodeJS.ErrnoException, cwd),
truncated: false,
};
}
}
function resolveEnvPath(env?: Record<string, string>): string[] {
const raw =
env?.PATH ??
(env as Record<string, string>)?.Path ??
process.env.PATH ??
process.env.Path ??
DEFAULT_NODE_PATH;
return raw.split(path.delimiter).filter(Boolean);
}
function resolveExecutable(bin: string, env?: Record<string, string>) {
if (bin.includes("/") || bin.includes("\\")) {
return null;
}
const extensions =
process.platform === "win32"
? (
env?.PATHEXT ??
env?.PathExt ??
env?.Pathext ??
process.env.PATHEXT ??
process.env.PathExt ??
".EXE;.CMD;.BAT;.COM"
)
.split(";")
.map((ext) => normalizeLowercaseStringOrEmpty(ext))
: [""];
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: SystemWhichParams, env?: Record<string, string>) {
const bins = normalizeStringEntries(params.bins);
const found: Record<string, string> = {};
for (const bin of bins) {
const pathLocal = resolveExecutable(bin, env);
if (pathLocal) {
found[bin] = pathLocal;
}
}
return { bins: found };
}
function buildExecEventPayload(payload: ExecEventPayload): ExecEventPayload {
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: ExecFinishedEventParams & {
client: NodeHostClient;
},
) {
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 ?? undefined,
timedOut: params.result.timedOut,
success: params.result.success,
output: combined,
suppressNotifyOnExit: params.suppressNotifyOnExit,
}),
);
}
async function runViaMacAppExecHost(params: {
approvals: ExecApprovalsResolved;
request: ExecHostRequest;
signal?: AbortSignal;
}): Promise<ExecHostResponse | null> {
const { approvals, request } = params;
return await requestExecHostViaSocket({
socketPath: approvals.socketPath,
token: approvals.token,
request,
signal: params.signal,
});
}
async function sendJsonPayloadResult(
client: NodeHostClient,
frame: NodeInvokeRequestPayload,
payload: unknown,
) {
await sendInvokeResult(client, frame, {
ok: true,
payloadJSON: JSON.stringify(payload),
});
}
async function sendMcpPayloadResult(
client: NodeHostClient,
frame: NodeInvokeRequestPayload,
payload: unknown,
) {
await sendInvokeResult(client, frame, { ok: true, payload });
}
async function sendRawPayloadResult(
client: NodeHostClient,
frame: NodeInvokeRequestPayload,
payloadJSON: string,
) {
await sendInvokeResult(client, frame, {
ok: true,
payloadJSON,
});
}
async function sendErrorResult(
client: NodeHostClient,
frame: NodeInvokeRequestPayload,
code: string,
message: string,
) {
await sendInvokeResult(client, frame, {
ok: false,
error: { code, message },
});
}
async function sendInvalidRequestResult(
client: NodeHostClient,
frame: NodeInvokeRequestPayload,
err: unknown,
) {
await sendErrorResult(client, frame, "INVALID_REQUEST", String(err));
}
function classifyExecApprovalsStorageError(err: unknown): "TIMEOUT" | "UNAVAILABLE" {
const errorCode =
err && typeof err === "object" && "code" in err ? (err as { code?: unknown }).code : null;
return errorCode === "file_lock_timeout" ? "TIMEOUT" : "UNAVAILABLE";
}
async function sendExecApprovalsStorageErrorResult(
client: NodeHostClient,
frame: NodeInvokeRequestPayload,
err: unknown,
) {
await sendErrorResult(client, frame, classifyExecApprovalsStorageError(err), String(err));
}
function createNodeHostInvocationClient(
client: NodeHostClient,
signal: AbortSignal | undefined,
): NodeHostClient {
if (!signal) {
return client;
}
return {
async request<T = Record<string, unknown>>(
method: string,
params?: unknown,
opts?: Parameters<NodeHostClient["request"]>[2],
): Promise<T> {
// Superseded invocations share their replacement's Gateway id, so late
// results, progress, and events must not outlive invocation ownership.
if (
signal.aborted &&
(method === "node.invoke.result" ||
method === "node.invoke.progress" ||
method === "node.event")
) {
return {} as T;
}
return opts === undefined
? await client.request<T>(method, params)
: await client.request<T>(method, params, opts);
},
};
}
/** Handles one node-host command invocation payload and returns serialized results. */
export async function handleInvoke(
frame: NodeInvokeRequestPayload,
client: NodeHostClient,
skillBins: SkillBinsProvider,
mcpManager?: NodeHostMcpManager,
runtime: NodeHostPrivateInvokeRuntime = {},
) {
const invocationClient = createNodeHostInvocationClient(client, runtime.signal);
try {
await dispatchInvoke(frame, invocationClient, client, skillBins, mcpManager, runtime);
} catch (err) {
// Gateway events launch this handler without awaiting it. Consume unexpected
// failures here so one bad request cannot terminate the node-host process.
logWarn(
`node host invoke failed (command=${frame.command ?? "unknown"}, id=${frame.id}): ${String(err)}`,
);
try {
await sendErrorResult(invocationClient, frame, "UNAVAILABLE", "node invocation failed");
} catch (sendErr) {
// The caller intentionally detaches this promise. A failed result send is
// terminal for this request and must not surface as an unhandled rejection.
logWarn(
`node host invoke failure response could not be sent (id=${frame.id}): ${String(sendErr)}`,
);
}
}
}
async function dispatchInvoke(
frame: NodeInvokeRequestPayload,
client: NodeHostClient,
abortedFailureClient: NodeHostClient,
skillBins: SkillBinsProvider,
mcpManager?: NodeHostMcpManager,
runtime: NodeHostPrivateInvokeRuntime = {},
) {
const command = frame.command ?? "";
if (
(command === NODE_WORKER_DESKTOP_COMPUTER_COMMAND && !runtime.workerComputer) ||
(runtime.workerComputer && (command === "screen.snapshot" || command === "computer.act"))
) {
await sendErrorResult(
client,
frame,
"UNAVAILABLE",
"computer command is unavailable on this node transport",
);
return;
}
const workerSupervisorResult = await invokeNodeWorkerSupervisorCommand({
command,
paramsJSON: frame.paramsJSON,
bundleInstaller: runtime.workerBundleInstaller,
supervisor: runtime.workerSupervisor,
workspace: runtime.workerWorkspace,
gatewayUrl: runtime.gatewayUrl,
gatewayTlsFingerprint: runtime.gatewayTlsFingerprint,
gatewayCloudflareAccess: runtime.gatewayCloudflareAccess,
signal: runtime.signal,
});
if (workerSupervisorResult.handled) {
if (workerSupervisorResult.ok) {
await sendJsonPayloadResult(client, frame, workerSupervisorResult.payload);
} else {
await sendErrorResult(
client,
frame,
workerSupervisorResult.code,
workerSupervisorResult.message,
);
}
return;
}
if (command === NODE_DEVICE_APPS_COMMAND) {
const result = await invokeDeviceApps({
paramsJSON: frame.paramsJSON,
sharingEnabled: runtime.installedAppsSharingEnabled === true,
...(runtime.installedAppsPlatform ? { platform: runtime.installedAppsPlatform } : {}),
...(runtime.scanInstalledApps ? { scan: runtime.scanInstalledApps } : {}),
});
if (result.ok) {
await sendJsonPayloadResult(client, frame, result.payload);
} else {
await sendErrorResult(client, frame, result.code, result.message);
}
return;
}
if (command === NODE_DESKTOP_STREAM_COMMAND) {
try {
await invokeNodeDesktopStream({
paramsJSON: frame.paramsJSON,
gatewayUrl: runtime.gatewayUrl,
gatewayTlsFingerprint: runtime.gatewayTlsFingerprint,
gatewayCloudflareAccess: runtime.gatewayCloudflareAccess,
config: runtime.desktopHostConfig,
signal: runtime.signal,
emitStatus: runtime.emitProgress,
});
await sendJsonPayloadResult(client, frame, { status: "closed" });
} catch (error) {
await sendErrorResult(
client,
frame,
"UNAVAILABLE",
error instanceof Error ? error.message : "desktop stream unavailable",
);
}
return;
}
if (command === "system.execApprovals.get") {
let includeResolvedDefaults = false;
try {
if (frame.paramsJSON != null) {
const params = decodeParams<unknown>(frame.paramsJSON);
if (
!isRecord(params) ||
(params.includeResolvedDefaults !== undefined &&
typeof params.includeResolvedDefaults !== "boolean")
) {
throw new Error("INVALID_REQUEST: includeResolvedDefaults must be boolean");
}
includeResolvedDefaults = params.includeResolvedDefaults === true;
}
} catch (err) {
await sendInvalidRequestResult(client, frame, err);
return;
}
try {
const snapshot = await ensureExecApprovalsSnapshot();
const payload = {
...redactExecApprovals(snapshot),
...(includeResolvedDefaults
? { resolvedDefaults: resolveExecApprovalsFromFile({ file: snapshot.file }).defaults }
: {}),
};
await sendJsonPayloadResult(client, frame, payload);
} catch (err) {
await sendExecApprovalsStorageErrorResult(client, frame, err);
}
return;
}
if (command === "system.execApprovals.set") {
let params: SystemExecApprovalsSetParams;
let normalized: ExecApprovalsFile;
try {
params = decodeParams<SystemExecApprovalsSetParams>(frame.paramsJSON);
if (!params.file || typeof params.file !== "object") {
throw new Error("INVALID_REQUEST: exec approvals file required");
}
normalized = normalizeExecApprovals(params.file);
} catch (err) {
await sendInvalidRequestResult(client, frame, err);
return;
}
let snapshot: ExecApprovalsSnapshot;
try {
// A stale save must not initialize state before its base hash is checked.
snapshot = readExecApprovalsSnapshot();
} catch (err) {
await sendExecApprovalsStorageErrorResult(client, frame, err);
return;
}
try {
requireExecApprovalsBaseHash(params, snapshot);
} catch (err) {
await sendInvalidRequestResult(client, frame, err);
return;
}
let nextSnapshot: ExecApprovalsSnapshot | null;
try {
nextSnapshot = await updateExecApprovals({
baseHash: snapshot.hash,
update: (current) => mergeExecApprovalsSocketDefaults({ normalized, current }),
});
} catch (err) {
await sendExecApprovalsStorageErrorResult(client, frame, err);
return;
}
if (!nextSnapshot) {
await sendErrorResult(
client,
frame,
"INVALID_REQUEST",
"INVALID_REQUEST: exec approvals changed; reload and retry",
);
return;
}
const payload: ExecApprovalsSnapshot = redactExecApprovals(nextSnapshot);
await sendJsonPayloadResult(client, frame, payload);
return;
}
if (command === "system.which") {
try {
const params = decodeParams<SystemWhichParams>(frame.paramsJSON);
if (!Array.isArray(params.bins)) {
throw new Error("INVALID_REQUEST: bins required");
}
const env = sanitizeEnv(undefined);
const payload = await handleSystemWhich(params, env);
await sendJsonPayloadResult(client, frame, payload);
} catch (err) {
await sendInvalidRequestResult(client, frame, err);
}
return;
}
const fileCommand = await invokeNodeFileCommand(command, frame.paramsJSON);
if (fileCommand) {
if ("error" in fileCommand) {
await sendInvalidRequestResult(client, frame, fileCommand.error);
} else {
await sendJsonPayloadResult(client, frame, fileCommand.payload);
}
return;
}
if (command === NODE_MCP_TOOLS_CALL_COMMAND) {
await handleMcpToolsCall(frame, client, mcpManager, runtime.signal);
return;
}
if (command === NODE_AGENT_CLI_CLAUDE_RUN_COMMAND) {
await handleClaudeCliNodeInvoke({
frame,
client,
skillBins,
runtime,
deps: {
sendErrorResult,
sendInvalidRequestResult,
sendInvokeResult,
resolveExecSecurity,
resolveExecAsk,
isCmdExeInvocation,
sanitizeEnv,
runViaMacAppExecHost,
buildExecEventPayload,
},
});
return;
}
try {
const { pluginCommandIo: io, pluginCommandContext: context } = runtime;
const acquireManagedWorkspace = context?.acquireManagedWorkspace;
let pluginInvocationActive = true;
const invokeContext =
context && (frame.sessionKey || runtime.signal || acquireManagedWorkspace)
? {
...context,
...(frame.sessionKey ? { sessionKey: frame.sessionKey } : {}),
...(runtime.signal ? { signal: runtime.signal } : {}),
...(acquireManagedWorkspace
? {
acquireManagedWorkspace: (
request: Parameters<typeof acquireManagedWorkspace>[0],
) => {
if (
!pluginInvocationActive ||
runtime.signal?.aborted ||
!frame.sessionKey ||
request.sessionKey !== frame.sessionKey
) {
throw new Error("node placement workspace invocation authority is closed");
}
return acquireManagedWorkspace(request);
},
}
: {}),
}
: context;
let pluginResult: string | null;
try {
pluginResult =
command === NODE_WORKER_DESKTOP_COMPUTER_COMMAND
? await invokeNodeWorkerComputerCommand({
paramsJSON: frame.paramsJSON,
computer: runtime.workerComputer!,
invoke: (innerCommand, paramsJSON) =>
invokePlugin(innerCommand, paramsJSON, undefined, invokeContext),
})
: await invokePlugin(command, frame.paramsJSON, io, invokeContext);
} finally {
pluginInvocationActive = false;
}
if (pluginResult !== null) {
await runtime.flushPluginCommandIo?.();
await sendRawPayloadResult(client, frame, pluginResult);
return;
}
} catch (err) {
// Only the exact current owner's exact framed failure may bypass its aborted-client fence.
const failureClient = runtime.canReportAbortedFailure?.(err) ? abortedFailureClient : client;
await sendInvalidRequestResult(failureClient, frame, err);
return;
}
if (command === "system.run.prepare") {
try {
const params = resolveNodeSkillCwdParam(
decodeParams<SystemRunPrepareParams>(frame.paramsJSON),
frame.nodeId,
);
const { getRuntimeConfig } = await import("../config/config.js");
const execPolicy = await resolveEffectiveSystemRunExecPolicy({
cfg: getRuntimeConfig(),
agentId: normalizeOptionalString(params.agentId),
defaultSecurity: resolveExecSecurity(undefined),
defaultAsk: resolveExecAsk(undefined),
requireSocket: preferMacAppExecHost,
});
// Omitted caller policy retains the approval-preparation contract. A caller can
// narrow local policy, but cannot turn a restrictive node into an ordinary launch.
const bindApproval =
params.security === undefined ||
params.ask === undefined ||
minSecurity(execPolicy.security, resolveExecSecurity(params.security)) !== "full" ||
maxAsk(execPolicy.ask, resolveExecAsk(params.ask)) !== "off" ||
params.strictInlineEval === true ||
execPolicy.agentExec?.strictInlineEval === true ||
execPolicy.globalExec?.strictInlineEval === true;
const prepared = buildSystemRunApprovalPlan(params, bindApproval);
if (!prepared.ok) {
await sendErrorResult(client, frame, "INVALID_REQUEST", prepared.message);
return;
}
const prepareEnv = buildSystemRunPrepareCoverageEnv({
argv: prepared.plan.argv,
env: params.env ?? undefined,
});
if (!prepareEnv.ok) {
await sendErrorResult(client, frame, "INVALID_REQUEST", prepareEnv.message);
return;
}
const plan = {
...prepared.plan,
policySnapshot: createExecApprovalPolicySnapshot({
file: execPolicy.approvals.file,
agentId: prepared.plan.agentId ?? undefined,
}),
};
await sendJsonPayloadResult(client, frame, {
plan,
execPolicy: {
security: execPolicy.security,
ask: execPolicy.ask,
},
allowAlwaysCoverage: bindApproval
? await buildSystemRunAllowAlwaysCoverage({
argv: prepared.plan.argv,
rawCommand: typeof params.rawCommand === "string" ? params.rawCommand : null,
cwd: prepared.plan.cwd,
env: prepareEnv.env,
strictInlineEval: params.strictInlineEval === true,
})
: { complete: false, patterns: [] },
});
} catch (err) {
await sendInvalidRequestResult(client, frame, err);
}
return;
}
if (command !== "system.run") {
await sendErrorResult(client, frame, "UNAVAILABLE", "command not supported");
return;
}
let params: SystemRunParams;
try {
params = resolveNodeSkillCwdParam(
decodeParams<SystemRunParams>(frame.paramsJSON),
frame.nodeId,
);
} 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,
signal: runtime.signal,
execHostEnforced,
execHostFallbackAllowed,
resolveExecSecurity,
resolveExecAsk,
isCmdExeInvocation,
sanitizeEnv,
runCommand,
runViaMacAppExecHost,
sendNodeEvent,
buildExecEventPayload,
sendInvokeResult: async (result) => {
await sendInvokeResult(client, frame, result);
},
sendExecFinishedEvent: async (event) => {
await sendExecFinishedEvent({ ...event, client });
},
preferMacAppExecHost,
});
}
function decodeMcpToolsCallParams(raw?: string | null): McpToolsCallParams {
const value = decodeParams<unknown>(raw);
if (!isRecord(value)) {
throw new Error("INVALID_REQUEST: MCP tool params must be an object");
}
const server = typeof value.server === "string" ? value.server.trim() : "";
const tool = typeof value.tool === "string" ? value.tool.trim() : "";
if (!server || !tool) {
throw new Error("INVALID_REQUEST: server and tool required");
}
if (value.arguments !== undefined && !isRecord(value.arguments)) {
throw new Error("INVALID_REQUEST: arguments must be an object");
}
return {
server,
tool,
...(value.arguments ? { arguments: value.arguments } : {}),
};
}
async function handleMcpToolsCall(
frame: NodeInvokeRequestPayload,
client: NodeHostClient,
mcpManager: NodeHostMcpManager | undefined,
signal?: AbortSignal,
): Promise<void> {
if (!mcpManager) {
await sendErrorResult(client, frame, "MCP_SERVER_UNAVAILABLE", "node host MCP is unavailable");
return;
}
let params: McpToolsCallParams;
try {
params = decodeMcpToolsCallParams(frame.paramsJSON);
} catch (error) {
await sendInvalidRequestResult(client, frame, error);
return;
}
try {
const result = await mcpManager.callMcpTool({
...params,
timeoutMs: frame.timeoutMs ?? undefined,
...(signal ? { signal } : {}),
});
await sendMcpPayloadResult(client, frame, boundMcpToolResultPayload(result));
} catch (error) {
if (error instanceof NodeHostMcpError) {
await sendErrorResult(client, frame, error.code, error.message);
return;
}
await sendErrorResult(
client,
frame,
"MCP_TOOL_ERROR",
truncateUtf16Safe(String(error), MCP_ERROR_MESSAGE_MAX_CHARS),
);
}
}
// oxlint-disable-next-line typescript/no-unnecessary-type-parameters -- CLI JSON params are typed by the invoked method.
function decodeParams<T>(raw?: string | null): T {
if (!raw) {
throw new Error("INVALID_REQUEST: paramsJSON required");
}
try {
return JSON.parse(raw) as T;
} catch {
throw new Error("INVALID_REQUEST: paramsJSON malformed JSON");
}
}
async function sendInvokeResult(
client: NodeHostClient,
frame: NodeInvokeRequestPayload,
result: Parameters<typeof buildNodeInvokeResultParams>[1],
) {
try {
await client.request("node.invoke.result", buildNodeInvokeResultParams(frame, result));
} catch {
// ignore: node invoke responses are best-effort
}
}
function buildNodeInvokeResultParams(
frame: NodeInvokeRequestPayload,
result: {
ok: boolean;
payload?: unknown;
payloadJSON?: string | null;
error?: { code?: string; message?: string } | null;
},
): {
id: string;
nodeId: string;
ok: boolean;
payload?: unknown;
payloadJSON?: string;
error?: { code?: string; message?: string };
} {
const params: ReturnType<typeof buildNodeInvokeResultParams> = {
id: frame.id,
nodeId: frame.nodeId,
ok: result.ok,
};
if (result.payload !== undefined) {
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: NodeHostClient, event: string, payload: unknown) {
try {
await client.request("node.event", buildNodeEventParams(event, payload));
} catch {
// ignore: node events are best-effort
}
}
const testing = {
clarifyNodeExecCwdSpawnError,
runCommand,
} as const;
if (process.env.VITEST || process.env.NODE_ENV === "test") {
(globalThis as Record<PropertyKey, unknown>)[Symbol.for("openclaw.nodeHostInvokeTestApi")] =
testing;
}
/* oxlint-disable max-lines -- TODO: split this grandfathered oversized file. */
|