UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,246 lines (1,245 loc) • 45 kB
import { l as normalizeOptionalString, m as readNonBlankString } from "./string-coerce-CCIiB4H7.mjs"; import { A as resolveExpiresAtMsFromDurationMs, o as asDateTimestampMs } from "./number-coercion-D6u-4YD8.mjs"; import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { r as runWithMainThreadTask } from "./main-thread-stall-BhUfYJnA.mjs"; import { s as formatErrorMessage } from "./error-coercion-hDrHOSGy.mjs"; import { n as safeParseJsonRecord } from "./json-coercion-CaJLaav-.mjs"; import { f as normalizeStringEntries } from "./string-normalization-DLmfYZXI.mjs"; import { t as killProcessTree } from "./kill-tree-DlMFq2XA.mjs"; import { u as redactToolPayloadText } from "./redact-Mj7pppxC.mjs"; import { t as LruCache } from "./lru-cache-wquJPIr-.mjs"; import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs"; import "./paths-DAcAg5aV.mjs"; import { t as formatErrorMessage$1 } from "./errors-BKzCeTYb.mjs"; import { c as omitGatewayCredentialEnv } from "./host-env-security-BrTYS4pH.mjs"; import { C as isSubagentSessionKey, b as isCronRunSessionKey, j as parseAgentSessionKey } from "./session-key-CqAyZeVk.mjs"; import { n as resolveRuntimeWorkerArgv } from "./runtime-worker-url-DRDkoS4J.mjs"; import { a as resolveRuntimeProcessEntrypointUrl } from "./runtime-process-url-CoHTemu-.mjs"; import { E as recordDiagnosticToolExecutionDeadline, i as emitDiagnosticEventWithTrustedTraceContext } from "./diagnostic-events-BjAH1Kbx.mjs"; import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs"; import { n as resolvePreferredOpenClawTmpDir } from "./tmp-openclaw-dir-Bf0oU1Cn.mjs"; import { i as withChildProcessOperation } from "./spawn-diagnostics-DBVI9KzR.mjs"; import { n as createLazyPromise } from "./lazy-promise-DiCvjz9w.mjs"; import { d as hasAgentRunContextExecutionOwner } from "./agent-run-registry-D7vkrqFT.mjs"; import { a as listAgentRunsForSession } from "./agent-run-registry-state-BFfw9a4W.mjs"; import { t as DEFAULT_EXEC_APPROVAL_TIMEOUT_MS } from "./exec-approvals-core-puBAw1bE.mjs"; import { l as withSystemEventOwner } from "./system-event-ownership-zDxyv2EM.mjs"; import { n as runWithoutOwnedSessionTranscriptWrites } from "./transcript-write-context-store-kFqld1UQ.mjs"; import { d as withExecRequestOwners, l as readExecRequestOwners, s as execRequestAbortSignal, u as retainExecRequestProcess } from "./exec-request-context-C8VKkMcB.mjs"; import { c as normalizeDeliveryContext } from "./delivery-context.shared-CRlipPTj.mjs"; import { d as enqueueSystemEventWithReceipt, t as SystemEventQueueFullError } from "./system-events-BFJiZPP0.mjs"; import { t as enqueueSessionEventForHost } from "./session-event-handoff-CC7Ui3SA.mjs"; import { o as resolveExecApprovalAllowedDecisions } from "./exec-approvals-policy-BGzNHuNm.mjs"; import { m as withoutGatewayToolCallerIdentity, o as getGatewayToolCallerIdentity, t as captureGatewayToolCallerAssertion } from "./gateway-caller-context-BNidAW8G.mjs"; import { a as followSessionEventTargetForHost, r as captureSessionEventTargetForHost } from "./session-event-target-BPiQeS30.mjs"; import { c as buildExecExitOutcome, d as joinExecFailureOutput, h as renderExecUpdateText, l as buildExecRuntimeErrorOutcome, o as appendExecTimeoutRetryGuidance, p as renderExecExitLabel } from "./bash-tools.exec-output-CrrdoikE.mjs"; import { t as formatFencedCodeBlock } from "./markdown-code-C5it6V4Q.mjs"; import { i as logWarn } from "./logger-CIwfuhOU.mjs"; import { n as createSessionSlug } from "./session-slug-CTgJwlm2.mjs"; import { c as resolveSafeTimeoutDelayMs } from "./timeouts-nwfOzsiL.mjs"; import "./exec-approvals-rOfoWejC.mjs"; import { A as chunkString, O as waitForExecSession, P as readEnvInt, S as recordNotifyOnExitRemoval, T as settleExecSessionFinalization, _ as markCancellationRequested, f as isProcessSessionIdTaken, j as clampWithDefault, n as addSession, o as createProcessSession, r as appendOutput, v as markExited, w as resolveProcessCleanupMs, x as processSessionInstanceId } from "./bash-process-registry-Dh1460VO.mjs"; import { t as formatDurationCompact } from "./format-duration-iMnO_MN6.mjs"; import { a as removePathPrepend, n as findPathKey, r as mergePathPrepend } from "./path-prepend-HpofbiEN.mjs"; import { n as recordAgentCleanupFailure } from "./run-cleanup-timeout-Bk3vN1Oh.mjs"; import { t as callGatewayTool } from "./gateway-DL_Nxi-v.mjs"; import { r as captureAgentToolSourceExecutionGuard, s as runWithAgentToolSourceExecutionScope } from "./agent-tool-source-execution-guard-CD-ezY7E.mjs"; import { t as markToolDecisionRecorded } from "./agent-tools.before-tool-call.decision-NP6t8oB5.mjs"; import { n as spawnProcess } from "./spawn-utils-DLbtt13t.mjs"; import { t as isApprovalNotFoundError } from "./approval-errors-byE8UOsC.mjs"; import { r as resolveHostExecMemoryLimit, t as getProcessSupervisor } from "./supervisor-BeB1eaLi.mjs"; import { n as createStreamingBinaryOutputSanitizer, o as getShellConfig } from "./shell-utils-rrqUwXNm.mjs"; import { t as prependShellPath } from "./login-shell-path-carrier-xD8JTcx9.mjs"; import { t as buildGitHubExecLaunchArgv } from "./github-exec-launch-BPrPEpvY.mjs"; import { t as resolveEventSessionKeyForPolicy } from "./event-session-routing-QCFK39bz.mjs"; import { n as isUnsupportedShellWrapperArgv } from "./format-B36Ju1QI.mjs"; import { a as registerSecretEgressProxyProcess } from "./registry-WDs449Ix.mjs"; import { constants } from "node:fs"; import path from "node:path"; import { createHash, randomBytes } from "node:crypto"; import fs$1 from "node:fs/promises"; import os from "node:os"; import { AsyncLocalStorage } from "node:async_hooks"; //#region src/agents/bash-process-id.ts const bootId = randomBytes(6).toString("hex"); function createProcessSessionId() { return `${createSessionSlug((e) => isProcessSessionIdTaken(`${e}:${bootId}`))}:${bootId}`; } function missingProcessMessage(e) { const t = /:([a-f0-9]{12})$/.exec(e)?.[1]; if (t && t !== bootId) return `Process ${e} was started before the Gateway restarted and is no longer tracked; rerun it if still needed. Check saved output and side effects before repeating work.`; return `Process ${e} is no longer tracked or is outside this session's scope. Handles are lost when the Gateway restarts; rerun it if still needed after checking saved output and side effects.`; } //#endregion //#region 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 } : {} }); } //#endregion //#region 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; /** Keep capture and replay on the same shell environment policy. */ 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; } //#endregion //#region 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("\n"); 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("\n"); 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("\n"); } 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("\n"); } 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("\n"); } 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("\n"); } 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 {} })); } //#endregion //#region src/agents/bash-tools.exec-host-spawn.ts async function prepareHostExecSpawn(e) { return await runWithMainThreadTask("exec:spawn-prepare", async () => { const { shell: t, args: n } = 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" }; }); } /** Final launch env; host launches re-apply the credential names published right now. */ function resolveExecLaunchEnv(e, t, n) { const r = e && !t ? omitGatewayCredentialEnv(e) : e; return n ? { ...r, ...n } : r; } //#endregion //#region 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; } }; /** Retain launch custody separately from process lifetime and proven-no-initiation fallback. */ 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(); } }; } }; } //#endregion //#region src/agents/bash-tools.exec-notify.ts /** Owns captured destinations and cancellation for background exec completion notifications. */ function enqueueExecExitNotification(e, t, n, r = {}) { return enqueueSessionEventForHost(e, { ...r, agentId: t.agentId, sessionKey: t.sessionKey, source: "exec", contextKey: r.contextKey ?? `exec:${n}`, sourceTurnId: `exec:${n}`, expectedTarget: t }); } /** Capture the original session before spawning work that may outlive its turn. */ function prepareExecExitNotification(e, t) { if (!e.notifyOnExit || !e.sessionKey || t || isSubagentSessionKey(e.sessionKey)) return; const n = isCronRunSessionKey(e.sessionKey) ? e.sessionKey : resolveEventSessionKeyForPolicy(e.sessionKey, e.eventRouting ?? {}); const r = e.agentId ?? parseAgentSessionKey(n)?.agentId; if (!r) return; return captureSessionEventTargetForHost(r, n, { operatorAuthority: getGatewayToolCallerIdentity()?.operatorAuthority, retainRequesterOwner: true }).then((t) => { if (isCronRunSessionKey(n)) { const r = listAgentRunsForSession({ sessionKey: n, sessionId: t.sessionId }); e.assertExitNotificationAcceptanceCurrent = () => { if (!r.some((e) => hasAgentRunContextExecutionOwner(e.runId))) throw new Error("Originating cron run ended; inspect the result with process log"); }; } e.notifySessionTarget = t; }, (t) => { e.notifyOnExit = false; logWarn(`exec: automatic completion has no destination (${formatErrorMessage$1(t)}); use process poll.`); }); } /** A new conversation does not get the old command's wake; it gets a visible note instead. */ async function withholdExecExitNotification(e, t, n) { const r = n.status === "deleted" ? "the conversation was deleted" : "the conversation was reset, rewound or moved to a new session after the command started"; logWarn(`exec: completion ${e.id} withheld (${r}); inspect the process result.`); if (n.status === "deleted") return; const i = `exec-withheld:${processSessionInstanceId(e)}`; try { const { appendSessionTranscriptReport: a } = await import("./session-accessor-DTtHAol5.mjs"); const o = await runWithoutOwnedSessionTranscriptWrites(() => a({ agentId: t.agentId, sessionKey: t.sessionKey, storePath: t.storePath, sessionId: n.sessionId, expectedLifecycleRevision: n.lifecycleRevision }, { kind: "custom", customTypes: ["run-failed-before-reply"], selectReport: (t) => isRecord(t?.details) && t.details.runId === i ? void 0 : { customType: "run-failed-before-reply", display: true, excludeFromContext: true, content: `Background command result withheld (${e.id}, ${renderExecExitLabel(e)}): ${r}. Its output stays in process log.`, details: { runId: i, processId: e.id } } })); if (!o.ok) throw new Error(`transcript refused the note: ${o.error.code}`); } catch (t) { logWarn(`exec: completion ${e.id} withheld note failed (${formatErrorMessage$1(t)}).`); } } async function maybeNotifyOnExit(e, t, n) { if (e.exitNotified) return; if (!e.backgrounded || !e.notifyOnExit || e.requestCancelled || readExecRequestOwners(e)?.some((e) => e.signal.aborted) || e.terminalPollObserved) return; const r = e.sessionKey?.trim(); if (!r) return; e.exitNotified = true; if (e.exitReason === "manual-cancel" && e.finalizationFailed !== true) return; const i = e.tail; const a = i.trim(); if (t === "completed" && e.exitCode === 0 && !a && e.notifyOnExitEmptySuccess !== true) return; const o = `Exec ${t} (${e.id.slice(0, 8)}, ${renderExecExitLabel(e)}, ${formatDurationCompact((e.endedAt ?? Date.now()) - e.startedAt) ?? "0s"})`; const s = !a ? `${o} with no output.` : e.totalOutputChars > i.length ? `${o}, last ${i.length} of ${e.totalOutputChars} output chars (${e.totalOutputChars > e.aggregated.length ? `process log keeps the last ${e.aggregated.length}; earlier output was discarded` : "process log has the rest"}):\n${a}` : `${o}:\n${a}`; const c = appendExecTimeoutRetryGuidance(s, e.exitReason); const l = e.notifySessionTarget?.sessionKey ?? resolveEventSessionKeyForPolicy(r, e.eventRouting); const u = withExecRequestOwners({ sessionKey: l, contextKey: `exec:${e.id}`, deliveryContext: e.notifyDeliveryContext }, readExecRequestOwners(e)); if (!n && !isSubagentSessionKey(r)) { if (!(e.agentId ?? parseAgentSessionKey(l)?.agentId) || !e.notifySessionTarget) { logWarn(`exec: completion ${e.id} has no admitted session destination; inspect its process result.`); return; } const t = e.notifySessionTarget; try { const n = await followSessionEventTargetForHost(t); if (n.status !== "current") { await withholdExecExitNotification(e, t, n); return; } } catch (t) { logWarn(`exec: completion ${e.id} could not read its session (${formatErrorMessage$1(t)}).`); } try { const n = enqueueExecExitNotification(c, t, processSessionInstanceId(e), { ...u, sourceRunId: e.originRunId, assertAcceptanceCurrent: e.assertExitNotificationAcceptanceCurrent }); recordNotifyOnExitRemoval(e, n.cancel); n.settled.then(async (e) => { if (e.status === "failed") logWarn(`exec: completion delivery failed (${e.error}); inspect the process result.`); }); } catch (e) { logWarn(`exec: completion was not admitted (${formatErrorMessage$1(e)}); inspect the process result.`); } return; } try { const t = enqueueSystemEventWithReceipt(c, e.agentId ? withSystemEventOwner(u, e.agentId) : u, { allowDuplicate: true }); if (t) recordNotifyOnExitRemoval(e, t); } catch (t) { if (!(t instanceof SystemEventQueueFullError)) throw t; logWarn(`exec: completion ${e.id} was not queued (${t.message}); use process poll.`); } } //#endregion //#region src/agents/bash-tools.exec-settlement.ts /** Settle the process owner's ledger and notifications before releasing scope joins. */ async function settleExecProcessExit({ session: e, outcome: t, onSettledBeforeNotify: n, notifyOnExit: r, failureOutcome: i }) { let a = t; const { exitCode: o, exitSignal: s, status: c, exitReason: l, noOutputTimedOut: u } = a; const markProcessExited = () => markExited(e, o, s, c, l, u); try { const t = !e.exited; const i = n?.(a); if (i instanceof Promise) await i; if (t) { markProcessExited(); await r(e, a.status); } } catch (t) { e.finalizationFailed = true; a = i(t); const r = n?.(a); if (r instanceof Promise) await r; } finally { try { if (!e.exited) markProcessExited(); } finally { delete e.sessionKey; delete e.eventRouting; delete e.notifyDeliveryContext; delete e.notifySessionTarget; delete e.notifyOnExit; delete e.notifyOnExitEmptySuccess; if (e.finalizationFailed || e.cleanupUncertain) for (const t of readExecRequestOwners(e) ?? []) t.cleanupUncertain = true; settleExecSessionFinalization(e); } } return a; } //#endregion //#region src/agents/bash-tools.exec-runtime.ts /** * Spawns host/sandbox processes, manages session updates/backgrounding, * approval messaging constants, environment safety, and exit outcome shaping. */ function resolveExecTimeoutMs(e) { if (typeof e !== "number" || !Number.isFinite(e) || e <= 0) return; return resolveSafeTimeoutDelayMs(e * 1e3); } /** Default retained aggregate output cap for exec sessions. */ const DEFAULT_MAX_OUTPUT = clampWithDefault(readEnvInt("OPENCLAW_BASH_MAX_OUTPUT_CHARS", "PI_BASH_MAX_OUTPUT_CHARS"), 2e5, 1e3, 2e5); /** Default pending output cap for poll/update buffers. */ const DEFAULT_PENDING_MAX_OUTPUT = clampWithDefault(readEnvInt("OPENCLAW_BASH_PENDING_MAX_OUTPUT_CHARS"), 3e4, 1e3, 2e5); /** Fallback PATH used when the process environment has no PATH. */ 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; /** Gateway request timeout for approval registration/wait calls. */ const DEFAULT_APPROVAL_REQUEST_TIMEOUT_MS = DEFAULT_APPROVAL_TIMEOUT_MS + 1e4; const DEFAULT_APPROVAL_RUNNING_NOTICE_MS = 1e4; const APPROVAL_SLUG_LENGTH = 8; const UNCONFIRMED_DESCENDANT_CLEANUP_NOTE = "OpenClaw could not confirm that every process started by this command stopped; a detached process (such as a daemon or tmux server) may still be running. Use background: true for long-running services."; /** Merges shell-discovered PATH entries into an exec environment. */ 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; } /** Creates the short approval id shown in `/approve` prompts. */ function createApprovalSlug(e) { return e.slice(0, APPROVAL_SLUG_LENGTH); } /** Builds the user-facing approval-pending message for foreground exec. */ 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("\n"); } 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); } /** Starts a host or sandbox exec process and registers it for polling/backgrounding. */ 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, 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); if (S) await S; let C = t && AsyncLocalStorage.bind(t); let w = n; let T = s.approvalTransport ? () => { r?.(); s.approvalTransport?.assertExecution({ command: s.command, execCommand: _, cwd: s.workdir, env: s.env, pty: s.usePty }); } : r; let E = 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 D = createStreamingBinaryOutputSanitizer((e) => { if (e === "?1h" || e === "?1l") x.cursorKeyMode = e === "?1h" ? "application" : "normal"; else if (L && (e === "6n" || e === "?6n")) F?.stdin?.write("\x1B[1;1R"); }); const O = createStreamingBinaryOutputSanitizer(); const handleOutput = (e, t) => (n) => { for (const r of chunkString(t(n))) { appendOutput(x, e, r); emitUpdate(); } }; 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: k }); }; const runtimeErrorOutcome = (e) => buildExecRuntimeErrorOutcome({ error: e, aggregated: x.aggregated.trim(), durationMs: Date.now() - m }); const finalizeAndSettleSession = async (e) => { P?.revoke(); let t = e; x.finalizing = true; try { if (!s.sandbox && F?.waitForExtinction) { F.cancel(); let n; try { n = await F.waitForExtinction(); } catch (n) { if (e.status !== "completed" || x.requestCancelled) throw n; x.cleanupUncertain = true; recordAgentCleanupFailure(); logWarn(`exec: descendant cleanup after completion was not confirmed (${redactToolPayloadText(formatErrorMessage(n))}).`); appendOutput(x, "stderr", `\n${UNCONFIRMED_DESCENDANT_CLEANUP_NOTE}\n`); t = { ...e, aggregated: joinExecFailureOutput(e.aggregated, UNCONFIRMED_DESCENDANT_CLEANUP_NOTE) }; } x.cleanupUncertain ||= n?.status === "uncertain"; if (x.requestCancelled && x.cleanupUncertain) throw new Error("Command descendant cleanup could not be confirmed"); } if (e.exitReason !== "exit") beginSandboxTermination(); await N; const [n] = await Promise.allSettled([finalizeSandboxExec({ status: e.status, exitCode: e.exitCode, timedOut: e.timedOut })]); const r = N ? await N : void 0; const i = r ? [r.error] : []; if (n.status === "rejected") i.push(n.reason); if (i.length > 0) { const e = i.map((e) => formatErrorMessage(e)).join("\n"); throw new AggregateError(i, e); } } catch (n) { x.finalizationFailed = true; recordAgentCleanupFailure(); const r = redactToolPayloadText(formatErrorMessage(n)); if (e.status === "completed") t = runtimeErrorOutcome(r); else { t = { ...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`); t.aggregated = x.aggregated.trim(); } finally { t = await settleExecProcessExit({ session: x, outcome: t, onSettledBeforeNotify: E, notifyOnExit: (e, t) => maybeNotifyOnExit(e, t, s.subagentSession === true), failureOutcome: runtimeErrorOutcome }); } return t; }; 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 }); k = t.finalizeToken; A = t.assertCurrent; 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; 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 I = createExecLaunchLifecycle(i, a); const onOperatorRevoked = () => F?.cancel("manual-cancel"); const releaseExecutionContext = () => { E = void 0; f?.removeEventListener("abort", onOperatorRevoked); p?.(); p = void 0; c?.removeEventListener("abort", onRequestCancelled); }; let L = s.usePty && !s.sandbox; const emitCompleted = (e) => emitExecProcessCompleted({ command: s.command, mode: L ? "pty" : "child", outcome: e, sessionKey: s.sessionKey, target: v }); const assertPreSpawnAuthorized = () => I.prepare(u, w); const spawn = (e) => runWithAgentToolSourceExecutionScope(u, async () => { const t = u; const n = d?.assertCurrent; const r = A; const i = T; const assertCurrent = () => { t?.(); n?.(); r?.(); }; assertCurrent(); i?.(); const a = s.secretEgressBindings ? await registerSecretEgressProxyProcess(s.secretEgressBindings) : void 0; P = a; try { return await withChildProcessOperation("agent.exec", () => withoutGatewayToolCallerIdentity(() => y.spawn({ ...e, env: resolveExecLaunchEnv(e.env, Boolean(s.sandbox), a?.env), onCancel: () => { beginSandboxTermination(); a?.revoke(); }, assertCurrent, beforeSpawn: i, initiateSpawn: I.wrap(assertCurrent, i) }))); } catch (e) { a?.revoke(); throw e; } }); try { u?.(); d?.assertCurrent(); p = d?.retain?.(); const e = await prepareSpawnSpec(); L = e.mode === "pty"; const t = { executionIntent: "agent-tool", runId: g, ...s.sandbox ? { cleanupOwnership: "external", exactEnv: true } : {}, scopeKey: s.scopeKey, cwd: e.cwd ?? s.workdir, env: e.env, timeoutMs: h, memoryLimitBytes: s.sandbox ? void 0 : resolveHostExecMemoryLimit(), captureOutput: false, onStdout: handleOutput("stdout", D), onStderr: handleOutput("stderr", O) }; await assertPreSpawnAuthorized(); if (e.mode === "pty") try { F = await spawn({ ...t, mode: "pty", argv: e.argv }); } catch (e) { if (I.initiated) { I.release(); throw e; } I.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); L = false; await assertPreSpawnAuthorized(); } if (!F) F = await spawn({ ...t, mode: "child", argv: e.argv, stdinMode: e.stdinMode }); f?.addEventListener("abort", onOperatorRevoked, { once: true }); if (f?.aborted) onOperatorRevoked(); } catch (e) { I.release(); C = void 0; emitCompleted(await finalizeAndSettleSession(runtimeErrorOutcome(e)).finally(releaseExecutionContext)); throw e; } finally { I.dispose(); w = void 0; T = void 0; u = void 0; d = void 0; A = void 0; } x.processActivity = F.activity; recordDiagnosticToolExecutionDeadline(F.activity.deadlineAtMs); x.stdin = F.stdin; x.pid = F.pid; const R = F; const z = withoutGatewayToolCallerIdentity(async () => { try { let e; try { const t = await R.wait(); e = buildExecExitOutcome({ exit: t, 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 t = await finalizeAndSettleSession(e); emitCompleted(t); return t; } finally { releaseExecutionContext(); } }); return { session: x, startedAt: m, pid: x.pid ?? void 0, promise: z, kill: () => { F?.cancel("manual-cancel"); }, disableUpdates: () => { C = void 0; } }; } //#endregion //#region src/agents/bash-tools.exec-approval-request.ts /** * Registers two-phase approval requests with the gateway, waits for decisions, * and builds host/node payloads with optional command highlighting. */ const loadExecApprovalCommandSpansRuntime = createLazyPromise(() => import("./bash-tools.exec-approval-request.runtime.js"), { 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; } /** Registers a two-phase exec approval request with the gateway. */ 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 }; } /** Uses a pre-resolved decision or waits for the registered approval id. */ 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(); } } /** Builds originating channel context for approval delivery/routing. */ 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 }; } /** Registers a host/node approval request and wraps failures for exec callers. */ 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 }); } } //#endregion export { DEFAULT_APPROVAL_TIMEOUT_MS as a, DEFAULT_PENDING_MAX_OUTPUT as c, createApprovalSlug as d, resolveApprovalRunningNoticeMs as f, missingProcessMessage as h, 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 };