openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
23 lines • 29.9 kB
JavaScript
import{l as normalizeOptionalString,m as readNonBlankString}from"./string-coerce-CpTFcSwY.mjs";import{A as resolveExpiresAtMsFromDurationMs,o as asDateTimestampMs}from"./number-coercion-B3CfI447.mjs";import{s as formatErrorMessage}from"./error-coercion-DlKnt6w-.mjs";import{n as safeParseJsonRecord}from"./json-coercion-DNNwq4_v.mjs";import{f as normalizeStringEntries}from"./string-normalization-D_oBUpO3.mjs";import{r as runWithMainThreadTask}from"./main-thread-stall-CJLZRvCI.mjs";import{t as killProcessTree}from"./kill-tree-CIjHhVfN.mjs";import{t as LruCache}from"./lru-cache-BkKrgG7y.mjs";import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import{d as redactToolPayloadText}from"./redact-BT59pdZ_.mjs";import"./paths-D_FOvGon.mjs";import{n as createLazyPromise}from"./lazy-promise-CismJCQR.mjs";import{c as omitGatewayCredentialEnv}from"./host-env-security-CA3pVx5Z.mjs";import{n as resolveRuntimeWorkerArgv}from"./runtime-worker-url-Dqf-I1cs.mjs";import{o as resolveRuntimeProcessEntrypointUrl}from"./runtime-process-url-DJ272Tuo.mjs";import{E as recordDiagnosticToolExecutionDeadline,i as emitDiagnosticEventWithTrustedTraceContext}from"./diagnostic-events-BYBrlAdF.mjs";import{t as _usingCtx}from"./usingCtx-CUVyQ_FT.mjs";import{r as resolvePreferredOpenClawTmpDir}from"./tmp-openclaw-dir-DapBruir.mjs";import{i as withChildProcessOperation}from"./spawn-diagnostics-C-LTFiNq.mjs";import{n as spawnProcess}from"./spawn-utils-B2ZRlkW6.mjs";import{t as DEFAULT_EXEC_APPROVAL_TIMEOUT_MS}from"./exec-approvals-core-BZ6-zeZE.mjs";import{d as withExecRequestOwners,s as execRequestAbortSignal,u as retainExecRequestProcess}from"./exec-request-context-BB4c5QQi.mjs";import{c as normalizeDeliveryContext}from"./delivery-context.shared-L-4UIv4-.mjs";import{o as resolveExecApprovalAllowedDecisions}from"./exec-approvals-policy-DUqwCsoC.mjs";import{m as withoutGatewayToolCallerIdentity,o as getGatewayToolCallerIdentity,t as captureGatewayToolCallerAssertion}from"./gateway-caller-context-Dw9IijqV.mjs";import{b as renderExecUpdateText,d as buildStoppedRunExit,l as buildExecExitOutcome,m as joinExecFailureOutput,r as EXEC_OUTPUT_FILE_MAX_BYTES,u as buildExecRuntimeErrorOutcome}from"./bash-tools.exec-output-Ci2XRgYO.mjs";import{t as formatFencedCodeBlock}from"./markdown-code-rYi19S0p.mjs";import{i as logWarn}from"./logger-BHIcoxTH.mjs";import{c as resolveSafeTimeoutDelayMs}from"./timeouts-Dzxxy4Mb.mjs";import{t as getProcessSupervisor}from"./supervisor-4YHLp8V6.mjs";import{c as runWithAgentToolSourceExecutionScope,i as captureAgentToolSourceExecutionGuard}from"./agent-tool-source-execution-guard-D2z6vTFX.mjs";import{A as waitForExecSession,L as readEnvInt,N as chunkString,P as clampWithDefault,g as markCancellationRequested,n as addSession,o as createProcessSession,r as appendOutput,w as resolveProcessCleanupMs}from"./bash-process-registry-BL4zA8Yf.mjs";import"./exec-approvals-BLANskJu.mjs";import{a as removePathPrepend,n as findPathKey,r as mergePathPrepend}from"./path-prepend-DUq-slJD.mjs";import{n as recordAgentCleanupFailure}from"./run-cleanup-timeout-B__J_Jbc.mjs";import{t as callGatewayTool}from"./gateway-Bf9f0Pcc.mjs";import{t as markToolDecisionRecorded}from"./agent-tools.before-tool-call.decision-kOa4S0Cs.mjs";import{t as isApprovalNotFoundError}from"./approval-errors-CMSQmBZ2.mjs";import{n as createStreamingBinaryOutputSanitizer,o as getShellConfig}from"./shell-utils-B6f0UW0e.mjs";import{t as prependShellPath}from"./login-shell-path-carrier-BidH7Ys3.mjs";import{t as buildGitHubExecLaunchArgv}from"./github-exec-launch-BFX4QHjM.mjs";import{a as maybeNotifyOnExit,s as prepareExecExitNotification}from"./bash-tools.exec-notify-CT6pCobB.mjs";import{n as isUnsupportedShellWrapperArgv}from"./format-DqQj_vVw.mjs";import{a as registerSecretEgressProxyProcess}from"./registry-D0UT9UlH.mjs";import{i as createProcessSessionId,n as settleHostExecDescendants,t as settleExecProcessExit}from"./bash-tools.exec-settlement-Bl5VupHb.mjs";import{t as openPrivateTempFileStream}from"./private-temp-file-Da4iZ-3j.mjs";import{constants}from"node:fs";import path from"node:path";import{createHash}from"node:crypto";import fs$1 from"node:fs/promises";import os from"node:os";import{AsyncLocalStorage}from"node:async_hooks";
//!src/agents/bash-tools.exec-diagnostics.ts
function emitExecProcessCompleted(e){const t=e.outcome.exitSignal;const n=t===null?void 0:String(t);emitDiagnosticEventWithTrustedTraceContext({type:`exec.process.completed`,target:e.target,mode:e.mode,outcome:e.outcome.status,durationMs:e.outcome.durationMs,commandLength:e.command.length,...e.sessionKey?.trim()?{sessionKey:e.sessionKey.trim()}:{},...e.outcome.exitCode!=null?{exitCode:e.outcome.exitCode}:{},...n?{exitSignal:n}:{},...e.outcome.status===`failed`?{timedOut:e.outcome.timedOut,failureKind:e.outcome.failureKind}:{}})}
//!src/agents/shell-snapshot-env.ts
const SAFE_ENV_NAMES=/* @__PURE__ */ new Set([`ASDF_DIR`,`BUN_INSTALL`,`CARGO_HOME`,`CDPATH`,`GOPATH`,`GOROOT`,`GOENV_ROOT`,`HOMEBREW_CELLAR`,`HOMEBREW_PREFIX`,`HOMEBREW_REPOSITORY`,`INFOPATH`,`MANPATH`,`NVM_DIR`,`PATH`,`PNPM_HOME`,`PYENV_ROOT`,`RBENV_ROOT`,`RUSTUP_HOME`,`VOLTA_HOME`]);const SECRET_ENV_PATTERN=/(secret|token|password|passwd|credential|cookie|session|auth|key)/i;function captureShellSnapshotEnvironment(e){const t={};for(const[n,r]of Object.entries(e))if(SAFE_ENV_NAMES.has(n)&&!SECRET_ENV_PATTERN.test(n)&&typeof r===`string`)t[n]=r;return t}
//!src/agents/shell-snapshot.ts
const SNAPSHOT_VERSION=1;const SNAPSHOT_REFRESH_MS=3e5;const SNAPSHOT_MAX_AGE_MS=2592e5;const SNAPSHOT_CACHE_MAX_ENTRIES=128;const CAPTURE_MARKER=`__OPENCLAW_SHELL_SNAPSHOT_CAPTURE__`;const ENV_MARKER=`__OPENCLAW_SHELL_SNAPSHOT_ENV__`;const EXEC_SHELL_SNAPSHOT_ENV=`OPENCLAW_EXEC_SHELL_SNAPSHOT`;const SNAPSHOT_SHELLS=/* @__PURE__ */ new Set([`bash`,`zsh`]);const SNAPSHOT_DISABLE_VALUES=/* @__PURE__ */ new Set([`0`,`false`,`no`,`off`]);const CAPTURE_ENV_NAMES=/* @__PURE__ */ new Set([...SAFE_ENV_NAMES,`HOME`,`OPENCLAW_SHELL`,`SHELL`,`USERPROFILE`,`ZDOTDIR`]);const SECRET_SHELL_STATE_PATTERNS=[/\b(authorization|api[_-]?key|access[_-]?token|refresh[_-]?token|secret|password|passwd|credential)\b\s*[:=]/i,/\b[A-Z][A-Z0-9_]*(?:SECRET|TOKEN|PASSWORD|PASSWD|CREDENTIAL|API_KEY|ACCESS_KEY|SESSION)[A-Z0-9_]*\s*[:=]/,/\b(GITHUB_TOKEN|OPENAI_API_KEY|ANTHROPIC_API_KEY|GOOGLE_API_KEY|GEMINI_API_KEY)\b/,/\b(ghp_|github_pat_|sk-[A-Za-z0-9]|xox[baprs]-|ya29\.|AIza[0-9A-Za-z_-]|AKIA[0-9A-Z]{16})/,/-----BEGIN [A-Z ]*PRIVATE KEY-----/];const snapshotCache=new LruCache(SNAPSHOT_CACHE_MAX_ENTRIES);let cleanupPromise=null;async function maybeWrapCommandWithShellSnapshot(e){if(e.enabled===false||process.platform===`win32`||isExecShellSnapshotDisabled(process.env)||!isSupportedSnapshotShell(e.shell,e.shellArgs))return e.command;try{const t=await getOrCreateShellSnapshot(e);return t?buildSnapshotWrappedCommand(e.command,t,buildRuntimeEnvRestoreScript(e.env)):e.command}catch{return e.command}}function resolveShellSnapshotDir(e=process.env){return path.join(resolveStateDir(e),`cache`,`shell-snapshots`)}function isSupportedSnapshotShell(e,t){return t.includes(`-c`)&&SNAPSHOT_SHELLS.has(path.basename(e))}function isExecShellSnapshotDisabled(e){const t=e[EXEC_SHELL_SNAPSHOT_ENV]?.trim().toLowerCase();return Boolean(t&&SNAPSHOT_DISABLE_VALUES.has(t))}async function getOrCreateShellSnapshot(e){const t=buildSnapshotKey(e);const n=snapshotCache.get(t);const r=Date.now();if(n&&r-n.createdAtMs<SNAPSHOT_REFRESH_MS)return await n.promise;const i=createShellSnapshot(e,t,Boolean(n));snapshotCache.set(t,{createdAtMs:r,promise:i});return await i}function buildSnapshotKey(e){return createHash(`sha256`).update(JSON.stringify({version:SNAPSHOT_VERSION,shell:e.shell,shellArgs:e.shellArgs,cwd:path.resolve(e.cwd),home:getTrustedShellHome(),stateDir:resolveStateDir(process.env),env:buildSafeEnvSignature(process.env),zdotdir:process.env.ZDOTDIR?.trim()||getTrustedShellHome()})).digest(`hex`)}function buildSafeEnvSignature(e){return[...SAFE_ENV_NAMES].toSorted().map(t=>[t,e[t]??null])}function getTrustedShellHome(){const e=readNonBlankString(process.env.HOME)??readNonBlankString(process.env.USERPROFILE);if(e)return e;const t=readNonBlankString(os.userInfo().homedir);if(!t)throw new Error(`Unable to resolve the current user's home directory`);return t}async function createShellSnapshot(e,t,n){const r=resolveShellSnapshotDir(process.env);await fs$1.mkdir(r,{recursive:true,mode:448});cleanupPromise??=cleanupStaleSnapshots(r);const i=path.join(r,`${t}.sh`);if(!n&&await isFreshSnapshot(i))return i;const a=await captureShellSnapshot(e);if(!a)return null;const o=path.join(r,`${t}.${process.pid}.${Date.now()}.tmp`);await fs$1.writeFile(o,a,{encoding:`utf8`,mode:384});await fs$1.chmod(o,384);if(!await validateSnapshot(e,o)){await fs$1.rm(o,{force:true});return null}await fs$1.rename(o,i);await fs$1.chmod(i,384);return i}async function isFreshSnapshot(e){try{const t=await fs$1.stat(e);return Date.now()-t.mtimeMs<SNAPSHOT_REFRESH_MS}catch{return false}}async function validateSnapshot(e,t){return await runShell({shell:e.shell,shellArgs:e.shellArgs,cwd:e.cwd,env:buildTrustedSnapshotCaptureEnv(e.env),command:`. ${shQuote(t)} >/dev/null 2>&1`,timeoutMs:2e3})===0}async function captureShellSnapshot(e){const t=path.basename(e.shell);const n=await fs$1.mkdtemp(path.join(resolvePreferredOpenClawTmpDir(),`openclaw-shell-snapshot-`));try{try{var r=_usingCtx();await fs$1.chmod(n,448);const i=path.join(n,`snapshot.out`);const a=r.a(await fs$1.open(i,constants.O_RDWR|constants.O_CREAT|constants.O_EXCL|constants.O_NOFOLLOW,384));await a.chmod(384);const o=[process.execPath,...resolveRuntimeWorkerArgv(resolveRuntimeProcessEntrypointUrl(`shellSnapshotEnvironment`),process.execPath)];const s=[`{`,t===`zsh`?`if [ -r "\${ZDOTDIR:-$HOME}/.zshrc" ]; then . "\${ZDOTDIR:-$HOME}/.zshrc"; fi`:`:`,`printf '\\n%s\\n' ${shQuote(CAPTURE_MARKER)}`,t===`zsh`?`alias -L 2>/dev/null || true`:`alias 2>/dev/null || true`,`(typeset -f 2>/dev/null || declare -f 2>/dev/null || true)`,`printf '\\n%s\\n' ${shQuote(ENV_MARKER)}`,o.map(shQuote).join(` `),`} > ${shQuote(i)}`].join(`
`);if(await runShell({shell:e.shell,shellArgs:t===`bash`?[`-i`,`-c`]:[`-f`,`-i`,`-c`],cwd:e.cwd,env:buildTrustedSnapshotCaptureEnv(e.env),command:s,timeoutMs:5e3})!==0)return null;return buildSnapshotFile(await a.readFile(`utf8`))}catch(e){r.e=e}finally{await r.d()}}finally{await fs$1.rm(n,{recursive:true,force:true})}}function buildSnapshotCaptureEnv(e){return Object.fromEntries(Object.entries(e).filter(([e])=>CAPTURE_ENV_NAMES.has(e)&&!SECRET_ENV_PATTERN.test(e)))}function buildTrustedSnapshotCaptureEnv(e){const t=buildSnapshotCaptureEnv(process.env);t.HOME=getTrustedShellHome();if(e.OPENCLAW_SHELL===`exec`)t.OPENCLAW_SHELL=`exec`;return t}function buildSnapshotFile(e){const t=e.indexOf(CAPTURE_MARKER);const n=e.indexOf(ENV_MARKER);if(t===-1||n===-1||n<=t)return null;const r=e.slice(t+35,n).trim().split(/\r?\n/).filter(e=>!e.includes(CAPTURE_MARKER)&&!e.includes(ENV_MARKER)).join(`
`);if(SECRET_SHELL_STATE_PATTERNS.some(e=>e.test(r)))return null;return[`# OpenClaw exec shell snapshot. Generated; do not edit.`,'if [ -n "${BASH_VERSION:-}" ]; then shopt -s expand_aliases 2>/dev/null || true; fi',`unalias -a 2>/dev/null || true`,r,parseSafeEnvExports(e.slice(n+31).trim()),``].filter(e=>e.trim().length>0).join(`
`)}function parseSafeEnvExports(e){const t=safeParseJsonRecord(e);if(!t)return``;return Object.entries(captureShellSnapshotEnvironment(t)).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`export ${e}=${shQuote(t)}`).join(`
`)}function buildRuntimeEnvRestoreScript(e){return[...SAFE_ENV_NAMES].toSorted().filter(t=>e[t]!==process.env[t]&&!SECRET_ENV_PATTERN.test(t)).map(t=>typeof e[t]===`string`?`export ${t}=${shQuote(e[t])}`:`unset ${t}`).join(`
`)}function buildSnapshotWrappedCommand(e,t,n){return[`if [ -r ${shQuote(t)} ]; then . ${shQuote(t)}; fi`,n,`eval ${shQuote(e)}`].filter(e=>e.trim().length>0).join(`
`)}function shQuote(e){return`'${e.replace(/'/g,`'\\''`)}'`}async function runShell(e){return await new Promise(t=>{const n=withChildProcessOperation(`shell.snapshot`,()=>spawnProcess(e.shell,[...e.shellArgs,e.command],{cwd:e.cwd,detached:process.platform!==`win32`,env:e.env,stdio:`ignore`,windowsHide:true}));let r=false;const finish=e=>{if(r)return;r=true;clearTimeout(i);if(n.pid)killProcessTree(n.pid,{graceMs:0,detached:true});else n.kill(`SIGKILL`);t(e)};n.once(`spawn`,()=>{if(r&&n.pid)killProcessTree(n.pid,{graceMs:0,detached:true})});const i=setTimeout(()=>{killProcessTree(n.pid??0,{graceMs:250,detached:true});finish(null)},e.timeoutMs);n.on(`error`,()=>{finish(null)});n.on(`exit`,e=>{setTimeout(()=>finish(e),250)});n.on(`close`,finish)})}async function cleanupStaleSnapshots(e){const t=Date.now()-SNAPSHOT_MAX_AGE_MS;let n;try{n=await fs$1.readdir(e)}catch{return}await Promise.all(n.filter(e=>e.endsWith(`.sh`)||e.endsWith(`.tmp`)).map(async n=>{const r=path.join(e,n);try{if((await fs$1.stat(r)).mtimeMs<t)await fs$1.rm(r,{force:true})}catch{}}))}
//!src/agents/bash-tools.exec-host-spawn.ts
async function prepareHostExecSpawn(e){return await runWithMainThreadTask(`exec:spawn-prepare`,async()=>{const{shell:t,args:n}=await getShellConfig();const r=omitGatewayCredentialEnv(e.env);let i=e.execCommand??e.command;const a=e.pathPrepend;if(process.platform!==`win32`&&a&&a.length>0){const e=findPathKey(r);const t=r[e];if(t){const n=removePathPrepend(t,a);if(n!==void 0)r[e]=n}i=prependShellPath(i,r,a.join(path.delimiter))}const o=await maybeWrapCommandWithShellSnapshot({enabled:e.execCommand===void 0,command:i,shell:t,shellArgs:n,cwd:e.workdir,env:r});const s=[t,...n,o];return{mode:e.usePty?`pty`:`child`,argv:e.githubProfileDir?buildGitHubExecLaunchArgv(s,e.githubProfileDir,{githubHost:r.GH_HOST}):s,env:r,cwd:e.workdir,stdinMode:e.usePty?`pipe-open`:`pipe-closed`}})}function resolveExecLaunchEnv(e,t,n){const r=e&&!t?omitGatewayCredentialEnv(e):e;return n?{...r,...n}:r}
//!src/agents/bash-tools.exec-launch.ts
var ExecProcessPreflightError=class ExecProcessPreflightError extends Error{constructor(e){super(`exec denied by final preflight`);this.result=e}static unwrap(e){if(e instanceof ExecProcessPreflightError)return e.result;throw e}};function createExecLaunchLifecycle(e,t){let n=e;let r=t;let i=false;const release=e=>r?.(e);return{get initiated(){return i},release,async prepare(e,t){e?.();const n=await t?.();e?.();if(n)throw new ExecProcessPreflightError(n)},dispose(){release();r=void 0;n=void 0},wrap(e,t){return(r,a)=>{e();t?.();const initiate=()=>{i=true;return r()};try{return n?n(initiate,a):initiate()}finally{if(!a)release()}}}}}
//!src/agents/bash-tools.exec-runtime.ts
function resolveExecTimeoutMs(e){if(typeof e!==`number`||!Number.isFinite(e)||e<=0)return;return resolveSafeTimeoutDelayMs(e*1e3)}const DEFAULT_MAX_OUTPUT=clampWithDefault(readEnvInt(`OPENCLAW_BASH_MAX_OUTPUT_CHARS`,`PI_BASH_MAX_OUTPUT_CHARS`),2e5,1e3,2e5);const DEFAULT_PENDING_MAX_OUTPUT=clampWithDefault(readEnvInt(`OPENCLAW_BASH_PENDING_MAX_OUTPUT_CHARS`),3e4,1e3,2e5);const DEFAULT_PATH=process.env.PATH??`/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`;const DEFAULT_APPROVAL_TIMEOUT_MS=DEFAULT_EXEC_APPROVAL_TIMEOUT_MS;const DEFAULT_APPROVAL_REQUEST_TIMEOUT_MS=DEFAULT_APPROVAL_TIMEOUT_MS+1e4;const DEFAULT_APPROVAL_RUNNING_NOTICE_MS=1e4;const APPROVAL_SLUG_LENGTH=8;function applyShellPath(e,t){if(!t)return;const n=normalizeStringEntries(t.split(path.delimiter));if(n.length===0)return;const r=findPathKey(e);const i=mergePathPrepend(e[r],n);if(i)e[r]=i}function createApprovalSlug(e){return e.slice(0,APPROVAL_SLUG_LENGTH)}function buildApprovalPendingMessage(e){const t=formatFencedCodeBlock(e.command,`sh`);const n=[];const r=e.allowedDecisions??resolveExecApprovalAllowedDecisions();const i=r.join(`|`);const a=e.warningText?.trim();if(a)n.push(a,``);n.push(`Approval required (id ${e.approvalSlug}, full ${e.approvalId}).`);n.push(`Host: ${e.host}`);if(e.nodeId)n.push(`Node: ${e.nodeId}`);n.push(`CWD: ${e.cwd??`(node default)`}`);n.push(`Command:`);n.push(t);n.push(`Mode: foreground (interactive approvals available).`);if(e.processContinuationAvailable!==false)n.push(r.includes(`allow-always`)?`Background mode requires pre-approved policy (allow-always or ask=off).`:`Background mode requires an effective policy that allows pre-approval (for example ask=off).`);n.push(`Reply with: /approve ${e.approvalSlug} ${i}`);if(!r.includes(`allow-always`))n.push(`Allow Always is unavailable for this command.`);n.push(`If the short code is ambiguous, use the full id in /approve.`);return n.join(`
`)}function resolveApprovalRunningNoticeMs(e){if(typeof e!==`number`||!Number.isFinite(e))return DEFAULT_APPROVAL_RUNNING_NOTICE_MS;if(e<=0)return 0;return Math.floor(e)}async function runExecProcess({startupSignal:e,onUpdate:t,beforeSpawn:n,assertCurrent:r,initiateSpawn:i,releaseSpawn:a,onSettledBeforeNotify:o,...s}){const c=execRequestAbortSignal(s.requestOwners);const l=c&&e?AbortSignal.any([c,e]):c??e;let u=captureAgentToolSourceExecutionGuard(l);let d=getGatewayToolCallerIdentity()?.operatorAuthority;const f=d?.signal;let p;const m=Date.now();const h=resolveExecTimeoutMs(s.timeoutSec);if(h!==void 0)recordDiagnosticToolExecutionDeadline(m+h);const g=createProcessSessionId();const _=s.execCommand??s.command;const v=s.sandbox?`sandbox`:`host`;const y=getProcessSupervisor();const b={...s.env,OPENCLAW_SHELL:`exec`};const x=createProcessSession(withExecRequestOwners({id:g,command:s.command,scopeKey:s.scopeKey,sessionKey:s.sessionKey,sandboxContainerName:s.sandbox?.containerName,cleanupMs:resolveProcessCleanupMs(s.cleanupMs),agentId:s.agentId,eventRouting:s.eventRouting,notifyDeliveryContext:normalizeDeliveryContext(s.notifyDeliveryContext),notifyOnExit:s.notifyOnExit,notifyOnExitEmptySuccess:s.notifyOnExitEmptySuccess===true,exitNotified:false,startedAt:m,cwd:s.workdir,maxOutputChars:s.maxOutput,pendingMaxOutputChars:s.pendingMaxOutput,totalOutputChars:0,pendingStdoutChars:0,pendingStderrChars:0,pendingOutputDropped:false,exited:false,truncated:false,backgrounded:false,...s.independentService?{independentService:true}:{},cursorKeyMode:s.usePty?`unknown`:`normal`},s.requestOwners));withoutGatewayToolCallerIdentity(()=>addSession(x));if(s.requestOwners?.length)retainExecRequestProcess(s.requestOwners,waitForExecSession(x));const S=prepareExecExitNotification(x,s.subagentSession===true,s.sessionsYieldAvailable===true);if(S)await S;let C=t&&AsyncLocalStorage.bind(t);let w=s.approvalTransport?()=>{r?.();s.approvalTransport?.assertExecution({command:s.command,execCommand:_,cwd:s.workdir,env:s.env,pty:s.usePty})}:r;let T=o;const emitUpdate=()=>{if(!C||x.backgrounded||x.exited)return;const e=x.tail;C({content:[{type:`text`,text:renderExecUpdateText({tailText:e||x.aggregated,warnings:s.warnings})}],details:{status:`running`,sessionId:g,pid:x.pid??void 0,startedAt:m,cwd:x.cwd,tail:e}})};const E=createStreamingBinaryOutputSanitizer(e=>{if(e===`?1h`||e===`?1l`)x.cursorKeyMode=e===`?1h`?`application`:`normal`;else if(R&&(e===`6n`||e===`?6n`))F?.stdin?.write(`\x1B[1;1R`)});const D=createStreamingBinaryOutputSanitizer();const handleOutput=(e,t)=>n=>{for(const r of chunkString(t(n))){appendOutput(x,e,r);emitUpdate()}};let O;let k;let A;let j=false;let M;let N;let P;const beginSandboxTermination=()=>{const e=M;if(!e||N||x.exited)return;N=withoutGatewayToolCallerIdentity(async()=>{try{await e();return}catch(e){return{error:e}}})};const finalizeSandboxExec=async e=>{if(!j||!s.sandbox?.finalizeExec)return;await s.sandbox.finalizeExec({...e,token:O})};const runtimeErrorOutcome=e=>buildExecRuntimeErrorOutcome({error:e,aggregated:x.aggregated.trim(),durationMs:Date.now()-m});const finalizeAndSettleSession=async(e,t)=>{P?.revoke();let n=e;x.finalizing=true;try{if(!s.sandbox&&F?.waitForExtinction)n=await settleHostExecDescendants(x,F,e,s.warnings);if(e.exitReason!==`exit`)beginSandboxTermination();await N;const[r]=await Promise.allSettled([finalizeSandboxExec({status:e.status,exitCode:e.exitCode,timedOut:e.timedOut})]);const i=N?await N:void 0;const a=[...t===void 0?[]:[t],...i?[i.error]:[]];if(r.status===`rejected`)a.push(r.reason);if(a.length>0){const e=a.map(e=>formatErrorMessage(e)).join(`
`);throw new AggregateError(a,e)}}catch(t){x.finalizationFailed=true;recordAgentCleanupFailure();const r=redactToolPayloadText(formatErrorMessage(t));if(e.status===`completed`)n=runtimeErrorOutcome(r);else{n={...e,message:joinExecFailureOutput(e.message,r),reason:joinExecFailureOutput(e.reason,r)};logWarn(`exec: finalization after process failure failed (${r}).`)}appendOutput(x,`stderr`,`\n${r}\n`);n.aggregated=x.aggregated.trim()}finally{n=await settleExecProcessExit({session:x,outcome:n,onSettledBeforeNotify:T,notifyOnExit:(e,t)=>maybeNotifyOnExit(e,t,s.subagentSession===true),failureOutcome:runtimeErrorOutcome})}return n};const prepareSpawnSpec=async()=>{if(s.sandbox){if(!s.sandbox.buildExecSpec)throw new Error(`sandbox backend does not provide buildExecSpec`);const e=s.sandbox.prepareProcessCleanup?.(b);M=e?.terminate.bind(e);const t=await s.sandbox.buildExecSpec({command:_,workdir:s.containerWorkdir??s.sandbox.containerWorkdir,env:e?.env??b,usePty:s.usePty});O=t.finalizeToken;k=t.assertCurrent;A=t.prepareCurrent;j=true;return{mode:`child`,argv:t.argv,env:t.env,cwd:t.cwd,stdinMode:t.stdinMode}}return prepareHostExecSpawn({...s,env:b})};let F=null;let I;const onRequestCancelled=()=>{x.requestCancelled=true;markCancellationRequested(x);C=void 0;if(F)F.cancel(`manual-cancel`);else y.cancel(g,`manual-cancel`);beginSandboxTermination()};c?.addEventListener(`abort`,onRequestCancelled,{once:true});if(c?.aborted)onRequestCancelled();const L=createExecLaunchLifecycle(i,a);const onOperatorRevoked=()=>F?.cancel(`manual-cancel`);const releaseExecutionContext=()=>{T=void 0;f?.removeEventListener(`abort`,onOperatorRevoked);p?.();p=void 0;c?.removeEventListener(`abort`,onRequestCancelled)};let R=s.usePty&&!s.sandbox;const emitCompleted=e=>emitExecProcessCompleted({command:s.command,mode:R?`pty`:`child`,outcome:e,sessionKey:s.sessionKey,target:v});const spawn=e=>runWithAgentToolSourceExecutionScope(u,async()=>{const t=u;const n=d?.assertCurrent;const r=k;const i=w;const assertCurrent=()=>{t?.();n?.();r?.()};assertCurrent();i?.();if(s.durable&&(s.sandbox||s.usePty||s.secretEgressBindings?.length))throw new Error(`Durable exec requires noninteractive Gateway-host execution without secret-egress proxy grants. Use non-durable background exec or a directly provided credential.`);const a=s.secretEgressBindings?await registerSecretEgressProxyProcess(s.secretEgressBindings):void 0;P=a;try{if(s.durable){const{startDurableExecProcess:t}=await import(`./bash-process-durable-D6g8n0F0.mjs`);return await t(x,{...e,env:resolveExecLaunchEnv(e.env,false),assertCurrent,beforeSpawn:i,initiateSpawn:L.wrap(assertCurrent,i)},s.durable)}return await withChildProcessOperation(`agent.exec`,()=>withoutGatewayToolCallerIdentity(()=>y.spawn({...e,env:resolveExecLaunchEnv(e.env,Boolean(s.sandbox),a?.env),onCancel:e=>{I??=e;beginSandboxTermination();a?.revoke()},assertCurrent,...e.mode===`child`?{prepareTargetSpawn:A}:{},beforeSpawn:i,initiateSpawn:L.wrap(assertCurrent,i)})))}catch(e){a?.revoke();throw e}});if(!s.sandbox&&!s.durable)x.outputFile=openPrivateTempFileStream(`openclaw-exec`,EXEC_OUTPUT_FILE_MAX_BYTES);try{u?.();d?.assertCurrent();p=d?.retain?.();const e=await prepareSpawnSpec();R=e.mode===`pty`;const t={executionIntent:`agent-tool`,executionScopeKey:s.sessionKey??s.scopeKey,runId:g,...s.sandbox?{cleanupOwnership:`external`,exactEnv:true}:{},scopeKey:s.scopeKey,cwd:e.cwd??s.workdir,env:e.env,timeoutMs:h,captureOutput:false,onStdout:handleOutput(`stdout`,E),onStderr:handleOutput(`stderr`,D)};await L.prepare(u,n);if(e.mode===`pty`)try{F=await spawn({...t,mode:`pty`,argv:e.argv})}catch(e){if(L.initiated){L.release();throw e}L.release(`retry`);u?.();const t=`Warning: PTY spawn failed (${String(e)}); retrying without PTY for \`${s.command}\`.`;logWarn(`exec: PTY spawn failed (${String(e)}); retrying without PTY for "${s.command}".`);s.warnings.push(t);R=false;await L.prepare(u,n)}if(!F)F=await spawn({...t,mode:`child`,argv:e.argv,stdinMode:e.stdinMode,...s.sandbox?{}:{releaseOnRootExit:true}});if(s.durable&&c?.aborted)F.cancel(`manual-cancel`);f?.addEventListener(`abort`,onOperatorRevoked,{once:true});if(f?.aborted)onOperatorRevoked()}catch(e){L.release();C=void 0;emitCompleted(await finalizeAndSettleSession(runtimeErrorOutcome(e)).finally(releaseExecutionContext));throw e}finally{L.dispose();w=void 0;u=void 0;d=void 0;k=void 0;A=void 0}x.processActivity=F.activity;recordDiagnosticToolExecutionDeadline(F.activity.deadlineAtMs);x.stdin=F.stdin;x.pid=F.pid;const z=F;const B=withoutGatewayToolCallerIdentity(async()=>{try{let e;let t;try{const n=await z.wait().catch(e=>{if(!I||I===`manual-cancel`)throw e;t=e;return buildStoppedRunExit(I,Date.now()-m)});e=buildExecExitOutcome({exit:n,aggregated:x.aggregated.trim(),durationMs:Date.now()-m,timeoutSec:s.timeoutSec,processContinuationAvailable:s.processContinuationAvailable!==false})}catch(t){e=runtimeErrorOutcome(t)}finally{C=void 0}const n=await finalizeAndSettleSession(e,t);emitCompleted(n);return n}finally{releaseExecutionContext()}});return{session:x,startedAt:m,pid:x.pid??void 0,promise:B,kill:()=>F?.cancel(`manual-cancel`),disableUpdates:()=>{C=void 0}}}
//!src/agents/bash-tools.exec-approval-request.ts
const loadExecApprovalCommandSpansRuntime=createLazyPromise(()=>import(`./bash-tools.exec-approval-request.runtime-vlB6kft5.mjs`),{cacheRejections:true});function parseDecision(e){if(!e||typeof e!==`object`)return{present:false,value:null};if(!Object.hasOwn(e,`decision`))return{present:false,value:null};const t=e.decision;return{present:true,value:typeof t===`string`?t:null}}function resolveDefaultExecApprovalExpiresAtMs(){return resolveExpiresAtMsFromDurationMs(DEFAULT_APPROVAL_TIMEOUT_MS)??0}var ExecApprovalRunAbortedError=class extends Error{constructor(){super(`Exec approval cancelled because its run was aborted`);this.name=`ExecApprovalRunAbortedError`}};function isExecApprovalRunAbortedError(e){return e instanceof ExecApprovalRunAbortedError}async function registerExecApprovalRequest(e,t){if(t){const n=await t.request(e);markToolDecisionRecorded();return n}const n=await callGatewayTool(`exec.approval.request`,{timeoutMs:DEFAULT_APPROVAL_REQUEST_TIMEOUT_MS},e,{expectFinal:false});markToolDecisionRecorded();const r=parseDecision(n);const i=normalizeOptionalString(n?.id)??e.id;const a=asDateTimestampMs(n?.expiresAtMs)??resolveDefaultExecApprovalExpiresAtMs();if(r.present)return{id:i,expiresAtMs:a,finalDecision:r.value};return{id:i,expiresAtMs:a}}async function resolveRegisteredExecApprovalDecision(e){if(e.preResolvedDecision!==void 0)return e.preResolvedDecision??null;const t=captureGatewayToolCallerAssertion();const n=e.expiresAtMs===void 0?void 0:getGatewayToolCallerIdentity()?.watchdogAttempt?.beginWait({kind:`approval`,deadlineAtMs:e.expiresAtMs,isCurrent:()=>{t?.();return true}});try{const t=e.approvalTransport?await e.approvalTransport.waitDecision({id:e.approvalId}):await callGatewayTool(`exec.approval.waitDecision`,{timeoutMs:DEFAULT_APPROVAL_REQUEST_TIMEOUT_MS},{id:e.approvalId});if(t&&typeof t===`object`&&t.terminalReason===`run-aborted`)throw new ExecApprovalRunAbortedError;return parseDecision(t).value}catch(e){if(isApprovalNotFoundError(e))return null;throw e}finally{n?.close()}}function buildExecApprovalTurnSourceContext(e){return{turnSourceChannel:e.turnSourceChannel,turnSourceTo:e.turnSourceTo,turnSourceAccountId:e.turnSourceAccountId,turnSourceThreadId:e.turnSourceThreadId}}async function resolveCommandSpans(e){if(!e)return;try{const{resolveExecApprovalCommandSpans:t}=await loadExecApprovalCommandSpansRuntime();return await t(e)}catch{return}}function shouldSkipGeneratedCommandSpans(e){if(e.host===`gateway`&&process.platform===`win32`)return true;const t=e.commandArgv?.length?e.commandArgv:e.systemRunPlan?.argv;return t?.length?isUnsupportedShellWrapperArgv(t):false}async function buildHostApprovalDecisionParams(e){const t=e.commandHighlighting===true?e.commandSpans??(shouldSkipGeneratedCommandSpans(e)?void 0:await resolveCommandSpans(e.command??e.systemRunPlan?.commandText)):void 0;return{id:e.approvalId,...e.command?{command:e.command}:{},...e.commandArgv?{commandArgv:e.commandArgv}:{},systemRunPlan:e.systemRunPlan,env:e.env,cwd:e.workdir,nodeId:e.nodeId,host:e.host,security:e.security,ask:e.ask,warningText:e.warningText,commandSpans:t,...e.unavailableDecisions?.length?{unavailableDecisions:e.unavailableDecisions}:{},agentId:e.agentId,sessionKey:e.sessionKey,resolvedPath:e.resolvedPath,sessionId:e.sessionId,runId:e.runId,toolCallId:e.toolCallId,requireDeliveryRoute:e.requireDeliveryRoute,suppressDelivery:e.suppressDelivery===true||e.trigger===`cron`&&e.host!==`gateway`?true:void 0,deliverToApprovalClientsOnly:e.trigger===`cron`&&e.host===`gateway`?true:void 0,approvalReviewerDeviceIds:e.approvalReviewerDeviceIds,...buildExecApprovalTurnSourceContext(e),timeoutMs:DEFAULT_APPROVAL_TIMEOUT_MS,twoPhase:true}}async function registerExecApprovalRequestForHostOrThrow(e){try{return await registerExecApprovalRequest(await buildHostApprovalDecisionParams(e),e.approvalTransport)}catch(e){throw new Error(`Exec approval registration failed: ${String(e)}`,{cause:e})}}export{DEFAULT_APPROVAL_TIMEOUT_MS as a,DEFAULT_PENDING_MAX_OUTPUT as c,createApprovalSlug as d,resolveApprovalRunningNoticeMs as f,resolveRegisteredExecApprovalDecision as i,applyShellPath as l,ExecProcessPreflightError as m,isExecApprovalRunAbortedError as n,DEFAULT_MAX_OUTPUT as o,runExecProcess as p,registerExecApprovalRequestForHostOrThrow as r,DEFAULT_PATH as s,buildExecApprovalTurnSourceContext as t,buildApprovalPendingMessage as u};