OpenClaw工具拆解之exec

张开发
2026/5/30 19:46:55 15 分钟阅读
OpenClaw工具拆解之exec
如果文章对你有帮助请点个“关注”一、工具概述功能执行 shell 命令最核心的基础工具核心特性支持后台运行yieldMs/background支持超时控制timeout支持 PTY 模式ptytrue 用于 TTY 命令支持多主机sandbox/gateway/node支持提权执行elevated支持安全模式deny/allowlist/full支持审批模式off/on-miss/always支持环境变量env支持工作目录cwd/workdir二、Schema 定义位置第 14782 行constexecSchemaType.Object({command:Type.String({description:Shell command to execute}),workdir:Type.Optional(Type.String({description:Working directory (defaults to cwd)})),env:Type.Optional(Type.Record(Type.String(),Type.String())),yieldMs:Type.Optional(Type.Number({description:Milliseconds to wait before backgrounding (default 10000)})),background:Type.Optional(Type.Boolean({description:Run in background immediately})),timeout:Type.Optional(Type.Number({description:Timeout in seconds (optional, kills process on expiry)})),pty:Type.Optional(Type.Boolean({description:Run in a pseudo-terminal (PTY) when available (TTY-required CLIs, coding agents)})),elevated:Type.Optional(Type.Boolean({description:Run on the host with elevated permissions (if allowed)})),host:Type.Optional(Type.String({description:Exec host (sandbox|gateway|node).})),security:Type.Optional(Type.String({description:Exec security mode (deny|allowlist|full).})),ask:Type.Optional(Type.String({description:Exec ask mode (off|on-miss|always).})),node:Type.Optional(Type.String({description:Node id/name for hostnode.}))});三、完整执行代码位置第 16558 行functioncreateExecTool(defaults){// 1. 解析默认配置constdefaultBackgroundMsclampWithDefault(defaults?.backgroundMs??readEnvInt(PI_BASH_YIELD_MS),1e4,10,12e4);constallowBackgrounddefaults?.allowBackground??true;constdefaultTimeoutSectypeofdefaults?.timeoutSecnumberdefaults.timeoutSec0?defaults.timeoutSec:1800;// 2. 解析安全策略白名单、黑名单等const{safeBins,safeBinProfiles,trustedSafeBinDirs}resolveExecSafeBinRuntimePolicy({...});// 3. 返回工具定义return{name:exec,label:exec,description:Execute shell commands with background continuation. Use yieldMs/background to continue later via process tool. Use ptytrue for TTY-required commands (terminal UIs, coding agents).,parameters:execSchema,execute:async(_toolCallId,args,signal,onUpdate){// 执行逻辑开始 constparamsargs;// 1. 参数验证if(!params.command)thrownewError(Provide a command to start.);// 2. 解析后台运行请求constbackgroundRequestedparams.backgroundtrue;constyieldRequestedtypeofparams.yieldMsnumber;constyieldWindowallowBackground?(backgroundRequested?0:clampWithDefault(params.yieldMs??defaultBackgroundMs,defaultBackgroundMs,10,12e4)):null;// 3. 解析提权请求constelevatedRequestedelevatedMode!off;if(elevatedRequested){if(!elevatedDefaults?.enabled||!elevatedDefaults.allowed){thrownewError(elevated is not available right now...);}}// 4. 确定执行主机sandbox/gateway/nodelethostrequestedHost??configuredHost;if(elevatedRequested)hostgateway;// 5. 确定安全模式letsecurityminSecurity(configuredSecurity,normalizeExecSecurity$1(params.security)??configuredSecurity);if(elevatedRequestedelevatedModefull)securityfull;// 6. 确定审批模式letaskmaxAsk(configuredAsk,normalizeExecAsk$1(params.ask)??configuredAsk);constbypassApprovalselevatedRequestedelevatedModefull;if(bypassApprovals)askoff;// 7. 解析工作目录constrawWorkdirparams.workdir?.trim()||defaults?.cwd||process.cwd();letworkdirrawWorkdir;if(sandbox){constresolvedawaitresolveSandboxWorkdir({workdir:rawWorkdir,sandbox,warnings});workdirresolved.hostWorkdir;}// 8. 解析环境变量安全检查constenvsandboxhostsandbox?buildSandboxEnv({...}):hostEnvResult?.env??inheritedBaseEnv;// 9. 处理不同主机的执行逻辑if(hostnode){returnexecuteNodeHostCommand({...});}if(hostgateway!bypassApprovals){// 10. Gateway 白名单检查可能需要用户审批constgatewayResultawaitprocessGatewayAllowlist({...});if(gatewayResult.pendingResult){// 需要审批返回待处理状态returngatewayResult.pendingResult;}execCommandOverridegatewayResult.execCommandOverride;}// 11. 执行命令construnawaitrunExecProcess({command:params.command,execCommand:execCommandOverride,workdir,env,sandbox,containerWorkdir,usePty:params.ptytrue!sandbox,warnings,maxOutput:DEFAULT_MAX_OUTPUT,pendingMaxOutput:DEFAULT_PENDING_MAX_OUTPUT,notifyOnExit,notifyOnExitEmptySuccess,timeoutSec:effectiveTimeout,onUpdate});// 12. 处理后台运行letyieldedfalse;letyieldTimernull;constonYieldNow(){if(yieldTimer)clearTimeout(yieldTimer);if(yielded)return;yieldedtrue;markBackgrounded(run.session);resolveRunning();};if(allowBackgroundyieldWindow!null){if(yieldWindow0)onYieldNow();elseyieldTimersetTimeout(onYieldNow,yieldWindow);}// 13. 等待执行完成returnnewPromise((resolve,reject){run.promise.then((outcome){if(yieldTimer)clearTimeout(yieldTimer);if(yielded||run.session.backgrounded)return;resolve(buildExecForegroundResult({outcome,cwd:run.session.cwd,warningText:getWarningText()}));}).catch((err){if(yieldTimer)clearTimeout(yieldTimer);if(yielded||run.session.backgrounded)return;reject(err);});});}};}四、执行流程图exec 工具调用 ↓ 1. 参数验证command 必填 ↓ 2. 解析后台运行请求background/yieldMs ↓ 3. 解析提权请求elevated ↓ 4. 确定主机sandbox/gateway/node ↓ 5. Gateway 白名单检查 ├─ 需要审批 → 返回 pending 状态等待用户 /approve └─ 无需审批 → 继续 ↓ 6. 启动进程runExecProcess ├─ 创建子进程 ├─ 监听输出 ├─ 记录日志 └─ 返回 session ↓ 7. 判断是否后台运行 ├─ 是 → 立即返回正在运行用户可用 process 工具管理 └─ 否 → 等待完成返回完整输出五、返回结果格式前台运行完成{content:[{type:text,text:命令输出内容...}],details:{status:completed,exitCode:0,cwd:/path/to/workdir}}后台运行中{content:[{type:text,text:Command still running (session abc123, pid 12345). Use process (list/poll/log/write/kill/clear/remove) for follow-up.}],details:{status:running,sessionId:abc123,pid:12345,startedAt:1711716000000,cwd:/path/to/workdir,tail:部分输出...}}需要审批{content:[{type:text,text:Approval required (id abc123).\nHost: gateway\nCWD: /workspace\nCommand:\nsh\nrm -rf /tmp/test\n\nReply with: /approve abc123 allow-once|allow-always|deny}],details:{status:pending_approval,approvalId:abc123}}六、参数详解6.1 必填参数参数类型说明commandstring要执行的 shell 命令6.2 可选参数参数类型默认值说明workdirstringcwd工作目录envobject-环境变量键值对yieldMsnumber10000后台运行等待时间毫秒backgroundbooleanfalse立即后台运行timeoutnumber1800超时时间秒ptybooleanfalse使用 PTYTTY 命令需要elevatedbooleanfalse提权执行hoststringsandbox执行主机sandbox/gateway/nodesecuritystringallowlist安全模式deny/allowlist/fullaskstringon-miss审批模式off/on-miss/alwaysnodestring-节点 IDhostnode 时使用七、使用示例7.1 简单命令{name:exec,arguments:{command:ls -la}}7.2 后台运行{name:exec,arguments:{command:python long_running_script.py,yieldMs:5000}}7.3 超时控制{name:exec,arguments:{command:ping -n 100 www.example.com,timeout:30}}7.4 PTY 模式{name:exec,arguments:{command:htop,pty:true}}7.5 环境变量{name:exec,arguments:{command:echo $MY_VAR,env:{MY_VAR:Hello World}}}八、安全机制8.1 安全模式模式说明deny禁止所有命令allowlist只允许白名单中的命令full允许所有命令需要提权8.2 审批模式模式说明off无需审批on-miss白名单未命中时审批always总是审批8.3 提权执行{name:exec,arguments:{command:apt update,elevated:true,host:gateway}}前提条件elevatedDefaults.enabled trueelevatedDefaults.allowed true九、配套工具process 工具exec 的配套工具用于管理后台进程Action说明list列出所有进程poll轮询进程状态log读取进程日志write写入 stdinsend-keys发送按键paste粘贴文本submit发送 EOFkill终止进程如果文章对你有帮助请点个“关注”

更多文章