openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
4,391 lines • 160 kB
JavaScript
import { c as normalizeOptionalLowercaseString, l as normalizeOptionalString, m as readNonBlankString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { A as resolveExpiresAtMsFromDurationMs } from "./number-coercion-D6u-4YD8.mjs";
import { l as isRecord, r as asNullableRecord } from "./record-coerce-CVPuDqcc.mjs";
import { f as normalizeStringEntries } from "./string-normalization-DLmfYZXI.mjs";
import { r as buildExecRoutingEnv, t as OPENCLAW_CLI_ENV_VAR } from "./openclaw-exec-env-BPYcT7Dr.mjs";
import { s as safeRealpathSync } from "./boundary-path-C2gXEiXe.mjs";
import { t as LruCache } from "./lru-cache-wquJPIr-.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import { c as safeStatSync, r as isPathInside } from "./path-guards-TIjxtj6H.mjs";
import { i as createAbortError$1 } from "./src-BPmQBLJp.mjs";
import "./abort-signal-D4Q6SEw7.mjs";
import { t as sleep } from "./sleep-CkI3nkiJ.mjs";
import "./paths-DAcAg5aV.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { i as resolveEnvironmentValue, n as mergeProcessEnv } from "./process-env-DVJdcOcM.mjs";
import { n as isDangerousHostEnvOverrideVarName, r as isDangerousHostEnvVarName, s as normalizeHostOverrideEnvVarKey, u as sanitizeHostExecEnvWithDiagnostics } from "./host-env-security-BrTYS4pH.mjs";
import { r as getShellPathFromLoginShell, s as resolveShellEnvFallbackTimeoutMs } from "./shell-env-Dbjy7T84.mjs";
import { j as parseAgentSessionKey, l as resolveAgentIdFromSessionKey } from "./session-key-CqAyZeVk.mjs";
import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs";
import { l as emitTrustedSecurityEvent } from "./diagnostic-events-BjAH1Kbx.mjs";
import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs";
import { t as createLazyImportLoader } from "./lazy-promise-DiCvjz9w.mjs";
import { n as captureOpenClawStateReadWorkerContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs";
import { a as emitAgentEvent } from "./agent-events-BdfWYmot.mjs";
import { f as resolveExecutionTargetTrustPath, g as resolveExecWrapperTrustPlan, s as resolveApprovalAuditTrustPath } from "./exec-command-resolution-DaBYjPqy.mjs";
import { n as splitCommandArgs, r as splitShellArgs } from "./shell-argv-CjhAXJXb.mjs";
import { d as isBlockedShellWrapperCommand, u as hasPosixShellStartupBeforeInlineCommand } from "./shell-wrapper-resolution-BEK558J4.mjs";
import { r as normalizeExecAsk, u as resolveExecModePolicy } from "./exec-approvals-core-puBAw1bE.mjs";
import { n as APPROVALS_SCOPE, u as WRITE_SCOPE } from "./operator-scopes-CULmYfyY.mjs";
import { r as omitGatewayAgentCliPath } from "./openclaw-cli-shim-spskOd_w.mjs";
import { t as GatewayDrainingError, w as runWithGatewayIndependentRootWorkAdmission } from "./gateway-work-admission-79pid1hQ.mjs";
import { a as getActiveSecretsRuntimeConfigSnapshot } from "./runtime-state-Dq_fFDZp.mjs";
import { l as readExecRequestOwners, o as captureExecRequestOwners } from "./exec-request-context-C8VKkMcB.mjs";
import { c as normalizeDeliveryContext } from "./delivery-context.shared-CRlipPTj.mjs";
import { l as getDiagnosticSessionState } from "./diagnostic-runtime-BxwnWXDu.mjs";
import { a as EXEC_TOOL_DISPLAY_SUMMARY, o as PROCESS_TOOL_DISPLAY_SUMMARY } from "./tool-catalog-C1ALpCJD.mjs";
import { a as requiresExecApproval, c as resolveExecApprovalUnavailableDecisions, n as maxAsk, o as resolveExecApprovalAllowedDecisions, r as minSecurity } from "./exec-approvals-policy-BGzNHuNm.mjs";
import { m as withoutGatewayToolCallerIdentity } from "./gateway-caller-context-BNidAW8G.mjs";
import { c as attachInternalToolResultAcknowledgement } from "./internal-hooks-Ch3rqxs-.mjs";
import { r as markToolExecutionNotStarted } from "./tool-effect-receipt-BbbEwqBS.mjs";
import { r as textResult, t as failText } from "./tool-results-CcV0sxnb.mjs";
import { t as bindAgentToolAvailability } from "./agent-tool-availability-ecKW8hOH.mjs";
import { n as ToolInputError } from "./tool-input-error-B1hgavSw.mjs";
import "./common-njQNtpnW.mjs";
import { f as normalizeNotifyOutput, h as renderExecUpdateText, l as buildExecRuntimeErrorOutcome, o as appendExecTimeoutRetryGuidance, p as renderExecExitLabel, r as EXEC_RETENTION_CAP_NOTE, s as buildBackgroundExecFollowUp, t as EXEC_MANUAL_COLLECTION_FOLLOW_UP, u as hasExitWake } from "./bash-tools.exec-output-CrrdoikE.mjs";
import { D as formatExecDeniedReasonMessage, k as isExecDeniedResultText } from "./user-copy-DFvWpx47.mjs";
import { s as withPreparedSessionCapabilityRead } from "./subagent-session-store--G7wm9iV.mjs";
import { i as logWarn, r as logInfo } from "./logger-CIwfuhOU.mjs";
import { a as resolveStoredSubagentCapabilities, t as isSubagentEnvelopeSession } from "./subagent-capabilities-D82nSYzB.mjs";
import { n as getGlobalHookRunner } from "./hook-runner-global-DmYyIVDp.mjs";
import { c as prepareGitHubToolEnvironment } from "./github-tool-identity-41SK6r8O.mjs";
import { t as resolveExecApprovalsFromFileInternal } from "./exec-approvals-resolver-C6IwmycS.mjs";
import { a as loadExecApprovalsReadOnlyAsync, m as prepareCronExecHostPolicyUse } from "./exec-approvals-store-BUZ9uOWF.mjs";
import { m as buildEnforcedShellCommand, n as evaluateShellAllowlistWithAuthorization } from "./exec-approvals-allowlist-f3-u9Y6p.mjs";
import "./exec-wrapper-resolution-BXAtcqj7.mjs";
import { c as describeInterpreterInlineEval, o as detectInlineEvalInSegments } from "./risks-CqlFotky.mjs";
import { n as countObsoleteGeneratedExecApprovals, t as countObsoleteGeneratedExecApprovalRules } from "./exec-approvals-generated-migration-BCmbxD17.mjs";
import { a as hasDurableExecApproval, d as resolveDurableExecApprovalRequirement, i as createExecApprovalPolicySnapshot, l as resolveAllowAlwaysPatternCoverage, o as hasExactCommandDurableExecApproval, s as hasNodeCommandAllowAlwaysMarker, u as resolveAllowAlwaysPersistenceDecision } from "./exec-approvals-authorization.kernel-DITNT1Lg.mjs";
import { n as resolveExecApprovalsLocked, r as commitExecAuthorizationLocked } from "./exec-approvals-rOfoWejC.mjs";
import { n as resolveExecElevatedMode, r as resolveExecHost } from "./bash-tools.exec-target-DBNJnOXQ.mjs";
import { n as sanitizeEnvVars } from "./sanitize-env-vars-DJC8I4rj.mjs";
import { E as tail, F as sliceLogLines, I as truncateMiddle, M as coerceEnv, N as deriveSessionName, P as readEnvInt, a as compareProcessSessionStartOrder, b as prepareSessionPoll, d as hasPendingPollDelivery, g as markBackgrounded, h as listRunningSessions, j as clampWithDefault, k as buildSandboxEnv, l as getFinishedSession, m as listFinishedSessions, s as deleteSession, t as acknowledgeNotifyOnExit, u as getSession } from "./bash-process-registry-Dh1460VO.mjs";
import { t as resolveEligibleNodeFromList } from "./node-resolve-CkGq9hyv.mjs";
import { n as GatewayProtocolRequestTimeoutError, t as GatewayProtocolRequestError } from "./protocol-request-CsClAJsG.mjs";
import { t as formatDurationCompact } from "./format-duration-iMnO_MN6.mjs";
import { i as normalizePathPrepend, t as applyPathPrepend } from "./path-prepend-HpofbiEN.mjs";
import { n as getInstallationTarget, r as installationTargetEnv, t as LOCAL_INSTALLATION_TARGET_UNSUPPORTED } from "./installation-target-context-C_xR1SHA.mjs";
import { n as assertSandboxPath } from "./sandbox-paths-CGD5HJYL.mjs";
import { s as stripMalformedXmlArgValueSuffixFromKeys } from "./agent-tools.params-D3Fjhk01.mjs";
import { a as resolveExecApprovalInitiatingSurfaceStateAsync } from "./exec-approval-surface-B1PpwJWS.mjs";
import { t as callGatewayTool } from "./gateway-DL_Nxi-v.mjs";
import { t as SYSTEM_RUN_EXECUTION_CONTEXT_CAPABILITY } from "./system-run-execution-context-UpbI778p.mjs";
import { r as captureAgentToolSourceExecutionGuard, s as runWithAgentToolSourceExecutionScope } from "./agent-tool-source-execution-guard-CD-ezY7E.mjs";
import { t as isApprovalNotFoundError } from "./approval-errors-byE8UOsC.mjs";
import { t as readNodePermissionError } from "./node-permission-error-FsjZ46I7.mjs";
import { r as resolveExecSafeBinRuntimePolicy } from "./exec-safe-bin-runtime-policy-DUQ-JlOU.mjs";
import { n as describeExecTool, r as describeProcessTool } from "./bash-tools.descriptions-CjRLwO0Y.mjs";
import { a as createExecSchema, c as processSchema, n as resolveExecDefaultTimeoutSec, o as execSchema, r as resolveNodeExecTimeouts, t as createExecToolExecutionTimeoutResolver } from "./exec-tool-timeout-CpkOuB67.mjs";
import { r as getAgentToolExecutionContext } from "./tool-execution-context-D0eUSg2-.mjs";
import { n as resolveSystemRunCommandRequest, t as extractShellCommandFromArgv } from "./system-run-command-Al2Xy1OR.mjs";
import { c as prepareSystemRunMutableFileBinding, u as revalidateSystemRunMutableFileBinding } from "./system-run-approval-binding-B3btPgad.mjs";
import { n as captureApprovedCwdSnapshotSync, r as revalidateApprovedCwdSnapshot, t as APPROVAL_CWD_DRIFT_DENIED_MESSAGE } from "./system-run-cwd-binding-RQPTyu1g.mjs";
import { a as defaultExecAutoReviewer, c as resolveExecAutoReviewDecision, n as EXEC_AUTO_REVIEW_DISPATCH_IDENTITY_WARNING, o as formatExecAutoReviewAssessment, r as EXEC_AUTO_REVIEW_SHELL_STARTUP_WARNING } from "./exec-auto-review-CaqSrKQR.mjs";
import { t as resolveUnpinnedAutoApprovalEligibility } from "./exec-auto-approval-eligibility-Dg9TxKJk.mjs";
import { n as buildReviewedShellCommandFromPlan, t as buildAuthorizedShellCommandFromPlan } from "./exec-authorization-render-Bn4BVITQ.mjs";
import { o as buildExecApprovalUnavailableReplyPayload } from "./exec-approval-reply-CfpNUvnC.mjs";
import { a as isConfirmedRequestedStop, t as cancelBackgroundExecSession } from "./bash-process-control-aLfvOIsE.mjs";
import { t as createProcessToolScope } from "./bash-process-scope-B7TaQfLU.mjs";
import { n as abortable } from "./abortable-z1NE23aa.mjs";
import { n as listNodes, o as resolveNodeIdFromList } from "./nodes-utils-B4u6gtyR.mjs";
import { t as ProcessToolOutputSchema } from "./bash-tools.process-schema-UWH4XghY.mjs";
import { r as isSecretEgressProxyActive } from "./registry-WDs449Ix.mjs";
import { a as DEFAULT_APPROVAL_TIMEOUT_MS, c as DEFAULT_PENDING_MAX_OUTPUT, d as createApprovalSlug, f as resolveApprovalRunningNoticeMs, h as missingProcessMessage, i as resolveRegisteredExecApprovalDecision, l as applyShellPath, m as ExecProcessPreflightError, n as isExecApprovalRunAbortedError, o as DEFAULT_MAX_OUTPUT, p as runExecProcess, r as registerExecApprovalRequestForHostOrThrow, s as DEFAULT_PATH, t as buildExecApprovalTurnSourceContext, u as buildApprovalPendingMessage } from "./bash-tools.exec-approval-request-BDrMJ1hF.mjs";
import { a as buildExecApprovalFollowupTarget, i as buildExecApprovalDeniedToolResult, o as buildExecAutoReviewDeniedToolResult, s as formatExecApprovalContinuationSourceOutput } from "./bash-tools.exec-approval-output-Cb90XzcX.mjs";
import { o as registerExecApprovalFollowupRuntimeHandoff } from "./bash-tools.exec-approval-followup-state-CdzwahWm.mjs";
import { n as rejectUnsafeExecControlShellCommand, r as rejectUnsafeExecLiveStateSqliteShellCommand } from "./exec-control-command-guard-zwBmQEo0.mjs";
import { t as lookupCronRunExecSource } from "./cron-run-exec-source-BiohUkNP.mjs";
import { t as buildCronExecOperationBinding } from "./operator-approval-standing-grants-BXBRZZUP.mjs";
import { g as validateCronStandingGrant, t as consumeCronStandingGrant } from "./operator-approval-store-lZFt_sJ1.mjs";
import { t as parsePreparedSystemRunPayload } from "./system-run-approval-context-DkkOMgNU.mjs";
import { n as buildExecForegroundResult, r as resolveExecReviewerDefaults, t as attachExecApprovalReview } from "./bash-tools.exec-support-Cf0csuPW.mjs";
import { n as recordCommandPoll, r as resetCommandPollCount } from "./command-poll-backoff-F3lgfbeX.mjs";
import path from "node:path";
import crypto, { randomUUID } from "node:crypto";
import fs from "node:fs/promises";
//#region src/agents/bash-tools.exec-cron-grant.ts
/** Consumption accounts once; live run and host-policy checks gate native initiation. */
async function prepareCronStandingGrantConsumption(e, t, n) {
const r = t.standingGrantAuthority;
if (!r || !e.runId) return;
const i = e.runId;
const { context: a } = r;
const o = {
agentId: t.agentId,
cronJobId: t.jobId,
jobConfigRevision: t.jobConfigRevision,
operationBinding: buildCronExecOperationBinding({
command: e.command,
cwd: e.workdir,
env: e.requestedEnv
}),
handle: { ...r.handle }
};
const s = await prepareCronExecHostPolicyUse(a, {
...n,
agentId: t.agentId,
bypassHostApprovalFloors: e.bypassHostApprovalFloors
});
const assertOccurrence = () => {
if (lookupCronRunExecSource(i) !== t) throw new Error("Cron run is no longer active");
r.assertCurrent();
s.assertCurrent();
};
let c;
try {
assertOccurrence();
c = await validateCronStandingGrant({
...o,
databaseOptions: {
path: a.admission.databasePath,
env: a.environment
},
assertCurrent: assertOccurrence
});
assertOccurrence();
} catch (e) {
s.release();
throw e;
}
if (c.outcome !== "consumed") {
s.release();
return;
}
const l = {
grantId: c.grant.grantId,
mintedByApprovalId: c.grant.mintedByApprovalId
};
let u;
let d = false;
let f = false;
let p;
const releaseSpawn = (e) => {
f = false;
if (e !== "retry") {
d = true;
s.release();
}
};
const assertCurrent = () => {
if (d || !f) throw new Error("Cron standing-grant launch is no longer active");
assertOccurrence();
p?.throwIfAborted();
if (u?.expiresAtMs != null && u.expiresAtMs <= Date.now()) throw new Error("Cron standing grant expired before launch");
};
return {
assertCurrent,
releaseSpawn,
initiateSpawn(e, t) {
assertCurrent();
try {
return s.initiate(e, t);
} finally {
releaseSpawn();
}
},
async consume(e) {
if (d) throw new Error("Cron standing-grant launch cannot be replayed");
releaseSpawn("retry");
p = e;
try {
const assertAttempt = () => {
assertOccurrence();
e?.throwIfAborted();
if (u?.expiresAtMs != null && u.expiresAtMs <= Date.now()) throw new Error("Cron standing grant expired before launch");
};
const t = await consumeCronStandingGrant(a, {
...o,
expectedGrant: l,
recordUse: u === void 0
}, assertAttempt);
if (t.outcome !== "consumed") {
releaseSpawn();
return t;
}
u = t.grant;
f = true;
assertCurrent();
return t;
} catch (e) {
releaseSpawn();
throw e;
}
}
};
}
//#endregion
//#region src/agents/bash-tools.exec-host-gateway.output.ts
function formatBytes(e) {
if (typeof e !== "number" || !Number.isFinite(e)) return null;
return `${Math.max(0, Math.round(e))} bytes`;
}
function formatDiagnosticsExportSuccess(e) {
const t = e.trim();
if (!t) return "Diagnostics export completed, but no JSON output was returned.";
try {
const e = JSON.parse(t);
if (!isRecord(e)) return t;
const n = isRecord(e.manifest) ? e.manifest : {};
const r = [
"Diagnostics export created.",
"",
"Local Gateway bundle:"
];
const i = typeof e.path === "string" ? e.path : "";
if (i) r.push(`Path: ${i}`);
const a = formatBytes(e.bytes);
if (a) r.push(`Size: ${a}`);
if (typeof n.generatedAt === "string") r.push(`Generated at: ${n.generatedAt}`);
if (typeof n.openclawVersion === "string") r.push(`OpenClaw version: ${n.openclawVersion}`);
const o = Array.isArray(n.contents) ? n.contents : [];
if (o.length > 0) {
r.push("", `Contents (${o.length} files):`);
for (const e of o.slice(0, 12)) {
if (!isRecord(e)) continue;
const t = typeof e.path === "string" ? e.path : "";
if (!t) continue;
const n = formatBytes(e.bytes);
r.push(`- ${n ? `${t} (${n})` : t}`);
}
if (o.length > 12) r.push(`- ... ${o.length - 12} more`);
}
const s = isRecord(n.privacy) ? n.privacy : null;
if (s) {
const e = ["Privacy:"];
if (typeof s.payloadFree === "boolean") e.push(`- payload-free: ${s.payloadFree ? "yes" : "no"}`);
if (typeof s.rawLogsIncluded === "boolean") e.push(`- raw logs included: ${s.rawLogsIncluded ? "yes" : "no"}`);
const t = Array.isArray(s.notes) ? s.notes.filter((e) => typeof e === "string") : [];
for (const n of t.slice(0, 4)) e.push(`- ${n}`);
if (e.length > 1) r.push("", ...e);
}
return r.join("\n");
} catch {
return t;
}
}
function buildGatewayExecApprovalFollowupSummary(e) {
const t = e.outcome.timedOut ? "timeout" : `code ${e.outcome.exitCode ?? "?"}`;
let n;
if (e.trigger === "diagnostics") {
let r;
if (e.outcome.status === "completed" && e.outcome.exitCode === 0) r = formatDiagnosticsExportSuccess(e.outcome.aggregated);
else {
const n = normalizeNotifyOutput(tail(e.outcome.aggregated || "", 4e3));
const i = [`Diagnostics export failed (${t}).`];
if (e.outcome.reason) i.push(e.outcome.reason);
if (n) i.push("", n);
r = i.join("\n");
}
const i = e.approvalFollowupText?.trim();
const a = [r, i].filter(Boolean).join("\n\n");
n = `Exec finished (gateway id=${e.approvalId}, session=${e.sessionId}, ${t})\n${a}`;
} else {
const r = formatExecApprovalContinuationSourceOutput([{
label: "output",
value: e.outcome.aggregated
}]);
n = r ? `Exec finished (gateway id=${e.approvalId}, session=${e.sessionId}, ${t})\n${r}` : `Exec finished (gateway id=${e.approvalId}, session=${e.sessionId}, ${t})`;
}
return appendExecTimeoutRetryGuidance(n, e.outcome.exitReason);
}
function buildGatewayExecApprovalDeniedToolResult(e) {
const t = `Exec denied (${e.approvalId ? `gateway id=${e.approvalId}, ${e.deniedReason}` : e.deniedReason}): ${e.command}\n${formatExecDeniedReasonMessage(e.deniedReason)}`;
return {
content: [{
type: "text",
text: t
}],
details: {
status: "failed",
exitCode: null,
durationMs: 0,
aggregated: t,
timedOut: e.deniedReason.includes("timeout"),
cwd: e.cwd
}
};
}
async function resolveGatewayExecApprovalFollowupText(e) {
if (!e.approvalFollowup) return;
try {
return await e.approvalFollowup({
approvalId: e.approvalId,
sessionId: e.sessionId,
trigger: e.trigger,
outcome: e.outcome
});
} catch (e) {
return `Diagnostics follow-up failed: ${e instanceof Error ? e.message : String(e)}`;
}
}
function publishGatewayGuardianReview(e, t, n) {
if (!e.toolCallId) return;
const r = t === "in_progress" ? "reviewing" : t === "approved" ? "approved" : "denied";
const i = {
id: `guardian:${e.toolCallId}`,
label: "Guardian",
status: t,
...n ? {
riskLevel: n.risk,
rationale: n.rationale
} : {}
};
if (t !== "in_progress") e.onApprovalReview?.(i);
if (!e.runId) return;
emitAgentEvent({
runId: e.runId,
sessionKey: e.sessionKey,
sessionId: e.sessionId,
stream: "tool",
data: {
phase: "review",
name: "exec",
toolCallId: e.toolCallId,
hideFromChannelProgress: true,
approvalReviewOutcome: r,
review: i
}
});
}
//#endregion
//#region src/agents/bash-tools.exec-host-shared.ts
/**
* Owns pending-state construction, policy merging, unavailable-route handling,
* follow-up dispatch, and approval-pending tool result rendering.
*/
const loggedExecApprovalFollowupFailures = new LruCache(256);
function rememberExecApprovalFollowupFailureKey(e) {
if (loggedExecApprovalFollowupFailures.peek(e)) return false;
loggedExecApprovalFollowupFailures.set(e, true);
return true;
}
/** Converts a raw approval decision plus fallback policy into execution state. */
function resolveBaseExecApprovalDecision(e) {
if (e.decision === "deny") return {
approvedByAsk: false,
deniedReason: "user-denied",
timedOut: false
};
if (!e.decision) {
if (e.askFallback === "full") return {
approvedByAsk: true,
deniedReason: null,
timedOut: true
};
if (e.askFallback === "deny") return {
approvedByAsk: false,
deniedReason: "approval-timeout",
timedOut: true
};
return {
approvedByAsk: false,
deniedReason: null,
timedOut: true
};
}
return {
approvedByAsk: false,
deniedReason: null,
timedOut: false
};
}
async function resolveExecHostApprovalContext(e) {
const t = await resolveExecApprovalsLocked(e.agentId, {
security: e.security,
ask: e.ask
});
const n = e.bypassHostApprovalFloors ? e.security : minSecurity(e.security, t.agent.security);
const r = e.bypassHostApprovalFloors ? e.ask : maxAsk(e.ask, t.agent.ask);
const i = e.bypassHostApprovalFloors ? "deny" : minSecurity(n, t.agent.askFallback);
if (n === "deny") throw new Error(`exec denied: host=${e.host} security=deny`);
return {
approvals: t,
hostSecurity: n,
hostAsk: r,
askFallback: i
};
}
/** Resolves approval delivery availability for the initiating channel/account. */
async function resolveExecApprovalUnavailableState(e) {
const t = await resolveExecApprovalInitiatingSurfaceStateAsync({
channel: e.turnSourceChannel,
accountId: e.turnSourceAccountId
});
return {
initiatingSurface: t,
sentApproverDms: false,
unavailableReason: e.preResolvedDecision === null ? "no-approval-route" : t.kind === "disabled" ? "initiating-platform-disabled" : t.kind === "unsupported" ? "initiating-platform-unsupported" : null
};
}
async function createAndRegisterDefaultExecApprovalRequest(e) {
const t = crypto.randomUUID();
const n = resolveExpiresAtMsFromDurationMs(DEFAULT_APPROVAL_TIMEOUT_MS) ?? 0;
const r = e.warnings.length ? `${e.warnings.join("\n")}\n\n` : "";
const i = e.createApprovalSlug(t);
const a = await e.register(t);
const o = a.finalDecision;
const { initiatingSurface: s, sentApproverDms: c, unavailableReason: l } = await resolveExecApprovalUnavailableState({
turnSourceChannel: e.turnSourceChannel,
turnSourceAccountId: e.turnSourceAccountId,
preResolvedDecision: o
});
return {
approvalId: t,
approvalSlug: i,
warningText: r,
expiresAtMs: a.expiresAtMs ?? n,
preResolvedDecision: o,
initiatingSurface: s,
sentApproverDms: c,
unavailableReason: l
};
}
/** Resolves explicit, timeout-fallback, and strict-human approval policy in one owner. */
async function resolveExecApprovalDecisionState(e) {
const t = resolveBaseExecApprovalDecision({
decision: e.decision,
askFallback: e.askFallback
});
let { approvedByAsk: n, deniedReason: r } = t;
let i;
if (t.timedOut && e.resolveTimedOut) {
const a = await e.resolveTimedOut({
baseDecision: t,
approvedByAsk: n,
deniedReason: r
});
n = a.approvedByAsk;
r = a.deniedReason;
i = a.context;
} else if (e.decision === "allow-once" || e.decision === "allow-always") n = true;
const a = typeof e.requiresExplicitApproval === "function" ? e.requiresExplicitApproval(i) : e.requiresExplicitApproval;
if (t.timedOut && n && (a || e.requiresAutoReviewHumanApproval === true)) {
n = false;
r ??= "approval-timeout";
}
return {
baseDecision: t,
approvedByAsk: n,
deniedReason: r,
timeoutContext: i
};
}
/** Registers an approval and resolves terminal no-route fallback through the shared policy owner. */
async function createExecApprovalRequestRoute(e) {
const t = await createAndRegisterDefaultExecApprovalRequest(e);
if (t.unavailableReason !== "no-approval-route" || t.preResolvedDecision !== null) return {
...t,
kind: "wait"
};
const n = await resolveExecApprovalDecisionState({
...e,
decision: null
});
return {
...t,
kind: "inline",
preResolvedDecision: null,
state: n
};
}
function classifyExecApprovalWaitFailure(e) {
if (e instanceof Error && e.message === "Approval requester authority changed") return "authority-changed";
if (e instanceof GatewayProtocolRequestTimeoutError) return "gateway-timeout";
if (e instanceof GatewayProtocolRequestError) return "gateway-rejected";
return "unknown";
}
/** Waits for an approval and normalizes cancellation, request failure, and resolved policy. */
async function resolveExecApprovalWaitOutcome(e) {
let t;
try {
t = await resolveRegisteredExecApprovalDecision({
approvalTransport: e.approvalTransport,
approvalId: e.approvalId,
expiresAtMs: e.expiresAtMs,
preResolvedDecision: e.preResolvedDecision
});
} catch (t) {
if (isExecApprovalRunAbortedError(t)) return { kind: "run-aborted" };
logWarn(`exec approval wait failed (id=${e.approvalId}, reason=${classifyExecApprovalWaitFailure(t)})`);
return { kind: "request-failed" };
}
if (e.signal?.aborted) return { kind: "run-aborted" };
const n = await resolveExecApprovalDecisionState({
...e,
decision: t
});
return e.signal?.aborted ? { kind: "run-aborted" } : {
kind: "resolved",
decision: t,
state: n
};
}
/** Builds the denial copy for headless runs that cannot wait for approval. */
function buildHeadlessExecApprovalDeniedMessage(e) {
const t = e.trigger === "cron" ? "Automation runs" : "Headless runs";
const n = e.host === "node" ? "--node <id|name|ip>" : "--gateway";
const r = e.trigger === "cron" && e.host === "gateway" ? "- keep the Control UI or a macOS/iOS/Android app connected and answer the next run's approval card; Allow Always mints a standing grant" : "- rerun interactively and approve when prompted (Control UI or a chat channel with exec approvals)";
return [
`exec denied: ${t} cannot wait for interactive exec approval.`,
`Effective host exec policy: security=${e.security} ask=${e.ask} askFallback=${e.askFallback}`,
"Stricter values from tools.exec and the execution host's approvals policy both apply.",
"Fix one of these:",
"- set tools.exec.mode=\"full\" and align host approvals to security=\"full\" and ask=\"off\" for trusted local automation",
"- keep allowlist mode and add an explicit allowlist entry for this command",
r,
`Tip: run "openclaw doctor" and "openclaw approvals get ${n}" to inspect the effective policy.`
].join("\n");
}
/** Sends async approval follow-up results with deduped warning logs on failure. */
async function sendExecApprovalFollowupResult(e, t) {
const n = e.direct === true || !e.sessionKey || isExecDeniedResultText(t) ? void 0 : registerExecApprovalFollowupRuntimeHandoff({
approvalId: e.approvalId,
sessionKey: e.sessionKey,
bashElevated: e.bashElevated,
resultText: t
});
const r = {
approvalId: e.approvalId,
...e.agentId ? { agentId: e.agentId } : {},
sessionKey: e.sessionKey,
expectedSessionId: e.expectedSessionId,
sessionStore: e.sessionStore,
turnSourceChannel: e.turnSourceChannel,
turnSourceTo: e.turnSourceTo,
turnSourceAccountId: e.turnSourceAccountId,
turnSourceThreadId: e.turnSourceThreadId,
resultText: t,
direct: e.direct,
...n ? {
internalRuntimeHandoffId: n.handoffId,
idempotencyKey: n.idempotencyKey
} : {}
};
try {
const { sendExecApprovalFollowup: e } = await import("./bash-tools.exec-approval-followup-DlGJkUeV.mjs");
await e(r);
} catch (t) {
if (isApprovalNotFoundError(t)) return;
const n = formatErrorMessage(t);
if (!rememberExecApprovalFollowupFailureKey(`${e.approvalId}:${n}`)) return;
logWarn(`exec approval followup dispatch failed (id=${e.approvalId}): ${n}`);
}
}
/** Renders an approval-pending or approval-unavailable exec tool result. */
function buildExecApprovalPendingToolResult(e) {
const t = e.allowedDecisions ?? resolveExecApprovalAllowedDecisions();
return {
content: [{
type: "text",
text: e.unavailableReason !== null ? buildExecApprovalUnavailableReplyPayload({
warningText: e.warningText,
reason: e.unavailableReason,
channel: e.initiatingSurface.channel,
channelLabel: e.initiatingSurface.channelLabel,
accountId: e.initiatingSurface.accountId,
sentApproverDms: e.sentApproverDms,
host: e.host,
nodeId: e.nodeId
}).text ?? "" : buildApprovalPendingMessage({
warningText: e.warningText,
approvalSlug: e.approvalSlug,
approvalId: e.approvalId,
allowedDecisions: t,
command: e.command,
cwd: e.cwd,
host: e.host,
nodeId: e.nodeId,
processContinuationAvailable: e.processContinuationAvailable
})
}],
details: e.unavailableReason !== null ? {
status: "approval-unavailable",
reason: e.unavailableReason,
channel: e.initiatingSurface.channel,
channelLabel: e.initiatingSurface.channelLabel,
accountId: e.initiatingSurface.accountId,
sentApproverDms: e.sentApproverDms,
host: e.host,
command: e.command,
cwd: e.cwd,
nodeId: e.nodeId,
warningText: e.warningText
} : {
status: "approval-pending",
approvalId: e.approvalId,
approvalSlug: e.approvalSlug,
expiresAtMs: e.expiresAtMs,
allowedDecisions: t,
host: e.host,
command: e.command,
cwd: e.cwd,
nodeId: e.nodeId,
warningText: e.warningText
}
};
}
//#endregion
//#region src/agents/bash-tools.exec-host-gateway.ts
/**
* Evaluates shell allowlists, auto-review, durable approvals, follow-up routing,
* and approved command execution for gateway-backed exec calls.
*/
const ONE_SHOT_ALLOW_ALWAYS = {
kind: "one-shot",
reasons: ["no-reusable-pattern"]
};
const MAX_GATEWAY_AUTO_REVIEW_CANDIDATES = 64;
const MAX_CONSECUTIVE_AUTO_REVIEW_DENIALS = 3;
const consecutiveAutoReviewDenials = new LruCache(256);
function recordAutoReviewDenial(e) {
if (!e) return 1;
const t = Math.min((consecutiveAutoReviewDenials.get(e) ?? 0) + 1, MAX_CONSECUTIVE_AUTO_REVIEW_DENIALS);
consecutiveAutoReviewDenials.set(e, t);
return t;
}
async function resolveGatewayExecApprovalDrift(e) {
if (e.binding) {
const t = await revalidateSystemRunMutableFileBinding({
binding: e.binding,
cwd: e.cwd
});
if (!t.ok) return t.message;
}
if (e.cwdSnapshot && !revalidateApprovedCwdSnapshot(e.cwdSnapshot)) return APPROVAL_CWD_DRIFT_DENIED_MESSAGE;
}
/** Rechecks a gateway approval binding at the caller's final spawn boundary. */
async function revalidateGatewayExecApprovalBinding(e) {
const t = await resolveGatewayExecApprovalDrift(e);
return t ? buildGatewayExecApprovalDeniedToolResult({
deniedReason: t,
command: e.command,
cwd: e.cwd
}) : void 0;
}
/** Processes gateway exec policy and returns execution/approval/denial outcome. */
async function processGatewayAllowlist(e) {
const t = e.cleanupMs;
const deny = (t, n) => ({ deniedResult: buildGatewayExecApprovalDeniedToolResult({
approvalId: n,
deniedReason: t,
command: e.command,
cwd: e.workdir
}) });
const { approvals: n, hostSecurity: r, hostAsk: i, askFallback: a } = await resolveExecHostApprovalContext({
agentId: e.agentId,
security: e.security,
ask: e.ask,
bypassHostApprovalFloors: e.bypassHostApprovalFloors,
host: "gateway"
});
const o = r === "allowlist" || i !== "off" ? captureApprovedCwdSnapshotSync(e.workdir) : void 0;
if (o && !o.ok) return deny(o.message);
const s = o?.snapshot;
const c = createExecApprovalPolicySnapshot({
file: n.file,
agentId: e.agentId
});
const l = minSecurity(r, a);
const u = await evaluateShellAllowlistWithAuthorization({
command: e.command,
allowlist: n.allowlist,
safeBins: e.safeBins,
safeBinProfiles: e.safeBinProfiles,
cwd: e.workdir,
env: e.env,
platform: process.platform,
trustedSafeBinDirs: e.trustedSafeBinDirs
});
const d = u.allowlistMatches;
const f = u.analysisOk;
const p = r === "allowlist" && f ? u.allowlistSatisfied : false;
const m = countObsoleteGeneratedExecApprovals(n.file);
if (r === "allowlist" && !p && m > 0) e.warnings.push(`${m} older generated exec ${m === 1 ? "approval is" : "approvals are"} inactive because they are not tied to a working directory. Run "openclaw doctor --fix", then rerun the workflow and choose "Always allow here".`);
const h = hasDurableExecApproval({
analysisOk: f,
segmentAllowlistEntries: u.segmentAllowlistEntries,
allowlist: n.allowlist,
commandText: e.command
});
const g = r === "allowlist" && (!f || !p) && !h;
function emitApprovalEvent(t) {
emitTrustedSecurityEvent({
category: "approval",
action: t.action,
outcome: t.outcome,
severity: t.severity,
actor: { kind: "agent" },
target: {
kind: "tool",
name: "system.exec",
owner: "gateway"
},
policy: {
id: "exec.approval",
decision: t.action === "exec.approval.requested" ? "ask" : t.outcome === "success" ? "allow" : "deny",
...t.reason ? { reason: t.reason } : {}
},
control: {
id: "exec.approval",
family: "approval"
},
...t.reason ? { reason: t.reason } : {},
attributes: {
host: "gateway",
security: r,
ask: i,
segment_count: u.segments.length,
has_agent_id: Boolean(e.agentId?.trim()),
...e.trigger ? { trigger: e.trigger } : {},
...t.decision ? { decision: t.decision } : {}
}
});
}
const _ = e.strictInlineEval === true ? detectInlineEvalInSegments(u.segments) : null;
const v = resolveAllowAlwaysPersistenceDecision({
segments: u.segments,
cwd: e.workdir,
env: e.env,
platform: process.platform,
commandText: e.command,
strictInlineEval: e.strictInlineEval === true,
authorizationPlan: u.authorizationPlan,
runtimePayload: _ !== null
});
if (_) e.warnings.push(`Warning: strict inline-eval mode requires reviewer or explicit approval for ${describeInterpreterInlineEval(_)}.`);
const y = hasExactCommandDurableExecApproval({
allowlist: n.allowlist,
commandText: e.command
});
const b = f && u.allowlistSatisfied;
const x = (r === "allowlist" || l === "allowlist") && f ? process.platform === "win32" ? buildEnforcedShellCommand({
command: e.command,
segments: u.segments,
platform: process.platform
}) : u.authorizationPlan ? buildAuthorizedShellCommandFromPlan({
plan: u.authorizationPlan,
mode: "enforced",
segmentSatisfiedBy: u.segmentSatisfiedBy
}) : {
ok: false,
reason: "authorization plan unavailable"
} : null;
let S;
let C = null;
if (r === "allowlist" && f && p) {
const e = x ?? {
ok: false,
reason: "authorization plan unavailable"
};
if (!e.ok || !e.command) C = ("reason" in e ? e.reason : void 0) ?? "unsupported platform";
else S = e.command;
}
const w = l === "allowlist" && b && x?.ok === true ? x.command : void 0;
const T = l === "allowlist" && (b || y);
const E = y || w !== void 0;
const applyTimedOutAllowlistFallback = (e) => {
if (!e.baseDecision.timedOut || l !== "allowlist") return e;
const t = !T ? "approval-timeout: allowlist-miss" : !E ? "approval-timeout: execution-plan-miss" : null;
return {
...e,
approvedByAsk: t === null,
deniedReason: t
};
};
let D;
const assertCurrent = () => {
if (!D) throw new Error("Exec authorization has not been committed");
D();
};
const commitExecutionAuthorization = async (t) => {
const a = t.source === "current-policy" || t.source === "ask-fallback";
const o = t.source === "current-policy" ? r === "allowlist" && h && (!f || !p || y && C !== null) : t.source === "ask-fallback" ? l === "allowlist" && y && w === void 0 : false;
const s = resolveDurableExecApprovalRequirement({
durableApprovalRequired: o,
allowlist: n.allowlist,
commandText: e.command
});
const m = t.source === "explicit-approval" || t.source === "auto-review";
D = await commitExecAuthorizationLocked({
agentId: e.agentId,
matches: d,
command: e.command,
resolvedPath: t.resolvedPath,
authorization: {
source: t.source,
security: t.source === "ask-fallback" ? l : r,
ask: i,
bypassHostApprovalFloors: e.bypassHostApprovalFloors,
allowlistSatisfied: b || h,
...m ? { policySnapshot: c } : {},
requireAutoAllowSkills: a && u.segmentSatisfiedBy.includes("skills"),
requireExactCommandApproval: a && s === "exact-command",
requireDurableAllowlistApproval: a && s === "segment-allowlist"
},
...t.allowAlwaysDecision ? { allowAlwaysDecision: t.allowAlwaysDecision } : {}
});
};
const O = u.segments.some((e) => e.argv.some((e) => e.startsWith("<<")));
const k = O && r === "allowlist" && f && p;
const A = O && T;
const j = _ !== null;
const M = r === "allowlist" && f && p && !y && !S && C !== null;
const N = requiresExecApproval({
ask: i,
security: r,
analysisOk: f,
allowlistSatisfied: p,
durableApprovalSatisfied: h
}) || M || k || j;
const denyHeadlessApproval = () => {
const t = e.approvalFollowupText ? `${e.approvalFollowupText}\nCommand: ${e.command}` : `Exec denied (approval_required): ${e.command}`;
return { deniedResult: buildExecApprovalDeniedToolResult(t, e.workdir, "approval_required") };
};
if (k) e.warnings.push("Warning: heredoc execution requires reviewer or explicit approval in allowlist mode.");
if (M) e.warnings.push(`Warning: allowlist auto-execution is unavailable on ${process.platform}; reviewer or explicit approval is required.`);
if (N && e.nonInteractiveApproval && e.autoReview !== true) return denyHeadlessApproval();
if (e.autoReview !== true && M && C === "shell expansion in enforced arguments" && i === "off" && a === "deny") {
const e = "ask-fallback-deny: execution-plan-miss";
emitApprovalEvent({
action: "exec.approval.denied",
outcome: "denied",
severity: "medium",
reason: e
});
return deny(e);
}
let P;
const F = r === "allowlist" && h && (!f || !p || y && C !== null);
if (N || F) {
const t = await prepareSystemRunMutableFileBinding({
command: f ? {
kind: "segments",
segments: u.segments
} : {
kind: "shell",
text: e.command
},
cwd: e.workdir,
env: e.env
});
if (!t.ok) {
if (N && e.nonInteractiveApproval) return denyHeadlessApproval();
return deny(t.message);
}
P = t.binding;
}
const I = P?.operands.some((e) => e.kind === "mutable") ?? false;
const L = e.runId && e.agentId ? lookupCronRunExecSource(e.runId) : void 0;
if (N && i !== "always" && r !== "deny" && L !== void 0 && L.agentId === e.agentId && !I && !j && !k) {
let t;
try {
t = await prepareCronStandingGrantConsumption(e, L, {
security: r,
ask: i
});
} catch {
t = void 0;
}
if (t) {
const n = t.consume;
const emitGrantEvent = (e, t) => emitApprovalEvent({
action: e ? "exec.approval.approved" : "exec.approval.denied",
outcome: e ? "success" : "denied",
severity: "medium",
reason: t,
decision: "standing-grant"
});
return {
execCommandOverride: S,
assertCurrent: t.assertCurrent,
initiateSpawn: t.initiateSpawn,
releaseSpawn: t.releaseSpawn,
revalidateBeforeExecution: async () => {
let t;
try {
t = await n(e.signal);
} catch {
t = void 0;
}
const r = t?.outcome === "consumed" ? t.grant : void 0;
if (r && (r.expiresAtMs === null || r.expiresAtMs > Date.now())) {
emitGrantEvent(true, `standing-grant grant=${r.grantId} approval=${r.mintedByApprovalId}`);
return;
}
const i = r ? "expired" : t?.outcome ?? "grant-store-unavailable";
emitGrantEvent(false, `standing-grant-invalidated ${i}`);
return buildGatewayExecApprovalDeniedToolResult({
deniedReason: `standing grant no longer valid (${i}); the next occurrence will prompt for approval again`,
command: e.command,
cwd: e.workdir
});
}
};
}
}
const R = N || F && I;
const z = x?.ok === true ? x.command : void 0;
const B = u.segments.some((e) => hasPosixShellStartupBeforeInlineCommand(e.argv));
const V = resolveUnpinnedAutoApprovalEligibility({
authorizationPlan: u.authorizationPlan,
binding: P
});
const H = V.eligible && u.authorizationPlan && P ? buildReviewedShellCommandFromPlan({
plan: u.authorizationPlan,
binding: P,
segmentSatisfiedBy: u.segmentSatisfiedBy
}) : void 0;
const U = H?.ok ? H.command : void 0;
const W = U ?? z;
const G = z !== void 0 ? { eligible: true } : V.eligible && W === void 0 ? {
eligible: false,
reason: EXEC_AUTO_REVIEW_DISPATCH_IDENTITY_WARNING
} : V;
const K = e.approvalTransport || I || e.autoReview === true && (B || !G.eligible) || M && v.kind === "patterns" ? ONE_SHOT_ALLOW_ALWAYS : v;
const q = resolveExecApprovalAllowedDecisions({
ask: i,
allowAlwaysPersistence: K
});
const J = resolveExecApprovalUnavailableDecisions({
ask: i,
allowAlwaysPersistence: K
});
const ee = J.length > 0 ? { unavailableDecisions: J } : {};
if (R) {
const bindApprovalExecution = (t) => e.approvalTransport?.bindExecution({
command: e.command,
execCommand: t ?? e.command,
cwd: e.workdir,
env: e.env,
pty: e.pty
});
if (!P) return deny("SYSTEM_RUN_DENIED: mutable file approval binding is unavailable");
const n = P;
const resolveApprovalDrift = () => resolveGatewayExecApprovalDrift({
binding: n,
cwdSnapshot: s,
cwd: e.workdir
});
const o = s || n.operands.length > 0 ? () => revalidateGatewayExecApprovalBinding({
binding: n,
cwdSnapshot: s,
command: e.command,
cwd: e.workdir
}) : void 0;
const c = u.authorizationPlan?.ok ? u.authorizationPlan.groups.flatMap((e) => e.candidates) : [];
const d = c.length === 1 && u.segmentSatisfiedBy[0] !== "safeBuiltins" ? c[0]?.sourceSegment : void 0;
const m = d ? resolveExecutionTargetTrustPath(d.resolution, e.workdir) : void 0;
if (e.autoReview === true && B) e.warnings.push(EXEC_AUTO_REVIEW_SHELL_STARTUP_WARNING);
const _ = !G.eligible;
if (e.autoReview === true && !B && !G.eligible) e.warnings.push(G.reason);
const v = e.autoReview === true && i !== "always" && Math.max(c.length, u.segments.length) <= MAX_GATEWAY_AUTO_REVIEW_CANDIDATES && !B && !_;
let y = e.autoReview === true && B || e.autoReview === true && _ || e.autoReview === true && i !== "always" && !v || M || k;
if (v) {
const t = e.autoReviewer ?? defaultExecAutoReviewer;
publishGatewayGuardianReview(e, "in_progress");
bindApprovalExecution(W);
const r = {
command: e.command,
argv: m ? d?.argv : void 0,
resolvedPath: m,
cwd: e.workdir,
envKeys: Object.keys(e.requestedEnv ?? {}).toSorted(),
host: "gateway",
reason: j ? "strict-inline-eval" : O ? "heredoc" : z === void 0 ? "execution-plan-miss" : g ? "allowlist-miss" : "approval-required",
analysis: {
parsed: f,
allowlistMatched: p,
durableApprovalMatched: h,
inlineEval: j,
heredoc: O
},
agent: {
id: e.agentId,
sessionKey: e.sessionKey
}
};
const i = e.approvalTransport ? e.approvalTransport.review(r) : resolveExecAutoReviewDecision(t, r);
let a;
try {
a = e.signal ? await abortable(e.signal, i) : await i;
e.signal?.throwIfAborted();
} catch (t) {
publishGatewayGuardianReview(e, "aborted");
throw t;
}
const c = a.decision === "deny" && recordAutoReviewDenial(e.sessionKey) >= MAX_CONSECUTIVE_AUTO_REVIEW_DENIALS;
publishGatewayGuardianReview(e, a.decision === "allow-once" ? "approved" : "denied", a);
switch (a.decision) {
case "allow-once": {
if (a.risk !== "low" && a.risk !== "medium") break;
if (e.sessionKey) consecutiveAutoReviewDenials.delete(e.sessionKey);
const t = await revalidateGatewayExecApprovalBinding({
binding: n,
cwdSnapshot: s,
command: e.command,
cwd: e.workdir
});
if (t) return { deniedResult: t };
e.warnings.push(`Exec auto-review allowed once (${formatExecAutoReviewAssessment(a)}): ${a.rationale}`);
emitApprovalEvent({
action: "exec.approval.approved",
outcome: "success",
severity: "medium",
decision: "auto-review"
});
await commitExecutionAuthorization({
source: "auto-review",
resolvedPath: m
});
return {
execCommandOverride: W,
assertCurrent,
...o ? { revalidateBeforeExecution: o } : {}
};
}
case "deny":
if (c) {
e.warnings.push("Exec auto-review denied 3 consecutive commands for this session; escalating to human approval");
break;
}
emitApprovalEvent({
action: "exec.approval.denied",
outcome: "denied",
severity: "medium",
decision: "auto-review"
});
return { deniedResult: buildExecAutoReviewDeniedToolResult({
command: e.command,
cwd: e.workdir,
decision: a,
toolCallId: e.toolCallId
}) };
case "ask": break;
default: throw new Error("Unsupported exec auto-review decision", { cause: a });
}
e.warnings.push(`Exec auto-review deferred to human approval (${formatExecAutoReviewAssessment(a)}): ${a.rationale}`);
y = true;
}
if (e.nonInteractiveApproval) return denyHeadlessApproval();
bindApprovalExecution(U ?? S);
const registerGatewayApproval = async (t) => await registerExecApprovalRequestForHostOrThrow({
approvalTransport: e.approvalTransport,
approvalId: t,
command: e.command,
env: e.requestedEnv,
workdir: e.workdir,
host: "gateway",
security: r,
ask: i,
...ee,
commandHighlighting: e.commandHighlighting,
warningText: e.warnings.join("\n").trim() || void 0,
agentId: e.agentId,
sessionKey: e.sessionKey,
sessionId: e.sessionId,
runId: e.runId,
toolCallId: e.toolCallId,
trigger: e.trigger,
approvalReviewerDeviceIds: e.approvalReviewerDeviceId ? [e.approvalReviewerDeviceId] : void 0,
resolvedPath: resolveApprovalAuditTrustPath(u.segments[0]?.resolution ?? null, e.workdir),
...buildExecApprovalTurnSourceContext(e)
});
const b = await createExecApprovalRequestRoute({
warnings: e.warnings,
approvalRunningNoticeMs: e.approvalRunningNoticeMs,
createApprovalSlug,
turnSourceChannel: e.turnSourceChannel,
turnSourceAccountId: e.turnSourceAccountId,
register: registerGatewayApproval,
askFallback: a,
resolveTimedOut: applyTimedOutAllowlistFallback,
requiresExplicitApproval: j,
requiresAutoReviewHumanApproval: y || k || A
});
const { approvalId: x, approvalSlug: C, warningText: T, expiresAtMs: E, preResolvedDecision: D, initiatingSurface: N, sentApproverDms: F, unavailableReason: I } = b;
emitApprovalEvent({
action: "exec.approval.requested",
outcome: "success",
severity: "low"
});
if (b.kind === "inline") {
const t = b.state;
if (t.deniedReason || !t.approvedByAsk) {
emitApprovalEvent({
action: "exec.approval.denied",
outcome: "denied",
severity: "medium",
reason: t.deniedReason ?? "approval-required",
decision: D
});
throw new Error(buildHeadlessExecApprovalDeniedMessage({
trigger: e.trigger,
host: "gateway",
security: r,
ask: i,
askFallback: a
}));
}
const n = await resolveApprovalDrift();
if (n) return deny(n, x);
emitApprovalEvent({
action: "exec.approval.approved",
outcome: "success",
severity: "medium",
decision: null
});
await commitExecutionAuthorization({
source: "ask-fallback",
resolvedPath: resolveApprovalAuditTrustPath(u.segments[0]?.resolution ?? null, e.workdir)
});
const s = l === "allowlist" ? w : S;
return {
execCommandOverride: s,
allowWithoutEnforcedCommand: s === void 0,
assertCurrent,
...o ? { revalidateBeforeExecution: o } : {}
};
}
const R = resolveApprovalAuditTrustPath(u.segments[0]?.resolution ?? null, e.workdir);
const resolveApprovalForExecution = async (t) => {
const n = await resolveExecApprovalWaitOutcome({
approvalTransport: e.approvalTransport,
approvalId: x,
expiresAtMs: E,
preResolvedDecision: D,
signal: e.signal,
askFallback: a,
resolveTimedOut: applyTimedOutAllowlistFallback,
requiresExplicitApproval: j,
requiresAutoReviewHumanApproval: y || k || A
});
if (n.kind === "run-aborted") return {
deniedReason: "run-aborted",
requestFailed: false,
runAborted: true,
authorizationSource: "explicit-approval",
allowAlwaysDecision: void 0
};
if (n.kind === "request-failed") {
await t();
emitApprovalEvent({
action: "exec.approval.denied",
outcome: "error",
severity: "high",
reason: "approval-request-failed"
});
return {
deniedReason: e.approvalTransport ? "approval-request-failed: retry from a new worker turn" : "approval-request-failed",
requestFailed: true,
authorizationSource: "explicit-approval",
allowAlwaysDecision: void 0
};
}
const { decision: r, state: i } = n;
if (r !== null && e.sessionKey) consecutiveAutoReviewDenials.delete(e.sessionKey);
const { approvedByAsk: o } = i;
let { deniedReason: s } = i;
if (!o && g) s = s ?? "allowlist-miss";
if (!s && o) {
const e = await resolveApprovalDrift();
if (e) s = e;
}
emitApprovalEvent({
action: s ? "exec.approval.denied" : "exec.approval.approved",
outcome: s ? "denied" : "success",
severity: "medium",
reason: s ?? void 0,
decision: r
});
return {
deniedReason: s,
requestFailed: false,
authorizationSource: r === null ? "ask-fallback" : "explicit-approval",
allowAlwaysDecision: r === "allow-always" && !L ? K : void 0,
execCommandOverride: r === null && l === "allowlist" ? w : U ?? S
};
};
const commitApprovalDecision = (e) => commitExecutionAuthorization({
source: e.authorizationSource,
resolvedPath: R ?? void 0,
...e.allowAlwaysDecision ? { allowAlwaysDecision: e.allowAlwaysDecision } : {}
});
if (I === null && e.approvalFollowupMode === void 0) {
const emitApprovalLifecycle = (t) => {
if (e.runId) emitAgentEvent({
runId: e.runId,
sessionKey: e.sessionKey,
sessionId: e.sessionId,
stream: "lifecycle",
data: {
phase: t,
approvalId: x,
toolCallId: e.toolCallId
}
});
};
emitApprovalLifecycle("waiting-approval");
let t;
try {
t = await resolveApprovalForExecution(() => void 0);
} finally {
emitApprovalLifecycle("approval-resolved");
}
if (t.runAborted) e.signal?.throwIfAborted();
if (t.deniedReason) return deny(t.deniedReason, x);
e.signal?.throwIfAborted();
await commitApprovalDecision(t);
e.signal?.throwIfAborted();
return {
execCommandOverride: t.execCommandOverride,
allowWithoutEnforcedCommand: t.execCommandOverride === void 0,
assertCurrent,
...o ? { revalidateBeforeExecution: o } : {}
};
}
const V = typeof e.timeoutSec === "number" ? e.timeoutSec : e.defaultTimeoutSec;
const H = buildExecApprovalFollowupTarget(e, x);
const sendDeniedFollowup = (t) => sendExecApprovalFollowupResult(H, `Exec denied (gateway id=${x}, ${t}): ${e.command}`);
const denyApprovalStateWriteFailure = async () => {
emitApprovalEvent({
action: "exec.approval.denied",
outcome: "error",
severity: "high",
reason: "approval-state-write-failed"
});
await sendDeniedFollowup("approval-state-write-failed");
};
const sendApprovalRequestFailedFollowup = async () => {
if (!e.signal?.aborted) await sendDeniedFollowup("approval-request-failed");
};
let J = false;
(async () => {
const n = await resolveApprovalForExecution(sendApprovalRequestFailedFollowup);
if (n.requestFailed || n.runAborted || e.signal?.aborted) return;
if (n.deniedReason) {
await sendDeniedFollowup(n.deniedReason);
return;
}
let r;
try {
r = await runWithGatewayIndependentRootWorkAdmission(async () => {
if (e.signal?.aborted) return { status: "run-aborted" };
try {
await commitApprovalDecision(n);
} catch {
return { status: "approval-state-write-failed" };
}
if (e.signal?.aborted) return { status: "run-aborted" };
const r = await resolveApprovalDrift();
if (r) return {
status: "operand-drift",
message: r
};
let i;
let a;
const o = /* @__PURE__ */ new Error("gateway approval changed before spawn");
try {
J = true;
i = await runExecProcess({
approvalTransport: e.approvalTransport,
command: e.command,
execCommand: n.execCommandOverride,
workdir: e.workdir,
env: e.env,
secretEgressBindings: e.secretEgressBindings,
githubProfileDir: e.githubProfileDir,
pathPrepend: e.pathPrepend,
sandbox: void 0,
containerWorkdir: null,
usePty: e.pty,
warnings: e.warnings,
maxOutput: e.maxOutput,
pendingMaxOutput: e.pendingMaxOutput,
cleanupMs: t,
notifyOnExit: false,
notifyOnExitEmptySuccess: false,
scopeKey: e.scopeKey,
sessionKey: e.notifySessionKey ?? e.sessionKey,
timeoutSec: V,
startupSignal: e.signal,
assertCurrent,
beforeSpawn: async () => {
a = await resolveApprovalDrift();
if (a) throw o;
}
});
} catch (t) {
if (e.signal?.aborted) return { status: "run-aborted" };
if (t === o && a) return {
status: "operand-drift",
message: a
};
return { status: "spawn-failed" };
}
markBackgrounded(i.session);
return {
status: "started",
run: i
};
}, "exec-host:approval");
} catch (e) {
if (e instanceof GatewayDrainingError) {
await sendDeniedFollowup("gateway-draining");
return;
}
r = { status: "spawn-failed" };
}
if (r.status === "approval-state-write-failed") {
await denyApprovalStateWriteFailure();
return;
}
if (r.status === "run-aborted") return;
if (r.status === "operand-drift") {
await sendExecApprovalFollowupResult(H, r.message);
return;
}
if (r.status === "spawn-failed") {
await sendDeniedFollowup("spawn-failed");
return;
}
const { run: i } = r;
const a = await i.promise;
const o = await resolveGatewayExecApprovalFollowupText({
approvalFollowup: e.approvalFollowup,
approvalId: x,
sessionId: i.session.id,
trigger: e.trigger,
outcome: a
});
const s = normalizeStringEntries([e.approvalFollowupText ?? "", o ?? ""]).join("\n\n");
const c = buildGatewayExecApprovalFollowupSummary({
approvalId: x,
sessionId: i.session.id,
outcome: a,
trigger: e.trigger,
approvalFollowupText: s
});
await sendExecApprovalFollowupResult(H, c);
})().catch(async () => {
if (J || e.signal?.aborted) return;
await sendApprovalRequestFailedFollowup();
}).catch(() => void 0);
return { pendingResult: buildExecApprovalPendingToolResult({
host: "gateway",
command: e.command,
cwd: e.workdir,
warningText: T,
approvalId: x,
approvalSlug: C,
expiresAtMs: E,
initiatingSurface: N,
sentApproverDms: F,
unavailableReason: I,
allowedDecisions: q,
processContinuationAvailable: e.processContinuationAvailable
}) };
}
if (g) throw new Error("exec denied: allowlist miss");
await commitExecutionAuthorization({
source: "current-policy",
resolvedPath: resolveApprovalAuditTrustPath(u.segments[0]?.resolution ?? null, e.workdir)
});
return {
execCommandOverride: S,
assertCurrent,
...s ? { revalidateBeforeExecution: () => revalidateGatewayExecApprovalBinding({
cwdSnapshot: s,
command: e.command,
cwd: e.workdir
}) } : {}
};
}
//#endregion
//#region src/agents/bash-tools.exec-host-node-failure.ts
/** Only NOT_CONNECTED plus explicit pre-dispatch provenance proves a retry cannot duplicate work. */
function classifyNodeInvokeFailure(e) {
const t = asNullableRecord(e);
const n = asNullableRecord(t?.details);
const r = asNullableRecord(n?.nodeError);
const i = normalizeOptionalString(r?.code);
const a = normalizeOptionalString(r?.message) ?? (e instanceof Error ? e.message : normalizeOptionalString(e)) ?? "node invoke failed";
const o = typeof n?.nodeCommandDispatched === "boolean" ? n.nodeCommandDispatched : void 0;
const s = typeof t?.requestSent === "boolean" ? t.requestSent : void 0;
const c = readNodePermissionError(e);
if (i === "PERMISSION_MISSING" && c) return {
reason: "permission-missing",
retrySafe: false,
code: i,
message: e instanceof Error ? e.message : a,
permissionMissing: c,
nodeCommandDispatched: o,
requestSent: s
};
if (i === "SYSTEM_RUN_DENIED") return {
reason: "policy-denied",
retrySafe: false,
code: i,
message: a
};
if (i === "NOT_CONNECTED" && o === false) return {
reason: "not-dispatched",
retrySafe: true,
code: i,
message: a,
nodeCommandDispatched: o,
...s !== void 0 ? { requestSent: s } : {}
};
return {
reason: "outcome-unknown",
retrySafe: false,
...i ? { code: i } : {},
message: a,
...o !== void 0 ? { nodeCommandDispatched: o } : {},
...s !== void 0 ? { requestSent: s } : {}
};
}
function formatNodeInvokeFailureText(e) {
return [
...e.failure.reason === "permission-missing" ? [e.failure.message] : e.failure.reason === "outcome-unknown" ? [`Node command outcome is unknown for ${e.nodeId}.`, "The command may have executed. Do not rerun it automatically."] : e.failure.reason === "policy-denied" ? [`Node command was denied before execution on ${e.nodeId}.`, "Resolve the reported refusal before retrying."] : [`Node command was not dispatched to ${e.nodeId}.`, "It can be retried after the node reconnects."],
"",
"Command:",
e.command,
"",
`Details: ${e.failure.message}`
].join("\n");
}
function formatNodeInvokeFailureFollowup(e) {
return `${e.failure.reason === "permission-missing" ? `Exec needs permission (node=${e.nodeId} id=${e.approvalId})` : e.failure.reason === "outcome-unknown" ? `Exec outcome unknown (node=${e.nodeId} id=${e.approvalId}, outcome-unknown)` : e.failure.reason === "policy-denied" ? `Exec denied (node=${e.nodeId} id=${e.approvalId}, policy-denied)` : `Exec not dispatched (node=${e.nodeId} id=${e.approvalId}, not-dispatched)`}\n${formatNodeInvokeFailureText(e)}`;
}
function formatNodeInvokeFailureToolResult(e) {
const t = formatNodeInvokeFailureText(e);
return {
content: [{
type: "text",
text: renderExecUpdateText({
tailText: t,
warnings: e.warnings ?? []
})
}],
details: {
status: "failed",
exitCode: null,
failureKind: e.failure.reason,
reason: e.failure.reason,
...e.failure.reason === "permission-missing" ? { permissionMissing: e.failure.permissionMissing } : {},
nodeInvokeFailure: {
...e.failure.code ? { failureCode: e.failure.code } : {},
message: e.failure.message,
...e.failure.nodeCommandDispatched !== void 0 ? { nodeCommandDispatched: e.failure.nodeCommandDispatched } : {},
...e.failure.requestSent !== void 0 ? { requestSent: e.failure.requestSent } : {}
},
durationMs: Date.now() - e.startedAt,
aggregated: t,
cwd: e.cwd
}
};
}
/** Invokes node system.run and turns every non-cancellation failure into provenance-aware data. */
async function invokeNodeSystemRun(e) {
try {
const t = e.scopes || e.signal || e.source ? {
...e.scopes ? { scopes: e.scopes } : {},
...e.signal ? { signal: e.signal } : {},
...e.source ? { dispatchAuthority: {
version: 2,
kind: "source-bound",
assertCurrent: e.source
} } : {}
} : void 0;
const n = await callGatewayTool("node.invoke", { timeoutMs: e.invokeWaitMs }, e.invoke, t);
if (typeof asNullableRecord(asNullableRecord(n)?.payload)?.success !== "boolean") return {
ok: false,
failure: {
reason: "outcome-unknown",
retrySafe: false,
message: "malformed node invoke response"
}
};
return {
ok: true,
raw: n
};
} catch (t) {
if (e.signal?.aborted) throw t;
return {
ok: false,
failure: classifyNodeInvokeFailure(t)
};
}
}
//#endregion
//#region src/infra/node-shell.ts
/** Build argv for running a command through the platform default shell. */
function buildNodeShellCommand(e, t) {
const n = normalizeLowercaseStringOrEmpty((t ?? "").trim());
if (n.startsWith("win")) return [
"cmd.exe",
"/d",
"/s",
"/c",
e
];
if (n === "darwin" || n.startsWith("macos")) return [
"/bin/sh",
"-c",
e
];
return [
"/bin/sh",
"-lc",
e
];
}
//#endregion
//#region src/agents/bash-tools.exec-host-node-approval-eligibility.ts
function resolveNodeAutoApprovalEligibility(e) {
const t = e.platform === "win32" ? "win32" : e.platform === "darwin" ? "darwin" : "linux";
const n = resolveExecWrapperTrustPlan(e.argv, void 0, t);
const r = e.shellPayload === null && n.dispatchChain?.length === 1 && (t === "win32" ? path.win32 : path.posix).isAbsolute(e.argv[0] ?? "");
const i = e.shellPayload ? buildNodeShellCommand(e.shellPayload, e.platform) : void 0;
const a = e.authorizationPlan;
const o = a?.ok ? a.groups.flatMap((e) => e.candidates) : [];
const s = o[0]?.sourceSegment;
const c = i !== void 0 && i.length === e.argv.length && i.every((t, n) => t === e.argv[n]) && o.length === 1 && o[0]?.transport.kind === "direct" && o[0]?.trustMode === "executable" && s !== void 0 && resolveExecWrapperTrustPlan(s.sourceArgv ?? s.argv, void 0, t).dispatchChain?.length === 1 && (t === "win32" ? path.win32 : path.posix).isAbsolute(s.argv[0] ?? "") && a !== void 0 && buildAuthorizedShellCommandFromPlan({
plan: a,
mode: "enforced",
segmentSatisfiedBy: e.segmentSatisfiedBy
}).ok;
return r || c ? { eligible: true } : resolveUnpinnedAutoApprovalEligibility({
authorizationPlan: e.authorizationPlan,
binding: void 0,
platform: t
});
}
//#endregion
//#region src/agents/bash-tools.exec-host-node-phases.ts
function extractPreparedNodeShellPayload(e) {
const t = extractShellCommandFromArgv([...e]);
if (t) return t;
const n = e[0]?.split(/[\\/]/).pop()?.toLowerCase();
const r = e[1]?.trim();
const i = e[2]?.trim();
if (e.length === 3 && n === "sh" && r === "-lc" && i) return i;
return null;
}
async function resolveNodeExecutionTarget(e) {
const t = await listNodes({});
if (t.length === 0) throw new Error("exec host=node requires a paired node (none available). This lasts until the operator pairs a companion app or node host, so retrying will not help. Run the command on another exec host if the task allows it, or tell the user a node must be paired.");
const n = e.boundNode ? resolveNodeIdFromList(t, e.boundNode) : void 0;
let r;
if (e.requestedNode) try {
r = resolveNodeIdFromList(t, e.requestedNode);
} catch (t) {
throw new Error(`requested node not found: ${e.requestedNode} (${t instanceof Error ? t.message : String(t)})`, { cause: t });
}
if (n && r && n !== r) throw new Error(`exec node not allowed (bound to ${n}, requested resolved to ${r})`);
const i = resolveEligibleNodeFromList(t, n ?? r, (e) => e.connected === true && e.commands?.includes("system.run") === true, {
ineligibleExact: (e, t) => `exec host=node requires a connected node that supports system.run (${e} is not eligible; eligible node ids: ${t}).`,
nameResolveFailed: (e, t) => `${e} (eligible connected system.run node ids: ${t})`,
noneEligible: () => "exec host=node requires a connected node that supports system.run (none available). This lasts until a node reconnects, so retrying will not help. Run the command on another exec host if the task allows it, or tell the user to start or reconnect the companion app or node host.",
multipleEligible: (e) => `exec host=node requires a node when multiple executable nodes are connected: ${e.map((e) => e.displayName ? `${e.nodeId} (${e.displayName})` : e.nodeId).join(", ")}. Set exec.node, tools.exec.node, or /exec node=...`
});
const a = i.caps?.includes("system.run.execution-context.v1") ? e.executionContext : void 0;
return {
nodeId: i.nodeId,
platform: i.platform,
argv: buildNodeShellCommand(e.command, i.platform),
env: !a && e.executionContext ? {
...e.requestedEnv,
...buildExecRoutingEnv(e.executionContext)
} : e.requestedEnv ? { ...e.requestedEnv } : void 0,
executionContext: a,
...resolveNodeExecTimeouts(e.timeoutSec, e.defaultTimeoutSec),
supportsSystemRunPrepare: i.commands?.includes("system.run.prepare") === true
};
}
function buildNodeSystemRunInvoke(e) {
const { prepared: t, request: n } = e;
const r = e.runId ?? crypto.randomUUID();
return {
nodeId: e.target.nodeId,
command: "system.run",
timeoutMs: e.target.invokeDeadlineMs,
params: {
command: t.argv,
rawCommand: t.rawCommand,
...t.plan ? { systemRunPlan: t.plan } : {},
...t.cwd != null ? { cwd: t.cwd } : {},
env: e.target.env,
executionContext: e.target.executionContext,
timeoutMs: e.target.runTimeoutMs,
agentId: t.agentId,
sessionKey: t.sessionKey,
...n.turnSourceChannel != null ? { turnSourceChannel: n.turnSourceChannel } : {},
...n.turnSourceTo != null ? { turnSourceTo: n.turnSourceTo } : {},
...n.turnSourceAccountId != null ? { turnSourceAccountId: n.turnSourceAccountId } : {},
...n.turnSourceThreadId != null ? { turnSourceThreadId: n.turnSourceThreadId } : {},
approved: e.approved,
approvalDecision: e.approvalDecision ?? void 0,
approvalSource: e.approvalSource,
runId: r,
suppressNotifyOnExit: e.suppressNotifyOnExit === true || n.notifyOnExit === false ? true : void 0
},
idempotencyKey: crypto.randomUUID()
};
}
async function dispatchNodeSystemRun(e) {
const t = Date.now();
e.request.signal?.throwIfAborted();
const n = await runWithAgentToolSourceExecutionScope(e.source, () => invokeNodeSystemRun({
source: e.source,
invokeWaitMs: e.target.invokeWaitMs,
invoke: e.invoke,
scopes: e.scopes,
signal: e.request.signal
}));
if (!n.ok) return formatNodeInvokeFailureToolResult({
failure: n.failure,
nodeId: e.target.nodeId,
command: e.request.command,
startedAt: t,
cwd: e.request.workdir,
warnings: [...e.request.warnings, ...e.request.foregroundWarnings ?? []]
});
const r = [...e.request.warnings, ...e.request.foregroundWarnings ?? []];
const i = asNullableRecord(asNullableRecord(n.raw)?.payload) ?? {};
const a = typeof i.stdout === "string" ? i.stdout : "";
const o = typeof i.stderr === "string" ? i.stderr : "";
const s = typeof i.error === "string" ? i.error : "";
const c = typeof i.success === "boolean" ? i.success : false;
const l = typeof i.exitCode === "number" ? i.exitCode : null;
const u = i.timedOut === true;
const d = [
a,
o,
s,
u ? appendExecTimeoutRetryGuidance("Command timed out.", "overall-timeout") : !c && l !== null && l !== 0 ? `(Command exited with code ${l})` : ""
].filter(Boolean).join("\n");
return {
content: [{
type: "text",
text: `Node: ${e.target.nodeId}\n${renderExecUpdateText({
tailText: d,
warnings: r
})}`
}],
details: {
status: c ? "completed" : "failed",
exitCode: l,
durationMs: Date.now() - t,
aggregated: d,
nodeId: e.target.nodeId,
...u ? { timedOut: true } : {},
cwd: e.request.workdir
}
};
}
async function prepareNodeSystemRun(e) {
if (!e.target.supportsSystemRunPrepare) throw new Error("exec denied: node approval requires system.run.prepare support");
const t = await callGatewayTool("node.invoke", { timeoutMs: 15e3 }, {
nodeId: e.target.nodeId,
command: "system.run.prepare",
params: {
command: e.target.argv,
security: e.request.security,
ask: e.request.ask,
rawCommand: e.request.command,
...e.request.workdir != null ? { cwd: e.request.workdir } : {},
...e.target.env !== void 0 ? { env: e.target.env } : {},
executionContext: e.target.executionContext,
...e.request.strictInlineEval === true ? { strictInlineEval: true } : {},
agentId: e.request.agentId,
sessionKey: e.request.sessionKey
},
idempotencyKey: crypto.randomUUID()
});
const n = parsePreparedSystemRunPayload(t?.payload);
if (!n) throw new Error("invalid system.run.prepare response");
return {
plan: n.plan,
argv: n.plan.argv,
rawCommand: n.plan.commandText,
cwd: n.plan.cwd ?? e.request.workdir,
agentId: n.plan.agentId ?? e.request.agentId,
sessionKey: n.plan.sessionKey ?? e.request.sessionKey,
...n.execPolicy ? { execPolicy: n.execPolicy } : {},
allowAlwaysCoverage: n.allowAlwaysCoverage
};
}
async function analyzeNodeApprovalRequirement(e) {
const t = e.prepared.rawCommand;
const n = e.prepared.cwd ?? e.request.workdir;
const r = {
...e.target.env,
PATH: "",
Path: ""
};
const evaluateCommand = (t, n, i = []) => evaluateShellAllowlistWithAuthorization({
command: t,
allowlist: i,
safeBins: /* @__PURE__ */ new Set(),
cwd: n,
env: r,
platform: e.target.platform,
trustedSafeBinDirs: e.request.trustedSafeBinDirs
});
const i = await evaluateCommand(t, n);
const a = [{
command: t,
cwd: n,
allowlistEval: i
}];
const addCommandEval = async (e, t, n) => {
const r = t?.trim();
if (!r) return;
if (e.some((e) => e.command.trim() === r && e.cwd === n)) return;
e.push({
command: r,
cwd: n,
allowlistEval: await evaluateCommand(r, n)
});
};
const o = resolveSystemRunCommandRequest({
command: e.prepared.argv,
rawCommand: e.prepared.rawCommand
});
const s = extractPreparedNodeShellPayload(e.prepared.argv) ?? (o.ok ? o.shellPayload : null);
await addCommandEval(a, s, n);
const c = s?.trim() || t;
const l = a.find((e) => e.command.trim() === c.trim() && e.cwd === n)?.allowlistEval ?? i;
const u = [...a];
await addCommandEval(u, e.prepared.plan.commandPreview, n);
await addCommandEval(u, e.request.command, e.request.workdir);
let d = i.analysisOk;
let f = false;
let p = false;
let m = false;
let h = 0;
const g = e.request.strictInlineEval === true ? u.map((e) => detectInlineEvalInSegments(e.allowlistEval.segments)).find((e) => e !== null) ?? null : null;
if (g) e.request.warnings.push(`Warning: strict inline-eval mode requires reviewer or explicit approval for ${describeInterpreterInlineEval(g)}.`);
if ((e.hostAsk === "always" || e.hostSecurity === "allowlist" || e.prepared.execPolicy?.security === "allowlist" || e.prepared.execPolicy?.ask === "always" || e.request.autoReview === true) && d) try {
const t = e.prepared.plan.policySnapshot?.allowlistRules;
let n = t ? [...t] : void 0;
if (!n) {
const t = await callGatewayTool("exec.approvals.node.get", { timeoutMs: 1e4 }, { nodeId: e.target.nodeId });
if (t?.file && typeof t.file === "object") n = resolveExecApprovalsFromFileInternal({
file: t.file,
agentId: e.prepared.agentId
}).allowlist;
}
if (n) {
m = true;
h = countObsoleteGeneratedExecApprovalRules(n);
const t = await Promise.all(a.map(async (t) => {
const i = await evaluateCommand(t.command, t.cwd, n);
const a = hasExactCommandDurableExecApproval({
allowlist: n,
commandText: t.command
});
let o = false;
const c = e.prepared.rawCommand.trim();
if (c && t.allowlistEval.segments.length > 0 && hasNodeCommandAllowAlwaysMarker({
allowlist: n,
commandText: c
})) {
const i = /* @__PURE__ */ new Set();
for (const e of n) {
if (e.source !== "allow-always") continue;
i.add(`${e.pattern}\x00${e.argPattern ?? ""}`);
}
const a = e.prepared.allowAlwaysCoverage ?? resolveAllowAlwaysPatternCoverage({
segments: [...t.allowlistEval.segments],
cwd: t.cwd,
env: r,
platform: e.target.platform,
strictInlineEval: e.request.strictInlineEval
});
const s = a.patterns.map((e) => `${e.pattern}\x00${e.argPattern ?? ""}`);
o = a.complete && s.length > 0 && s.every((e) => i.has(e));
}
return {
allowlistEligible: !s || t.command.trim() === s.trim(),
exactDurableApprovalSatisfied: a,
nodeCommandDurableApprovalSatisfied: o,
allowlistEval: i,
durableApprovalSatisfied: hasDurableExecApproval({
analysisOk: i.analysisOk,
segmentAllowlistEntries: i.segmentAllowlistEntries,
allowlist: n,
commandText: t.command
})
};
}));
p = t.some((e) => e.durableApprovalSatisfied && (e.allowlistEligible || e.exactDurableApprovalSatisfied) || e.nodeCommandDurableApprovalSatisfied);
f = t.some((e) => e.allowlistEligible && e.allowlistEval.allowlistSatisfied);
d = t.some((e) => e.allowlistEval.analysisOk);
}
} catch {}
const [_] = l.segments;
const v = l.segments.length === 1 && _ !== void 0 && _.resolution?.policyBlocked !== true && !isBlockedShellWrapperCommand(_.argv) && (_.raw === void 0 || _.raw.trim() === c.trim()) ? _.argv : void 0;
if ((e.hostSecurity === "allowlist" || e.prepared.execPolicy?.security === "allowlist") && !f && h > 0) e.request.warnings.push(`${h} older generated exec ${h === 1 ? "rule is" : "rules are"} inactive for this agent on the node because they are not tied to a working directory. Run "openclaw doctor --fix" on the node, then rerun the workflow and choose "Always allow here".`);
const y = resolveNodeAutoApprovalEligibility({
argv: e.prepared.argv,
shellPayload: s,
platform: e.target.platform,
authorizationPlan: l.authorizationPlan,
segmentSatisfiedBy: l.segmentSatisfiedBy
});
const b = l.segments.some((e) => hasPosixShellStartupBeforeInlineCommand(e.argv));
return {
analysisOk: d,
allowlistSatisfied: f,
durableApprovalSatisfied: p,
nodeApprovalPolicyKnown: m && e.prepared.execPolicy !== void 0,
nodeSecurity: e.prepared.execPolicy?.security,
nodeAsk: e.prepared.execPolicy?.ask,
inlineEvalHit: g,
autoReviewBlockedByShellStartup: b,
autoReviewEligibility: y,
allowAlwaysPersistence: e.request.autoReview === true && (b || !y.eligible) ? {
kind: "one-shot",
reasons: ["no-reusable-pattern"]
} : resolveAllowAlwaysPersistenceDecision({
segments: i.segments,
commandText: t,
cwd: n,
env: r,
platform: e.target.platform,
strictInlineEval: e.request.strictInlineEval,
authorizationPlan: i.authorizationPlan,
runtimePayload: g !== null,
preparedCoverage: e.prepared.allowAlwaysCoverage
}),
autoReviewArgv: v
};
}
//#endregion
//#region src/agents/bash-tools.exec-host-node-policy.ts
async function assertCurrentNodeGatewayPolicyAllowsDispatch(e) {
if (e.request.bypassHostApprovalFloors) return;
const t = await resolveExecHostApprovalContext({
agentId: e.request.agentId,
security: e.request.security,
ask: e.request.ask,
host: "node"
});
if (t.hostSecurity === "deny") throw new Error("exec denied: host=node security=deny");
if (e.authority === "human-approval") return;
if (e.authority === "auto-review") {
if (t.hostAsk === "always") throw new Error("exec denied: host=node ask=always requires human approval");
return;
}
if (e.authority === "ask-fallback") {
const n = e.fallbackPolicy;
if (!n || t.hostSecurity !== n.hostSecurity || t.hostAsk !== n.hostAsk || t.askFallback !== n.askFallback) throw new Error("exec denied: host=node fallback policy changed before dispatch");
return;
}
if (!e.currentPolicyAllows?.(t)) throw new Error("exec denied: host=node policy changed before dispatch");
}
//#endregion
//#region src/agents/bash-tools.exec-host-node.ts
const APPROVED_NODE_INVOKE_SCOPES = [WRITE_SCOPE, APPROVALS_SCOPE];
async function executeNodeHostCommand(e) {
const t = captureAgentToolSourceExecutionGuard(e.signal);
const n = await resolveNodeExecutionTarget(e);
e.signal?.throwIfAborted();
const { hostSecurity: r, hostAsk: i, askFallback: a } = e.bypassHostApprovalFloors ? {
hostSecurity: e.security,
hostAsk: e.ask,
askFallback: "deny"
} : await resolveExecHostApprovalContext({
agentId: e.agentId,
security: e.security,
ask: e.ask,
host: "node"
});
const o = await prepareNodeSystemRun({
request: {
...e,
security: r,
ask: i
},
target: n
});
const s = await analyzeNodeApprovalRequirement({
request: e,
target: n,
prepared: o,
hostSecurity: r,
hostAsk: i
});
e.signal?.throwIfAborted();
const { analysisOk: c, allowlistSatisfied: l, durableApprovalSatisfied: u, nodeApprovalPolicyKnown: d, nodeSecurity: f, nodeAsk: p, inlineEvalHit: m, autoReviewBlockedByShellStartup: h, autoReviewEligibility: g, autoReviewArgv: _, allowAlwaysPersistence: v } = s;
const y = d && p !== void 0 ? maxAsk(i, p) : "always";
const b = resolveExecApprovalAllowedDecisions({
ask: y,
allowAlwaysPersistence: v
});
const x = resolveExecApprovalUnavailableDecisions({
ask: y,
allowAlwaysPersistence: v
});
const S = x.length > 0 ? { unavailableDecisions: x } : {};
const C = f === void 0 ? r : minSecurity(r, f);
const w = p === void 0 ? i : maxAsk(i, p);
if (C === "deny") throw new Error("exec denied: host=node security=deny");
const T = requiresExecApproval({
ask: w,
security: C,
analysisOk: c,
allowlistSatisfied: l,
durableApprovalSatisfied: u
}) || m !== null;
if (!T && C === "allowlist" && !(u || c && l)) throw new Error("exec denied: host=node allowlist miss (ask=off)");
if (T && e.nonInteractiveApproval) {
const t = `Exec denied (approval_required): ${e.command}`;
return buildExecApprovalDeniedToolResult(t, o.cwd, "approval_required");
}
const registerNodeApproval = async (t, a = {}) => await registerExecApprovalRequestForHostOrThrow({
approvalId: t,
systemRunPlan: o.plan,
env: n.env,
workdir: o.cwd,
host: "node",
nodeId: n.nodeId,
trigger: e.trigger,
toolCallId: e.toolCallId,
security: r,
ask: i,
...S,
commandHighlighting: e.commandHighlighting,
agentId: o.agentId,
sessionKey: o.sessionKey,
approvalReviewerDeviceIds: e.approvalReviewerDeviceId ? [e.approvalReviewerDeviceId] : void 0,
...a,
...buildExecApprovalTurnSourceContext(e)
});
const resolveCurrentTimeoutFallback = async () => {
try {
const t = await resolveExecHostApprovalContext({
agentId: e.agentId,
security: e.security,
ask: e.ask,
host: "node"
});
if (t.askFallback === "deny") return {
approvedByAsk: false,
deniedReason: "approval-timeout",
hostSecurity: t.hostSecurity,
hostAsk: t.hostAsk,
askFallback: t.askFallback,
requiresExplicitApproval: false
};
const r = await analyzeNodeApprovalRequirement({
request: {
...e,
warnings: []
},
target: n,
prepared: o,
hostSecurity: t.hostSecurity,
hostAsk: t.hostAsk
});
const i = t.askFallback === "full" || r.durableApprovalSatisfied || r.analysisOk && r.allowlistSatisfied;
return {
approvedByAsk: i,
deniedReason: i ? null : "approval-timeout: allowlist-miss",
hostSecurity: t.hostSecurity,
hostAsk: t.hostAsk,
askFallback: t.askFallback,
requiresExplicitApproval: r.inlineEvalHit !== null
};
} catch {
return {
approvedByAsk: false,
deniedReason: "approval-timeout: policy-unavailable",
hostSecurity: "deny",
hostAsk: i,
askFallback: "deny",
requiresExplicitApproval: false
};
}
};
let E = false;
let D = null;
let O;
let k;
let A = "current-policy";
let j;
if (T) {
if (e.autoReview === true && i !== "always" && h) e.warnings.push(EXEC_AUTO_REVIEW_SHELL_STARTUP_WARNING);
if (e.autoReview === true && i !== "always" && !h && !g.eligible) e.warnings.push(g.reason);
const s = c && _ !== void 0;
const y = e.autoReview === true && i !== "always" && (!d || p === "always" || f !== void 0 && minSecurity(r, f) !== r);
let x = y || e.autoReview === true && h || e.autoReview === true && !g.eligible || e.autoReview === true && i !== "always" && !s;
if (e.autoReview === true && i !== "always" && s && !y && !h && g.eligible) {
const t = e.autoReviewer ?? defaultExecAutoReviewer;
const i = m !== null ? "strict-inline-eval" : r === "allowlist" && (!c || !l) && !u ? "allowlist-miss" : "approval-required";
const a = resolveExecAutoReviewDecision(t, {
command: o.rawCommand,
argv: _,
cwd: o.cwd,
envKeys: Object.keys(n.env ?? {}).toSorted(),
host: "node",
reason: i,
analysis: {
parsed: c,
allowlistMatched: l,
durableApprovalMatched: u,
inlineEval: m !== null
},
agent: {
id: o.agentId,
sessionKey: o.sessionKey
}
});
const s = e.signal ? await abortable(e.signal, a) : await a;
e.signal?.throwIfAborted();
switch (s.decision) {
case "deny": return buildExecAutoReviewDeniedToolResult({
command: o.rawCommand,
cwd: o.cwd,
decision: s,
toolCallId: e.toolCallId
});
case "ask": break;
case "allow-once": {
if (s.risk !== "low" && s.risk !== "medium") break;
const e = randomUUID();
await registerNodeApproval(e, {
requireDeliveryRoute: false,
suppressDelivery: true
});
await callGatewayTool("exec.approval.resolve", { timeoutMs: 15e3 }, {
id: e,
decision: "allow-once"
}, {
scopes: [APPROVALS_SCOPE],
requireAgentRuntimeIdentity: true
});
E = true;
D = "allow-once";
k = e;
A = "auto-review";
break;
}
default: throw new Error("Unsupported exec auto-review decision", { cause: s });
}
if (!E) {
x = true;
e.warnings.push(`Exec auto-review deferred to human approval (${formatExecAutoReviewAssessment(s)}): ${s.rationale}`);
}
}
if (!E) {
const s = {
askFallback: a,
resolveTimedOut: async () => {
const e = await resolveCurrentTimeoutFallback();
return {
approvedByAsk: e.approvedByAsk,
deniedReason: e.deniedReason,
context: e
};
},
requiresExplicitApproval: (e) => e?.requiresExplicitApproval ?? m !== null,
requiresAutoReviewHumanApproval: x
};
const c = await createExecApprovalRequestRoute({
warnings: e.warnings,
approvalRunningNoticeMs: e.approvalRunningNoticeMs,
createApprovalSlug,
turnSourceChannel: e.turnSourceChannel,
turnSourceAccountId: e.turnSourceAccountId,
register: registerNodeApproval,
...s
});
const { approvalId: l, approvalSlug: u, warningText: d, expiresAtMs: f, preResolvedDecision: p, initiatingSurface: h, sentApproverDms: g, unavailableReason: _ } = c;
if (c.kind === "inline") {
const t = c.state;
const n = t.timeoutContext;
if (t.deniedReason || !t.approvedByAsk) throw new Error(buildHeadlessExecApprovalDeniedMessage({
trigger: e.trigger,
host: "node",
security: n?.hostSecurity ?? r,
ask: n?.hostAsk ?? i,
askFallback: n?.askFallback ?? a
}));
E = t.approvedByAsk;
O = "ask-fallback";
A = "ask-fallback";
j = n;
D = null;
k = l;
} else if (_ === null && e.approvalFollowupMode === void 0) {
const t = await resolveExecApprovalWaitOutcome({
approvalId: l,
expiresAtMs: f,
preResolvedDecision: p,
signal: e.signal,
...s
});
e.signal?.throwIfAborted();
if (t.kind !== "resolved") throw new Error(`exec denied: ${t.kind}\n${formatExecDeniedReasonMessage(t.kind)}`);
if (t.state.deniedReason || !t.state.approvedByAsk) {
const e = t.state.deniedReason ?? "approval-required";
throw new Error(`exec denied: ${e}\n${formatExecDeniedReasonMessage(e)}`);
}
E = true;
k = l;
D = t.decision === "allow-always" && m === null && v.kind !== "one-shot" ? "allow-always" : t.decision === "allow-once" || t.decision === "allow-always" ? "allow-once" : null;
O = t.decision === null ? "ask-fallback" : void 0;
A = O ?? "human-approval";
j = t.state.timeoutContext;
} else {
const r = buildExecApprovalFollowupTarget(e, l);
const sendDeniedFollowup = (t) => sendExecApprovalFollowupResult(r, `Exec denied (node=${n.nodeId} id=${l}, ${t}): ${e.command}`);
const sendApprovalRequestFailedFollowup = async () => {
if (!e.signal?.aborted) await sendDeniedFollowup("approval-request-failed");
};
let i = false;
let a = false;
(async () => {
const c = await resolveExecApprovalWaitOutcome({
approvalId: l,
expiresAtMs: f,
preResolvedDecision: p,
signal: e.signal,
...s
});
if (c.kind !== "resolved") {
if (c.kind === "request-failed") await sendApprovalRequestFailedFollowup();
return;
}
const { decision: u, state: d } = c;
const { approvedByAsk: h, deniedReason: g } = d;
const _ = d.timeoutContext;
const y = u === null ? "ask-fallback" : void 0;
const b = g ? null : _ ? h ? "allow-once" : null : u === "allow-once" || u === "allow-always" ? u : null;
if (g) {
await sendDeniedFollowup(g);
return;
}
try {
await assertCurrentNodeGatewayPolicyAllowsDispatch({
request: e,
authority: y ? "ask-fallback" : "human-approval",
fallbackPolicy: _ ?? void 0
});
if (e.signal?.aborted) return;
i = true;
const s = await runWithAgentToolSourceExecutionScope(t, () => invokeNodeSystemRun({
source: t,
invokeWaitMs: n.invokeWaitMs,
invoke: buildNodeSystemRunInvoke({
target: n,
prepared: o,
request: e,
approved: y ? void 0 : h,
approvalDecision: y ? null : b === "allow-always" && (m !== null || v.kind === "one-shot") ? "allow-once" : b,
approvalSource: y,
runId: l,
suppressNotifyOnExit: true
}),
scopes: APPROVED_NODE_INVOKE_SCOPES,
signal: e.signal
}));
a = true;
if (!s.ok) {
await sendExecApprovalFollowupResult(r, formatNodeInvokeFailureFollowup({
failure: s.failure,
nodeId: n.nodeId,
approvalId: l,
command: e.command
}));
return;
}
const c = s.raw;
const u = c?.payload && typeof c.payload === "object" ? c.payload : {};
const d = formatExecApprovalContinuationSourceOutput([
{
label: "stdout",
value: u.stdout
},
{
label: "stderr",
value: u.stderr
},
{
label: "error",
value: u.error
}
]);
const f = u.timedOut ? "timeout" : `code ${u.exitCode ?? "?"}`;
const p = d ? `Exec finished (node=${n.nodeId} id=${l}, ${f})\n${d}` : `Exec finished (node=${n.nodeId} id=${l}, ${f})`;
await sendExecApprovalFollowupResult(r, p);
} catch {
if (e.signal?.aborted || a) return;
await sendDeniedFollowup("invoke-failed");
}
})().catch(async (t) => {
if (i || e.signal?.aborted || isExecApprovalRunAbortedError(t)) return;
await sendApprovalRequestFailedFollowup();
}).catch(() => void 0);
return buildExecApprovalPendingToolResult({
host: "node",
command: e.command,
cwd: e.workdir,
warningText: d,
approvalId: l,
approvalSlug: u,
expiresAtMs: f,
initiatingSurface: h,
sentApproverDms: g,
unavailableReason: _,
allowedDecisions: b,
nodeId: n.nodeId,
processContinuationAvailable: e.processContinuationAvailable
});
}
}
}
e.signal?.throwIfAborted();
const M = buildNodeSystemRunInvoke({
target: n,
prepared: o,
request: e,
approved: O ? void 0 : E,
approvalDecision: O ? null : D,
approvalSource: O,
runId: k
});
await assertCurrentNodeGatewayPolicyAllowsDispatch({
request: e,
authority: A,
fallbackPolicy: j,
currentPolicyAllows: (e) => !requiresExecApproval({
ask: e.hostAsk,
security: e.hostSecurity,
analysisOk: c,
allowlistSatisfied: l,
durableApprovalSatisfied: u
}) && (e.hostSecurity !== "allowlist" || u || c && l) && m === null
});
e.signal?.throwIfAborted();
return dispatchNodeSystemRun({
source: t,
request: e,
target: n,
invoke: M,
...(E || O) && k ? { scopes: APPROVED_NODE_INVOKE_SCOPES } : {}
});
}
//#endregion
//#region src/agents/bash-tools.exec-workdir.ts
/**
* Internal exec workdir resolver.
* Owns cwd selection and validation before exec approval, hooks, preflight, or
* process launch can observe an invalid selected working directory.
*/
function unavailable(e) {
return {
kind: "unavailable",
requestedCwd: e
};
}
function resolveExistingHostWorkdir(e) {
return safeStatSync(e)?.isDirectory() ? safeRealpathSync(e) ?? path.resolve(e) : null;
}
function safeCurrentCwd() {
try {
return process.cwd();
} catch {
return null;
}
}
function mapContainerWorkdirToHost(e) {
const t = normalizeContainerPath(e.workdir);
const n = [...e.includeReadOnlySkillMounts ? (e.sandbox.readOnlyWorkspaceSkillMounts ?? []).map((e) => ({
hostRoot: path.resolve(e.hostPath),
containerRoot: normalizeContainerPath(e.containerPath)
})) : [], ...e.includePrimaryWorkspace === false ? [] : [{
hostRoot: path.resolve(e.sandbox.workspaceDir),
containerRoot: normalizeContainerPath(e.sandbox.containerWorkdir)
}]].filter((e) => e.containerRoot !== ".").toSorted((e, t) => t.containerRoot.length - e.containerRoot.length);
for (const e of n) {
const n = mapContainerWorkdirRelativeToRoot({
workdir: t,
root: e.containerRoot
});
if (n === null) continue;
return {
hostPath: path.resolve(e.hostRoot, ...n),
hostRoot: e.hostRoot,
containerRoot: e.containerRoot
};
}
}
function normalizeContainerPath(e) {
const t = e.trim().replace(/\\/g, "/");
if (!t) return ".";
const n = path.posix.normalize(t);
return n === "/" ? n : n.replace(/\/+$/g, "");
}
function mapContainerWorkdirRelativeToRoot(e) {
if (e.workdir === e.root) return [];
if (e.root === "/") return path.posix.isAbsolute(e.workdir) ? e.workdir.split("/").filter(Boolean) : null;
if (!e.workdir.startsWith(`${e.root}/`)) return null;
return e.workdir.slice(e.root.length + 1).split("/").filter(Boolean);
}
function joinContainerWorkdir(e, t) {
return t ? path.posix.join(e, t) : e;
}
function hasParentPathSegment(e) {
return e.replace(/\\/g, "/").split("/").some((e) => e === "..");
}
function isContainerWorkdirInsideRoot(e) {
const t = normalizeContainerPath(e.root);
const n = normalizeContainerPath(e.workdir);
if (t === "/") return path.posix.isAbsolute(n);
return n === t || n.startsWith(`${t}/`);
}
function resolveBackendWorkdirRoots(e) {
return [...new Set([e.containerWorkdir, ...e.workdirRoots ?? []].map((e) => normalizeContainerPath(e ?? "")).filter((e) => path.posix.isAbsolute(e)))];
}
function resolveBackendContainerWorkdir(e) {
const t = normalizeContainerPath(e.sandbox.containerWorkdir);
const n = resolveBackendWorkdirRoots(e.sandbox);
const r = normalizeContainerPath(e.workdir);
if (path.posix.isAbsolute(r)) return n.some((e) => isContainerWorkdirInsideRoot({
root: e,
workdir: r
})) ? r : null;
if (r === ".." || r.startsWith("../")) return null;
return joinContainerWorkdir(t, r === "." ? "" : r);
}
async function mapExistingHostPath(e) {
let t;
try {
t = await assertSandboxPath({
filePath: e.hostPath,
cwd: e.hostRoot,
root: e.hostRoot
});
} catch {
return { kind: "invalid" };
}
const n = safeStatSync(t.resolved);
const r = t.relative.split(path.sep).join(path.posix.sep);
if (!n) return {
kind: "missing",
relative: r
};
if (!n.isDirectory()) return { kind: "invalid" };
return {
kind: "available",
workdir: {
hostCwd: t.resolved,
containerCwd: joinContainerWorkdir(e.containerRoot, r),
scriptPreflightCwd: t.resolved
}
};
}
async function validateBackendWorkdir(e) {
const t = await e.sandbox.validateWorkdir?.(e.workdir.containerCwd);
return t ? {
...e.workdir,
containerCwd: t
} : null;
}
function resolveBackendHostWorkdirCandidate(e) {
if (!path.isAbsolute(e.workdir)) return {
hostPath: path.resolve(e.sandbox.workspaceDir, e.workdir),
hostRoot: path.resolve(e.sandbox.workspaceDir),
containerRoot: normalizeContainerPath(e.sandbox.containerWorkdir),
failIfInvalid: false
};
const t = path.resolve(e.workdir);
const n = mapContainerWorkdirToHost({
workdir: e.workdir,
sandbox: e.sandbox,
includeReadOnlySkillMounts: true,
includePrimaryWorkspace: false
});
if (n) return {
...n,
failIfInvalid: false
};
if (isPathInside(path.resolve(e.sandbox.workspaceDir), t)) return {
hostPath: t,
hostRoot: path.resolve(e.sandbox.workspaceDir),
containerRoot: normalizeContainerPath(e.sandbox.containerWorkdir),
failIfInvalid: true
};
const r = mapContainerWorkdirToHost({
workdir: e.workdir,
sandbox: e.sandbox
});
return r ? {
...r,
failIfInvalid: false
} : null;
}
async function resolveBackendValidatedSandboxWorkdir(e) {
const t = resolveExistingHostWorkdir(e.sandbox.workspaceDir);
if (!t) return null;
const n = resolveBackendHostWorkdirCandidate(e);
let r;
if (n) {
const e = await mapExistingHostPath(n);
if (e.kind === "available") r = e.workdir;
else if (e.kind === "missing") r = {
hostCwd: t,
containerCwd: joinContainerWorkdir(n.containerRoot, e.relative),
scriptPreflightCwd: null
};
else if (n.failIfInvalid) return null;
}
if (!r) {
const n = resolveBackendContainerWorkdir(e);
if (!n) return null;
r = {
hostCwd: t,
containerCwd: n,
scriptPreflightCwd: null
};
}
return await validateBackendWorkdir({
workdir: r,
sandbox: e.sandbox
});
}
async function resolveHostValidatedSandboxWorkdir(e) {
const t = mapContainerWorkdirToHost({
workdir: e.workdir,
sandbox: e.sandbox,
includeReadOnlySkillMounts: true
});
const n = t?.hostPath ?? e.workdir;
const r = t?.hostRoot ?? e.sandbox.workspaceDir;
const i = t?.containerRoot ?? e.sandbox.containerWorkdir;
try {
const e = await assertSandboxPath({
filePath: n,
cwd: r,
root: r
});
if (!(await fs.stat(e.resolved)).isDirectory()) return null;
const t = joinContainerWorkdir(i, e.relative ? e.relative.split(path.sep).join(path.posix.sep) : "");
return {
hostCwd: e.resolved,
containerCwd: t,
scriptPreflightCwd: e.resolved
};
} catch {
return null;
}
}
async function resolveSandboxWorkdir(e) {
if (hasParentPathSegment(e.workdir)) return null;
if (e.sandbox.workdirValidation === "backend") return await resolveBackendValidatedSandboxWorkdir(e);
return await resolveHostValidatedSandboxWorkdir(e);
}
function formatUnavailableWorkdirFailure(e) {
return [
`workdir "${e}" is unavailable or not a directory: command was not executed.`,
"workdir is treated as a literal path; shell expansions such as \"~\" are not applied.",
"Use an existing directory, omit an explicit workdir to use the default cwd, or update the configured default cwd."
].join(" ");
}
async function resolveExecWorkdir(e) {
const t = normalizeOptionalString(e.workdir);
if (e.workdir !== void 0 && e.workdir !== "" && !t) return unavailable(e.workdir);
if (e.host === "node") {
const t = readNonBlankString(e.workdir) ?? readNonBlankString(e.nodeCwd);
return t ? {
kind: "node",
remoteCwd: t
} : { kind: "node" };
}
const n = normalizeOptionalString(e.defaultCwd);
if (e.host === "sandbox") {
const r = e.sandbox;
if (!r) throw new Error("exec internal error: sandbox workdir resolution requires sandbox config");
const i = t ?? n ?? r.containerWorkdir;
const a = await resolveSandboxWorkdir({
workdir: i,
sandbox: r
});
return a ? {
kind: "sandbox",
...a
} : unavailable(i);
}
const r = t ?? n ?? safeCurrentCwd();
if (!r) return unavailable("current working directory");
let i = r;
if (t && n && !path.isAbsolute(r)) {
const e = resolveExistingHostWorkdir(n);
if (!e) return unavailable(n);
i = `${e}${path.sep}${r}`;
}
const a = resolveExistingHostWorkdir(i);
return a ? {
kind: "local",
hostCwd: a
} : unavailable(r);
}
//#endregion
//#region src/agents/bash-tools.exec-request-preparation.ts
const resolvedExecEnvPreparedStates = /* @__PURE__ */ new WeakMap();
const execHookContexts = /* @__PURE__ */ new WeakMap();
const resolvedExecWorkdirPreparedStates = /* @__PURE__ */ new WeakMap();
const XML_ARG_VALUE_EXEC_PARAM_KEYS = [
"command",
"workdir",
"host",
"ask",
"node"
];
function assertSupportedExecParams(e) {
if (!isRecord(e)) return;
if (typeof e.command === "string" && e.command.includes("\0")) throw new ToolInputError("Execution command must not contain NUL bytes. Remove them and retry.");
if (e.awaitResults !== void 0 && typeof e.awaitResults !== "boolean") throw new ToolInputError("exec awaitResults must be a boolean");
if (e.awaitResults === true && e.background === true) throw new ToolInputError("exec with awaitResults=true cannot be detached with background=true");
if (Object.hasOwn(e, "timeout")) throw new ToolInputError("exec parameter \"timeout\" is unsupported; use \"timeoutSeconds\" instead");
if (Object.hasOwn(e, "cwd")) throw new ToolInputError("exec parameter \"cwd\" is unsupported; use \"workdir\" instead");
}
function isExecToolArgsObject(e) {
return isRecord(e);
}
function filterPluginExecEnv(e) {
const t = {};
for (const [n, r] of Object.entries(e)) {
const e = normalizeHostOverrideEnvVarKey(n);
if (!e) continue;
const i = e.toUpperCase();
if (i === "PATH" || i === "OPENCLAW_CLI" || isDangerousHostEnvVarName(i) || isDangerousHostEnvOverrideVarName(i)) continue;
t[e] = r;
}
return Object.keys(t).length > 0 ? t : void 0;
}
/** Capture notification routing and child identity before process lifetime detaches. */
function resolveExecNotificationDefaults(e) {
const t = e?.notifyOnExit !== false;
const n = e?.notifyOnExitEmptySuccess !== false;
const r = normalizeOptionalString(e?.notifySessionKey ?? e?.runSessionKey ?? e?.sessionKey);
const i = parseAgentSessionKey(r);
let a;
const resolveSubagentSession = () => a ??= (async () => {
if (!r || !e?.config || !i?.rest.startsWith("dashboard:")) return isSubagentEnvelopeSession(r);
const { readSessionEntriesFromStoreInWorker: t } = await import("./session-entry-read-runtime-24no1ay9.mjs");
const n = await t({
agentId: i.agentId,
sessionKeys: [r],
snapshotFields: [],
storePath: resolveSessionStorePathCore(e.config.session?.store, { agentId: i.agentId })
});
return isSubagentEnvelopeSession(r, { entry: n.entries.find(({ sessionKey: e }) => e === r)?.entry });
})().catch(() => {
a = void 0;
return isSubagentEnvelopeSession(r);
});
return {
notifyOnExit: t,
notifyOnExitEmptySuccess: n,
notifySessionKey: r,
resolveSubagentSession,
notifyDeliveryContext: normalizeDeliveryContext({
channel: e?.messageProvider,
to: e?.currentMessagingTarget ?? e?.currentChannelId,
accountId: e?.accountId,
threadId: e?.currentThreadTs
})
};
}
function resolveExecPreparedRunEnvironment(e) {
return {
...e?.preparedRunEnvironment ?? prepareGitHubToolEnvironment({
config: e?.config ?? {},
sourceConfig: getActiveSecretsRuntimeConfigSnapshot()?.sourceConfig,
agentId: e?.executionAgentId ?? e?.agentId ?? "main"
}),
localProcessEnv: installationTargetEnv(getInstallationTarget())
};
}
function createExecRequestPreparation(e) {
const normalizeParams = (e) => stripMalformedXmlArgValueSuffixFromKeys(e, XML_ARG_VALUE_EXEC_PARAM_KEYS);
const prepareParamsWithResolvedExecWorkdir = async (t) => {
if (typeof t !== "object" || t === null || Array.isArray(t)) return t;
const n = normalizeParams(t);
let r;
try {
r = e.resolveHostForParams(n);
} catch {
return n;
}
if (r === "sandbox" && !e.defaults?.sandbox) return n;
if (r === "sandbox" && e.defaults?.sandbox?.workdirValidation === "backend") return n;
const i = await resolveExecWorkdir({
host: r,
workdir: n.workdir,
defaultCwd: e.defaults?.cwd,
nodeCwd: e.defaults?.nodeCwd,
sandbox: e.defaults?.sandbox
});
resolvedExecWorkdirPreparedStates.set(n, {
host: r,
inputWorkdir: n.workdir,
resolution: i
});
return n;
};
const shouldDeferResolveExecEnvUntilWorkdirValidated = (t) => {
try {
return e.resolveHostForParams(t) === "sandbox" && e.defaults?.sandbox?.workdirValidation === "backend";
} catch {
return false;
}
};
const prepareParamsWithResolvedExecEnv = async (t, n) => {
const r = normalizeParams(t);
if (!r.command) return r;
if (resolvedExecEnvPreparedStates.has(r)) return r;
const i = getGlobalHookRunner();
if (!i?.hasHooks("resolve_exec_env") || typeof i.runResolveExecEnv !== "function") {
resolvedExecEnvPreparedStates.set(r, {});
return r;
}
let a;
try {
a = e.resolveHostForParams(r);
} catch {
return r;
}
const o = n?.hookContext?.sessionId ?? e.defaults?.sessionId;
const s = filterPluginExecEnv(await i.runResolveExecEnv({
sessionKey: n?.hookContext?.sessionKey ?? e.defaults?.sessionKey,
toolName: "exec",
host: a
}, {
agentId: n?.hookContext?.agentId ?? e.agentId,
sessionKey: n?.hookContext?.sessionKey ?? e.defaults?.sessionKey,
...o ? { sessionId: o } : {},
messageProvider: e.defaults?.messageProvider,
channelId: e.defaults?.currentChannelId ?? n?.hookContext?.channelId,
...e.defaults?.channelContext ? { channelContext: e.defaults.channelContext } : {}
}));
resolvedExecEnvPreparedStates.set(r, {
host: a,
...s ? { pluginEnv: s } : {}
});
return r;
};
const prepareBeforeToolCallParams = async (e, t) => {
assertSupportedExecParams(e);
const n = await prepareParamsWithResolvedExecWorkdir(e);
if (!isExecToolArgsObject(n)) return n;
const r = t.hookContext;
execHookContexts.set(n, r);
if (resolvedExecWorkdirPreparedStates.get(n)?.resolution.kind === "unavailable" || shouldDeferResolveExecEnvUntilWorkdirValidated(n)) return n;
return prepareParamsWithResolvedExecEnv(n, { hookContext: r });
};
const finalizeBeforeToolCallParams = (t, n) => {
const r = resolvedExecEnvPreparedStates.get(n);
const i = execHookContexts.get(n);
const a = resolvedExecWorkdirPreparedStates.get(n);
if (!r && !i && !a) return t;
if (!isExecToolArgsObject(t)) return t;
const o = t;
const invalidatePreparedParams = () => {
const e = { ...o };
execHookContexts.set(e, i);
return e;
};
let s;
const resolveFinalHost = () => {
s ??= e.resolveHostForParams(o);
return s;
};
try {
if (r?.host && o.command && resolveFinalHost() !== r.host) return invalidatePreparedParams();
if (a && (resolveFinalHost() !== a.host || o.workdir !== a.inputWorkdir)) return invalidatePreparedParams();
} catch {
return invalidatePreparedParams();
}
if (r) resolvedExecEnvPreparedStates.set(o, r);
if (i) execHookContexts.set(o, i);
if (a) resolvedExecWorkdirPreparedStates.set(o, a);
return o;
};
return {
normalizeParams,
prepareBeforeToolCallParams,
finalizeBeforeToolCallParams,
prepareParamsWithResolvedExecEnv,
isResolveExecEnvPrepared: (e) => resolvedExecEnvPreparedStates.has(e),
getExecHookContext: (e) => execHookContexts.get(e),
getResolvedExecWorkdirPreparedState: (e) => resolvedExecWorkdirPreparedStates.get(e),
getResolvedExecEnvPreparedState: (e) => resolvedExecEnvPreparedStates.get(e)
};
}
function resolvePreparedExecEnvironment(e) {
if (e.localProcessEnv && e.host !== "gateway") throw new Error(LOCAL_INSTALLATION_TARGET_UNSUPPORTED);
const t = coerceEnv(process.env);
const n = {
senderId: normalizeOptionalString(e.channelContext?.sender?.id),
chatId: normalizeOptionalString(e.channelContext?.chat?.id),
...e.subagentExecution ? { subagent: true } : {}
};
const r = buildExecRoutingEnv(n);
const i = e.execParams.env !== void 0 || e.pluginEnv !== void 0 ? {
...e.execParams.env,
...e.pluginEnv
} : void 0;
const a = e.storeEnv ? sanitizeHostExecEnvWithDiagnostics({
baseEnv: {},
overrides: e.storeEnv,
blockPathOverrides: true
}) : void 0;
const { [OPENCLAW_CLI_ENV_VAR]: o, ...s } = a?.env ?? {};
let c = Object.keys(s).length > 0 ? s : void 0;
const l = /* @__PURE__ */ new Set([...a?.rejectedOverrideBlockedKeys ?? [], ...a?.rejectedOverrideInvalidKeys ?? []]);
if (e.storeEnv && Object.hasOwn(e.storeEnv, "OPENCLAW_CLI")) l.add(OPENCLAW_CLI_ENV_VAR);
if (e.host === "sandbox" && c) {
const t = sanitizeEnvVars(c);
c = t.allowed;
for (const e of t.blocked) l.add(e);
if (t.warnings.length > 0) e.warnings.push(`Warning: secret store environment entries need attention: ${t.warnings.join("; ")}.`);
}
if (l.size > 0) e.warnings.push(`Warning: secret store environment entries were not applied for host=${e.host}: ${Array.from(l).toSorted().join(", ")}.`);
const u = c && Object.keys(c).length > 0 ? {
...c,
...i
} : i;
const d = e.storeSecretEnv ? {
...c,
...e.storeSecretEnv,
...i
} : u;
const f = e.host === "sandbox" ? null : sanitizeHostExecEnvWithDiagnostics({
baseEnv: t,
overrides: u,
blockPathOverrides: true
});
if (f && u && (f.rejectedOverrideBlockedKeys.length > 0 || f.rejectedOverrideInvalidKeys.length > 0)) {
const e = f.rejectedOverrideBlockedKeys;
const t = f.rejectedOverrideInvalidKeys;
const n = e.includes("PATH");
if (n && e.length === 1 && t.length === 0) throw new Error("Security Violation: Custom 'PATH' variable is forbidden during host execution.");
if (e.length === 1 && t.length === 0) throw new Error(`Security Violation: Environment variable '${e[0]}' is forbidden during host execution.`);
const r = [];
if (e.length > 0) r.push(`blocked override keys: ${e.join(", ")}`);
if (t.length > 0) r.push(`invalid non-portable override keys: ${t.join(", ")}`);
const i = r.join("; ");
if (n) throw new Error(`Security Violation: Custom 'PATH' variable is forbidden during host execution (${i}).`);
throw new Error(`Security Violation: ${i}.`);
}
const p = e.sandbox && e.host === "sandbox" ? buildSandboxEnv({
defaultPath: DEFAULT_PATH,
paramsEnv: u,
sandboxEnv: e.sandbox.env,
containerWorkdir: e.containerWorkdir ?? e.sandbox.containerWorkdir
}) : f?.env ?? t;
if (!e.sandbox && e.host === "gateway" && !d?.PATH) {
const e = getShellPathFromLoginShell({
env: process.env,
timeoutMs: resolveShellEnvFallbackTimeoutMs(process.env)
});
applyShellPath(p, e);
}
if (e.host === "node") {
if (omitGatewayAgentCliPath(e.defaultPathPrepend).length > 0) e.warnings.push("Warning: tools.exec.pathPrepend is ignored for host=node. Configure PATH on the node host/service instead.");
} else applyPathPrepend(p, e.defaultPathPrepend);
if (e.host === "gateway" && e.managedLocalIdentity === false) for (const e of ["GH_TOKEN", "GITHUB_TOKEN"]) {
const t = process.env[e];
if (typeof t === "string") p[e] = t;
}
if (e.storeSecretEnv) {
for (const [t, n] of Object.entries(e.storeSecretEnv)) if (!i || !Object.hasOwn(i, t)) p[t] = n;
}
const m = {
...e.localProcessEnv,
...e.credentialScrubEnv,
...e.host === "gateway" ? e.localIdentityEnv : void 0
};
const h = e.host === "gateway" && e.localGitConfigParameters ? { GIT_CONFIG_PARAMETERS: [resolveEnvironmentValue(m, "GIT_CONFIG_PARAMETERS") ?? resolveEnvironmentValue(p, "GIT_CONFIG_PARAMETERS"), e.localGitConfigParameters].filter(Boolean).join(" ") } : void 0;
const g = mergeProcessEnv([
p,
m,
r,
h
]);
const _ = e.host === "node" || !r ? d : {
...d,
...r
};
return {
env: g,
...e.host === "node" && r ? { executionContext: n } : {},
...e.host !== "node" && Object.keys(m).length > 0 ? { requestedEnv: {
..._,
...m
} } : { requestedEnv: _ }
};
}
//#endregion
//#region src/agents/bash-tools.exec-script-target.ts
const PREFLIGHT_ENV_OPTIONS_WITH_VALUES = /* @__PURE__ */ new Set([
"-C",
"-S",
"-u",
"--argv0",
"--block-signal",
"--chdir",
"--default-signal",
"--ignore-signal",
"--split-string",
"--unset"
]);
function isShellEnvAssignmentToken(e) {
return /^[A-Za-z_][A-Za-z0-9_]*=.*$/u.test(e);
}
function stripPreflightAssignments(e) {
let t = 0;
while (isShellEnvAssignmentToken(e[t] ?? "")) t += 1;
return e.slice(t);
}
function parsePreflightShellSegment(e) {
const t = splitShellArgs(e.trim()) ?? [];
return stripPreflightAssignments(stripPreflightEnvPrefix(/^(?:if|then|do|elif|else|while|until|time)$/i.test(t[0] ?? "") ? t.slice(1) : t));
}
function isEnvExecutableToken(e) {
if (!e) return false;
const t = normalizeOptionalLowercaseString(e.split(/[\\/]/u).at(-1)) ?? "";
return (t.endsWith(".exe") ? t.slice(0, -4) : t) === "env";
}
function stripPreflightEnvPrefix(e) {
if (e.length === 0) return e;
let t = 0;
while (t < e.length && isShellEnvAssignmentToken(e.at(t) ?? "")) t += 1;
if (!isEnvExecutableToken(e[t])) return e;
t += 1;
while (t < e.length) {
const n = e.at(t);
if (n === void 0) break;
if (n === "--") {
t += 1;
break;
}
if (isShellEnvAssignmentToken(n)) {
t += 1;
continue;
}
if (!n.startsWith("-") || n === "-") break;
t += 1;
const r = n.indexOf("=");
const i = n.includes("=") ? n.slice(0, r) : n;
if (PREFLIGHT_ENV_OPTIONS_WITH_VALUES.has(i) && !n.includes("=") && t < e.length) t += 1;
}
return e.slice(t);
}
function findFirstPythonScriptArg(e) {
const t = /* @__PURE__ */ new Set([
"-W",
"-X",
"-Q",
"--check-hash-based-pycs"
]);
for (let n = 0; n < e.length; n += 1) {
const r = e.at(n);
if (r === void 0) break;
if (r === "--") {
const t = e.at(n + 1);
return t && normalizeLowercaseStringOrEmpty(t).endsWith(".py") ? t : null;
}
if (r === "-") return null;
if (r.startsWith("-c") || r.startsWith("-m")) return null;
if (t.has(r)) {
n += 1;
continue;
}
if (r.startsWith("-")) continue;
return normalizeLowercaseStringOrEmpty(r).endsWith(".py") ? r : null;
}
return null;
}
function findNodeScriptArgs(e) {
const t = /* @__PURE__ */ new Set([
"-r",
"--require",
"--import"
]);
const n = [];
const addScript = (e) => {
if (e && normalizeLowercaseStringOrEmpty(e).endsWith(".js")) n.push(e);
};
let r = false;
for (let n = 0; n < e.length; n += 1) {
const i = e.at(n);
if (i === void 0) break;
if (i === "--") {
if (!r) addScript(e.at(n + 1));
break;
}
if (i.startsWith("-e") || i.startsWith("-p") || i === "--eval" || i === "--print" || i.startsWith("--eval=") || i.startsWith("--print=")) {
r = true;
if (i === "-e" || i === "-p" || i === "--eval" || i === "--print") n += 1;
continue;
}
if (t.has(i)) {
addScript(e.at(n + 1));
n += 1;
continue;
}
if (i.startsWith("-r") && i.length > 2 || i.startsWith("--require=") || i.startsWith("--import=")) {
addScript(i.startsWith("-r") ? i.slice(2) : i.slice(i.indexOf("=") + 1));
continue;
}
if (i.startsWith("-")) continue;
if (!r) addScript(i);
break;
}
return n;
}
function extractInterpreterScriptTargetFromArgv(e) {
if (!e || e.length === 0) return null;
const [t, ...n] = stripPreflightAssignments(e);
const r = normalizeOptionalLowercaseString(t);
if (!r) return null;
if (/^python(?:3(?:\.\d+)?)?$/i.test(r)) {
const e = findFirstPythonScriptArg(n);
return e ? {
kind: "python",
relOrAbsPaths: [e]
} : null;
}
if (r === "node") {
const e = findNodeScriptArgs(n);
return e.length > 0 ? {
kind: "node",
relOrAbsPaths: e
} : null;
}
return null;
}
function extractInterpreterScriptPathsFromSegment(e) {
return extractInterpreterScriptTargetFromArgv(parsePreflightShellSegment(e))?.relOrAbsPaths ?? [];
}
function extractScriptTargetFromCommand(e) {
const t = e.trim();
const n = process.platform === "win32" && /(?:^|[\s"'`])(?:[A-Za-z]:\\|\\\\|[^\s"'`|&;()<>]+\\[^\s"'`|&;()<>]+)/.test(t) ? splitCommandArgs(t) : splitShellArgs(t);
for (const e of [n, n ? stripPreflightEnvPrefix(n) : null]) {
const t = extractInterpreterScriptTargetFromArgv(e);
if (t) return t;
}
return null;
}
//#endregion
//#region src/agents/bash-tools.exec-script-ambiguity.ts
/** Detects ambiguous interpreter invocations that cannot be safely preflighted. */
function scanUnquotedShellText(e, t, n) {
let r;
let i = false;
for (const a of e) {
if (i) {
if (!r && t(a, true)) return "match";
i = false;
continue;
}
if (r !== "'" && a === "\\") {
i = true;
continue;
}
if (r) {
if (a === r) r = void 0;
continue;
}
if (a === "'" || a === "\"") {
if (n?.()) return "match";
r = a;
continue;
}
if (t(a, false)) return "match";
}
return i || r ? "incomplete" : "complete";
}
function extractUnquotedShellText(e) {
let t = "";
return scanUnquotedShellText(e, (e, n) => {
t += n ? `\\${e}` : e;
return false;
}) === "incomplete" ? null : t;
}
function splitShellSegmentsOutsideQuotes(e, t) {
const n = [];
let r = "";
let i;
let a = false;
const pushSegment = () => {
if (r.trim().length > 0) n.push(r);
r = "";
};
for (let n = 0; n < e.length; n += 1) {
const o = e[n];
const s = e[n + 1];
if (a) {
r += o;
a = false;
continue;
}
if (i !== "'" && o === "\\") {
r += o;
a = true;
continue;
}
if (i) {
r += o;
if (o === i) i = void 0;
continue;
}
if (o === "'" || o === "\"") {
i = o;
r += o;
continue;
}
if (o === "\n" || o === "\r" || o === ";") {
pushSegment();
continue;
}
if ((o === "&" || o === "|") && s === o) {
pushSegment();
n += 1;
continue;
}
if (t.splitPipes && o === "|") {
pushSegment();
continue;
}
r += o;
}
pushSegment();
return n;
}
function isInterpreterExecutable(e) {
if (!e) return false;
return /^python(?:3(?:\.\d+)?)?$/i.test(e) || e === "node";
}
function hasUnescapedSequence(e, t) {
let n = false;
for (let r = 0; r < e.length; r += 1) {
const i = e[r];
if (n) {
n = false;
continue;
}
if (i === "\\") {
n = true;
continue;
}
if (e.startsWith(t, r)) return true;
}
return false;
}
function hasUnquotedScriptHint(e) {
let t = "";
const flushToken = () => {
const e = normalizeLowercaseStringOrEmpty(t);
if (e.endsWith(".py") || e.endsWith(".js")) return true;
t = "";
return false;
};
return scanUnquotedShellText(e, (e, n) => {
if (!n && (/\s/u.test(e) || "|&;()<>".includes(e))) return flushToken();
t += e;
return false;
}, flushToken) === "match" || flushToken();
}
function resolveLeadingShellSegmentExecutable(e) {
return normalizeOptionalLowercaseString(parsePreflightShellSegment(extractUnquotedShellText(e) ?? e)[0]);
}
function analyzeInterpreterHeuristicsFromUnquoted(e) {
const t = splitShellSegmentsOutsideQuotes(e, { splitPipes: true }).map(resolveLeadingShellSegmentExecutable);
const n = t.some((e) => /^python(?:3(?:\.\d+)?)?$/i.test(e ?? ""));
const r = t.includes("node");
const i = hasUnescapedSequence(e, "<(") || hasUnescapedSequence(e, ">(");
return {
hasPython: n,
hasNode: r,
hasComplexSyntax: [
"|",
"&&",
"||",
";",
"$(",
"`"
].some((t) => hasUnescapedSequence(e, t)) || e.includes("\n") || e.includes("\r") || i,
hasProcessSubstitution: i,
hasScriptHint: hasUnquotedScriptHint(e)
};
}
function extractShellWrappedCommandPayload(e, t) {
if (!e) return null;
const n = normalizeOptionalLowercaseString(e.split(/[\\/]/u).at(-1)) ?? "";
const r = n.endsWith(".exe") ? n.slice(0, -4) : n;
if (!/^(?:bash|dash|fish|ksh|sh|zsh)$/i.test(r)) return null;
const i = /* @__PURE__ */ new Set(["-O", "-o"]);
for (let e = 0; e < t.length; e += 1) {
const n = t.at(e);
if (n === void 0) break;
if (n === "--") return null;
if (n === "-c") return t.at(e + 1) ?? null;
if (/^-[A-Za-z]+$/u.test(n)) {
if (n.includes("c")) return t.at(e + 1) ?? null;
if (i.has(n)) e += 1;
continue;
}
if (/^--[A-Za-z0-9][A-Za-z0-9-]*(?:=.*)?$/u.test(n)) {
if (!n.includes("=")) {
const n = t.at(e + 1);
if (n && n !== "--" && !n.startsWith("-")) e += 1;
}
continue;
}
return null;
}
return null;
}
function shouldFailClosedInterpreterPreflight(e) {
const t = e.trim();
const n = splitShellArgs(t);
const [r, ...i] = n ? stripPreflightAssignments(stripPreflightEnvPrefix(n)) : [];
const a = normalizeOptionalLowercaseString(r);
const o = isInterpreterExecutable(a);
const s = analyzeInterpreterHeuristicsFromUnquoted(extractUnquotedShellText(t) ?? t);
const c = extractShellWrappedCommandPayload(a, i);
const l = c ? extractUnquotedShellText(c) ?? c : "";
const u = c ? analyzeInterpreterHeuristicsFromUnquoted(l) : {
hasPython: false,
hasNode: false,
hasComplexSyntax: false,
hasProcessSubstitution: false,
hasScriptHint: false
};
const hasInterpreterInvocationInSegment = (e) => isInterpreterExecutable(resolveLeadingShellSegmentExecutable(e));
const isScriptExecutingInterpreterCommand = (e) => {
const [t, ...n] = parsePreflightShellSegment(e);
const r = normalizeOptionalLowercaseString(t);
if (!r) return false;
if (/^python(?:3(?:\.\d+)?)?$/i.test(r)) {
const e = /* @__PURE__ */ new Set([
"-V",
"--version",
"-h",
"--help"
]);
return !n.some((t) => e.has(t) || t.startsWith("-c") || t.startsWith("-m") || t === "--check-hash-based-pycs");
}
if (r === "node") {
const e = /* @__PURE__ */ new Set([
"-v",
"--version",
"-h",
"--help",
"-c",
"--check"
]);
return !n.some((t) => e.has(t) || t.startsWith("-e") || t.startsWith("-p") || t === "--eval" || t === "--print" || t.startsWith("--eval=") || t.startsWith("--print="));
}
return false;
};
const hasScriptHintInSegment = (e) => extractInterpreterScriptPathsFromSegment(e).length > 0 || hasUnquotedScriptHint(e);
const hasInterpreterAndScriptHintInSameSegment = (e) => {
return splitShellSegmentsOutsideQuotes(e, { splitPipes: true }).some((e) => {
if (!isScriptExecutingInterpreterCommand(e)) return false;
return hasScriptHintInSegment(e);
});
};
const hasInterpreterPipelineScriptHintInSameSegment = (e) => {
return splitShellSegmentsOutsideQuotes(e, { splitPipes: false }).some((e) => {
if (!splitShellSegmentsOutsideQuotes(e, { splitPipes: true }).slice(1).some((e) => isScriptExecutingInterpreterCommand(e))) return false;
return hasScriptHintInSegment(e);
});
};
const d = hasInterpreterAndScriptHintInSameSegment(t) || c !== null && hasInterpreterAndScriptHintInSameSegment(c);
const f = hasInterpreterPipelineScriptHintInSameSegment(t) || c !== null && hasInterpreterPipelineScriptHintInSameSegment(c);
const p = c !== null && hasInterpreterAndScriptHintInSameSegment(c);
const m = (u.hasPython || u.hasNode) && (p || u.hasScriptHint || u.hasComplexSyntax || u.hasProcessSubstitution);
const h = splitShellSegmentsOutsideQuotes(t, { splitPipes: true }).some((e) => hasInterpreterInvocationInSegment(e));
return {
hasInterpreterInvocation: o || m || h,
hasComplexSyntax: s.hasComplexSyntax || m,
hasProcessSubstitution: s.hasProcessSubstitution || u.hasProcessSubstitution,
hasInterpreterSegmentScriptHint: d,
hasInterpreterPipelineScriptHint: f,
isDirectInterpreterCommand: o
};
}
//#endregion
//#region src/agents/bash-tools.exec-script-preflight.ts
const SKIPPABLE_SCRIPT_PREFLIGHT_FS_ERROR_CODES = /* @__PURE__ */ new Set([
"EACCES",
"EISDIR",
"ELOOP",
"EINVAL",
"ENAMETOOLONG",
"ENOENT",
"ENOTDIR",
"EPERM"
]);
const SCRIPT_PREFLIGHT_MAX_BYTES = 524288;
function getNodeErrorCode(e) {
if (typeof e !== "object" || e === null || !("code" in e)) return;
return String(e.code);
}
const fsSafeModuleLoader = createLazyImportLoader(() => import("./fs-safe-CZVDXVig.mjs"));
function findPythonShellVariable(e) {
const t = /\$[A-Z_][A-Z0-9_]*/y;
const n = /[\p{ID_Continue}]/u;
const r = [{
kind: "code",
delimiters: null,
lambda: false
}];
let i = 0;
while (i < e.length) {
const a = r.at(-1);
const o = e[i];
if (a.kind === "string") {
const t = a.quote.repeat(a.triple ? 3 : 1);
if (e.startsWith(t, i)) {
r.pop();
i += t.length;
} else if (a.formatted && o === "\\" && e[i + 1] === "{") i += 1;
else if (o === "\\") i += e[i + 1] === "\r" && e[i + 2] === "\n" ? 3 : 2;
else if (!a.triple && (o === "\n" || o === "\r")) {
r.pop();
i += 1;
} else if (a.formatted && (o === "{" && e[i + 1] === "{" || o === "}" && e[i + 1] === "}")) i += 2;
else if (a.formatted && o === "{") {
r.push({
kind: "code",
delimiters: ["}"],
lambda: false
});
i += 1;
} else i += 1;
continue;
}
if (a.kind === "format") {
if (o === "{") r.push({
kind: "code",
delimiters: ["}"],
lambda: false
});
else if (o === "}") r.pop();
i += 1;
continue;
}
if (o === "#") {
const t = e.slice(i + 1).search(/[\r\n]/);
i = t === -1 ? e.length : i + t + 2;
continue;
}
if (o === "'" || o === "\"") {
const t = e.slice(Math.max(0, i - 3), i);
r.push({
kind: "string",
quote: o,
triple: e.startsWith(o.repeat(3), i),
formatted: /(?:^|[^A-Z0-9_])(?:F|FR|RF)$/i.test(t)
});
i += e.startsWith(o.repeat(3), i) ? 3 : 1;
continue;
}
if (a.delimiters) {
if (a.delimiters.length === 1 && !n.test(e.charAt(i - 1)) && e.startsWith("lambda", i) && !n.test(e.charAt(i + 6))) a.lambda = true;
const t = o === "(" ? ")" : o === "[" ? "]" : o === "{" ? "}" : null;
if (t) a.delimiters.push(t);
else if (a.delimiters.at(-1) === o) {
a.delimiters.pop();
if (a.delimiters.length === 0) r.pop();
} else if (o === ":" && a.delimiters.length === 1) {
if (a.lambda) a.lambda = false;
else r[r.length - 1] = { kind: "format" };
}
}
if (o === "$") {
t.lastIndex = i;
const n = t.exec(e);
if (n) return n;
}
i += 1;
}
return null;
}
function shouldSkipScriptPreflightPathError(e, t) {
if (e instanceof t) return true;
const n = getNodeErrorCode(e);
return Boolean(n && SKIPPABLE_SCRIPT_PREFLIGHT_FS_ERROR_CODES.has(n));
}
function resolvePreflightRelativePath(e) {
const t = path.resolve(e.rootDir);
const n = path.resolve(e.absPath);
const r = path.relative(t, n);
if (/^\.\.(?:[\\/]|$)/u.test(r) || path.isAbsolute(r)) return null;
return r;
}
async function validateScriptFileForShellBleed(e) {
const t = extractScriptTargetFromCommand(e.command);
if (!t) {
const { hasInterpreterInvocation: t, hasComplexSyntax: n, hasProcessSubstitution: r, hasInterpreterSegmentScriptHint: i, hasInterpreterPipelineScriptHint: a, isDirectInterpreterCommand: o } = shouldFailClosedInterpreterPreflight(e.command);
if (t && n && (i || a || r && o)) throw markToolExecutionNotStarted(/* @__PURE__ */ new Error("exec preflight: complex interpreter invocation detected; refusing to run without script preflight validation. Use a direct `python <file>.py` or `node <file>.js` command."));
return;
}
if (t.kind === "node") return;
const { FsSafeError: n, root: r } = await fsSafeModuleLoader.load();
const i = await r(e.workdir);
for (const r of t.relOrAbsPaths) {
const a = path.isAbsolute(r) ? path.resolve(r) : path.resolve(e.workdir, r);
const o = resolvePreflightRelativePath({
rootDir: e.workdir,
absPath: a
});
if (!o) continue;
let s;
try {
s = (await i.read(`./${o}`, {
symlinks: "follow-within-root",
maxBytes: SCRIPT_PREFLIGHT_MAX_BYTES,
hardlinks: /^~(?:$|[\\/])/u.test(o) ? "allow" : "reject"
})).buffer.toString("utf-8");
} catch (e) {
if (shouldSkipScriptPreflightPathError(e, n)) continue;
throw e;
}
const c = findPythonShellVariable(s);
if (c) {
const e = c.index;
const n = s.slice(0, e).split(/\r\n?|\n/).length;
const r = c[0];
throw markToolExecutionNotStarted(new Error([
`exec preflight: detected likely shell variable injection (${r}) in ${t.kind} script: ${path.basename(a)}:${n}.`,
`In Python, use os.environ.get(${JSON.stringify(r.slice(1))}) instead of raw ${r}.`,
"(If this is inside a string literal on purpose, escape it or restructure the code.)"
].join("\n")));
}
}
}
function shouldSkipExecScriptPreflight(e) {
return e.host === "gateway" && e.security === "full" && e.ask === "off";
}
//#endregion
//#region src/agents/bash-tools.exec-run.ts
function createExecTool(e) {
const t = isSecretEgressProxyActive();
const n = e?.cleanupMs;
const r = (e && readExecRequestOwners(e)) ?? captureExecRequestOwners({
runId: e?.runId,
sessionId: e?.sessionId
});
const i = resolveExecPreparedRunEnvironment(e);
let a;
const resolveSubagentExecution = () => e?.preparedSubagentExecution ?? (a ??= withPreparedSessionCapabilityRead(() => resolveStoredSubagentCapabilities(e?.runSessionKey ?? e?.sessionKey, { cfg: e?.config }).depth > 0));
let o = e?.preparedStoreEnvironment === void 0 ? void 0 : Promise.resolve(e.preparedStoreEnvironment);
const resolveStoreEnv = () => {
if (o === void 0) {
const e = captureOpenClawStateReadWorkerContext();
o = import("./secret-store-xf4-UqW-.mjs").then((n) => n.readSecretStoreExecEnvironment({
includeSecretSentinels: t,
excludeNames: i.excludedStoreNames,
context: e
}));
}
return o;
};
const s = clampWithDefault(e?.backgroundMs ?? readEnvInt("OPENCLAW_BASH_YIELD_MS", "PI_BASH_YIELD_MS"), 1e4, 10, 12e4);
const c = e?.processToolAvailabilityRef?.value ?? e?.allowBackground ?? true;
const l = resolveExecDefaultTimeoutSec(e?.timeoutSec);
const u = normalizePathPrepend(e?.pathPrepend);
const { safeBins: d, safeBinProfiles: f, trustedSafeBinDirs: p, unprofiledSafeBins: m, unprofiledInterpreterSafeBins: h } = resolveExecSafeBinRuntimePolicy({
local: {
safeBins: e?.safeBins,
safeBinTrustedDirs: e?.safeBinTrustedDirs,
safeBinProfiles: e?.safeBinProfiles
},
onWarning: logInfo
});
if (m.length > 0) logInfo(`exec: ignoring unprofiled safeBins entries (${m.toSorted().join(", ")}); use allowlist or define tools.exec.safeBinProfiles.<bin>`);
if (h.length > 0) logInfo(`exec: interpreter/runtime binaries in safeBins (${h.join(", ")}) are unsafe without explicit hardened profiles; prefer allowlist entries`);
const { notifyOnExit: g, notifyOnExitEmptySuccess: _, notifySessionKey: v, resolveSubagentSession: y, notifyDeliveryContext: b } = resolveExecNotificationDefaults(e);
const x = resolveApprovalRunningNoticeMs(e?.approvalRunningNoticeMs);
const S = parseAgentSessionKey(e?.sessionKey);
const C = e?.agentId ?? (S ? resolveAgentIdFromSessionKey(e?.sessionKey) : void 0);
const buildUnavailableWorkdirResult = (e) => buildExecForegroundResult({
outcome: buildExecRuntimeErrorOutcome({
error: formatUnavailableWorkdirFailure(e.cwd),
aggregated: "",
durationMs: e.startedAt ? Date.now() - e.startedAt : 0
}),
cwd: e.cwd,
warningText: e.warningText
});
const w = createExecRequestPreparation({
defaults: e,
agentId: C,
resolveHostForParams: (t) => resolveExecHost(t, e)
});
const T = {
name: "exec",
label: "exec",
displaySummary: EXEC_TOOL_DISPLAY_SUMMARY,
get description() {
return describeExecTool({
hasCronTool: e?.hasCronTool === true,
autoReview: e?.mode === "auto"
});
},
parameters: createExecSchema(e),
getExecutionTimeoutMs: createExecToolExecutionTimeoutResolver(e),
prepareBeforeToolCallParams: w.prepareBeforeToolCallParams,
finalizeBeforeToolCallParams: w.finalizeBeforeToolCallParams,
execute: async (a, o, m, h) => {
m?.throwIfAborted();
const S = e?.createApprovalTransport?.(a, m);
const T = captureAgentToolSourceExecutionGuard(m);
assertSupportedExecParams(o);
let autoReviewer = e?.autoReviewer;
if (!autoReviewer) {
const t = {
cfg: e?.config,
agentId: C,
reviewer: resolveExecReviewerDefaults({
defaults: e,
agentId: C
}),
signal: m
};
autoReviewer = async (e) => {
const { createModelExecAutoReviewer: n } = await import("./exec-auto-reviewer-BABANvdR.mjs");
return n(t)(e);
};
}
const E = autoReviewer;
autoReviewer = (t) => {
const n = e?.reviewTranscript?.();
return E(n ? {
...t,
transcript: n
} : t);
};
let D = w.normalizeParams(o);
const O = c && D.awaitResults !== true;
const k = w.isResolveExecEnvPrepared(o);
const A = w.getExecHookContext(D);
const j = w.getResolvedExecWorkdirPreparedState(D);
const M = [];
const getWarningText = () => M.length ? `${M.join("\n")}\n\n` : "";
const N = normalizeOptionalString(e?.approvalWarningText);
if (N) M.push(N);
const P = Date.now();
let F;
let I;
let L;
const R = O ? D.background === true ? 0 : clampWithDefault(D.yieldMs ?? s, s, 10, 12e4) : null;
const z = e?.elevated;
const B = resolveExecElevatedMode(e, D.elevated);
const V = B !== "off";
if (V && (!z?.enabled || !z.allowed)) {
const t = e?.sandbox ? "sandboxed" : "direct";
const n = [];
const r = normalizeOptionalString(e?.messageProvider);
const i = normalizeOptionalString(e?.sessionKey);
if (r) n.push(`provider=${r}`);
if (i) n.push(`session=${i}`);
const a = !z?.enabled ? "enabled (tools.elevated.enabled / agents.entries.*.tools.elevated.enabled)" : "allowFrom (tools.elevated.allowFrom.<provider> / agents.entries.*.tools.elevated.allowFrom.<provider>)";
throw new Error([
`elevated is not available right now (runtime=${t}).`,
`Failing gates: ${a}`,
n.length > 0 ? `Context: ${n.join(" ")}` : void 0,
"Fix-it keys:",
"- tools.elevated.enabled",
"- tools.elevated.allowFrom.<provider>",
"- agents.entries.*.tools.elevated.enabled",
"- agents.entries.*.tools.elevated.allowFrom.<provider>"
].filter(Boolean).join("\n"));
}
const H = resolveExecHost(D, e);
const U = (H === "node" || !c) && (D.background === true || typeof D.yieldMs === "number") ? H === "node" ? "Warning: continuation options are unavailable for host=node; running synchronously via remote system.run without a process session." : "Warning: continuation options are unavailable; running synchronously." : void 0;
const W = e?.security;
const G = W ?? (H === "sandbox" ? "deny" : "full");
const K = resolveExecModePolicy({
mode: e?.mode,
security: G,
ask: e?.ask ?? "off"
});
const q = H === "sandbox" || e?.bypassHostApprovalFloors === true ? void 0 : resolveExecApprovalsFromFileInternal({
file: await loadExecApprovalsReadOnlyAsync(),
agentId: C,
overrides: {
security: "full",
ask: "off"
}
}).agent;
const J = minSecurity(K.security, q?.security ?? K.security);
if (J === "deny" && (H !== "sandbox" || e?.mode === "deny" || W === "deny")) throw new Error(`exec denied: host=${H} security=deny`);
const ee = (q?.security ?? "full") === "full" && (q?.ask ?? "off") === "off";
const te = K.security === "full" && K.ask === "off";
const ne = normalizeExecAsk(D.ask);
const re = maxAsk(K.ask, q?.ask ?? K.ask);
const ie = e?.messageProvider && re === "off" ? void 0 : ne;
let ae = maxAsk(re, ie ?? re);
const oe = e?.bypassHostApprovalFloors === true && K.ask === "off" || V && B === "full" && te && ee;
if (oe) ae = "off";
const se = K.autoReview && ae === K.ask && !oe;
const Y = H === "sandbox" ? e?.sandbox : void 0;
if (H === "sandbox" && !Y) throw new Error(["exec host=sandbox requires a sandbox runtime for this session.", "Enable sandbox mode (`agents.defaults.sandbox.mode=\"non-main\"` or `\"all\"`) or use host=auto/gateway/node."].join("\n"));
if (!D.command) throw new Error("Provide a command to start.");
await rejectUnsafeExecControlShellCommand(D.command);
let X;
let ce = null;
let le = Y?.containerWorkdir;
let discardPreparedSandboxWorkdir = null;
const Z = j?.host === H ? j.resolution : await resolveExecWorkdir({
host: H,
workdir: D.workdir,
defaultCwd: e?.cwd,
nodeCwd: e?.nodeCwd,
sandbox: Y
});
if (Z.kind === "unavailable") return buildUnavailableWorkdirResult({
cwd: Z.requestedCwd,
startedAt: P,
warningText: M.join("\n")
});
if (Z.kind === "sandbox") {
X = Z.hostCwd;
le = Z.containerCwd;
ce = Z.scriptPreflightCwd;
if (Y?.discardPreparedWorkdir && Y.workdirValidation === "backend") {
const e = le;
discardPreparedSandboxWorkdir = () => {
Y.discardPreparedWorkdir?.(e);
};
}
} else if (Z.kind === "local") {
X = Z.hostCwd;
ce = Z.hostCwd;
} else X = Z.remoteCwd;
if (H === "gateway" && X) await rejectUnsafeExecLiveStateSqliteShellCommand(D.command, {
stateDir: resolveStateDir(),
workdir: X
});
let Q;
let ue = false;
const de = D.timeoutSeconds ?? l;
try {
if (V) logInfo("exec: elevated command");
if (!k) D = await w.prepareParamsWithResolvedExecEnv(D, { hookContext: A });
const o = w.getResolvedExecEnvPreparedState(D);
const s = await resolveStoreEnv();
const c = await resolveSubagentExecution();
T();
const E = t && H === "gateway";
if (E) {
if (!e?.operationalRunInstance) throw new Error("Secret egress proxy requires an admitted agent run instance");
T();
}
const j = E ? s.secretEgressBindings ?? [] : void 0;
const { env: N, requestedEnv: P, executionContext: R } = resolvePreparedExecEnvironment({
execParams: D,
host: H,
sandbox: Y,
containerWorkdir: le,
channelContext: e?.channelContext,
subagentExecution: c,
defaultPathPrepend: u,
pluginEnv: o?.pluginEnv,
storeEnv: H === "gateway" ? s.env : void 0,
storeSecretEnv: E ? s.secretSentinels : void 0,
...i,
warnings: M
});
const hostApprovalParams = () => ({
approvalTransport: S,
command: D.command,
toolCallId: a,
env: N,
requestedEnv: P,
sessionKey: e?.sessionKey,
sessionId: e?.sessionId,
sessionStore: e?.sessionStore,
bashElevated: z,
approvalReviewerDeviceId: e?.approvalReviewerDeviceId,
nonInteractiveApproval: e?.nonInteractiveApproval,
approvalFollowupMode: e?.approvalFollowupMode,
turnSourceChannel: e?.messageProvider,
turnSourceTo: e?.currentMessagingTarget ?? e?.currentChannelId,
turnSourceAccountId: e?.accountId,
turnSourceThreadId: e?.currentThreadTs,
agentId: C,
security: J,
ask: ae,
bypassHostApprovalFloors: e?.bypassHostApprovalFloors,
autoReview: se,
autoReviewer,
signal: m,
strictInlineEval: e?.strictInlineEval,
commandHighlighting: e?.commandHighlighting,
trigger: e?.trigger,
timeoutSec: D.timeoutSeconds,
defaultTimeoutSec: l,
approvalRunningNoticeMs: x,
warnings: M,
notifySessionKey: v,
trustedSafeBinDirs: p
});
if (H === "node") return executeNodeHostCommand({
...hostApprovalParams(),
workdir: X,
executionContext: R,
requestedNode: D.node?.trim(),
boundNode: e?.node?.trim(),
foregroundWarnings: U ? [U] : [],
processContinuationAvailable: false,
notifyOnExit: g
});
if (!X) throw new Error("exec internal error: local execution requires a resolved workdir");
const B = H === "gateway" && i.managedLocalIdentity ? i.localIdentityEnv.GH_CONFIG_DIR : void 0;
if (H === "gateway" && !oe) {
I = await processGatewayAllowlist({
...hostApprovalParams(),
workdir: X,
secretEgressBindings: j,
githubProfileDir: B,
pathPrepend: u,
pty: D.pty === true && !Y,
safeBins: d,
safeBinProfiles: f,
runId: e?.runId,
onApprovalReview: (e) => L = e,
scopeKey: e?.scopeKey,
approvalFollowupText: e?.approvalFollowupText,
approvalFollowup: e?.approvalFollowup,
maxOutput: DEFAULT_MAX_OUTPUT,
pendingMaxOutput: DEFAULT_PENDING_MAX_OUTPUT,
cleanupMs: n,
processContinuationAvailable: O
});
const t = I.pendingResult ?? I.deniedResult;
if (t) return attachExecApprovalReview(t, L);
m?.throwIfAborted();
F = I.allowWithoutEnforcedCommand ? void 0 : I.execCommandOverride;
}
if (U) M.push(U);
const W = D.pty === true && !Y;
if (D.pty === true && Y) M.push("Warning: PTY is unavailable in sandbox mode; running without a PTY. Use a noninteractive command.");
if (ce && !shouldSkipExecScriptPreflight({
host: H,
security: J,
ask: ae
})) await validateScriptFileForShellBleed({
command: D.command,
workdir: ce
});
const G = g && O ? await y() : false;
T();
Q = await runExecProcess({
command: D.command,
execCommand: F,
workdir: X,
env: N,
secretEgressBindings: j,
githubProfileDir: B,
pathPrepend: u,
sandbox: Y,
containerWorkdir: le,
usePty: W,
warnings: M,
maxOutput: DEFAULT_MAX_OUTPUT,
pendingMaxOutput: DEFAULT_PENDING_MAX_OUTPUT,
cleanupMs: n,
notifyOnExit: g,
subagentSession: G,
notifyOnExitEmptySuccess: _,
requestOwners: D.background === true ? void 0 : r,
scopeKey: e?.scopeKey,
sessionKey: v,
agentId: C,
eventRouting: e?.eventRouting,
notifyDeliveryContext: b,
timeoutSec: de,
processContinuationAvailable: O,
startupSignal: m,
onUpdate: h,
beforeSpawn: I?.revalidateBeforeExecution,
assertCurrent: I?.assertCurrent,
approvalTransport: S,
initiateSpawn: I?.initiateSpawn,
releaseSpawn: I?.releaseSpawn,
onSettledBeforeNotify: () => {
ue = true;
}
});
Q.session.originRunId = e?.runId;
discardPreparedSandboxWorkdir = null;
} catch (e) {
I?.releaseSpawn?.();
discardPreparedSandboxWorkdir?.();
return attachExecApprovalReview(ExecProcessPreflightError.unwrap(e), L);
}
const fe = buildBackgroundExecFollowUp(Q.session, D.yieldMs, []);
let pe = false;
let $ = null;
let me = null;
let he = false;
const onAbortSignal = () => {
Q.disableUpdates();
if (pe || Q.session.backgrounded) return;
he = true;
if ($) {
clearTimeout($);
$ = null;
}
if (!Q.session.requestCancelled) Q.kill();
};
const cleanupToolRunListeners = () => {
Q.disableUpdates();
me?.removeEventListener("abort", onAbortSignal);
me = null;
if ($) {
clearTimeout($);
$ = null;
}
};
if (m?.aborted) onAbortSignal();
else if (m) {
m.addEventListener("abort", onAbortSignal, { once: true });
me = m;
}
const ge = withoutGatewayToolCallerIdentity(() => createDeferredCore());
const _e = withoutGatewayToolCallerIdentity(() => Promise.race([Q.promise.then((e) => ({
status: "settled",
outcome: e
})), ge.promise]));
const onYieldNow = () => {
if (pe || he || Q.session.finalizing || ue) return;
pe = true;
Q.disableUpdates();
markBackgrounded(Q.session);
ge.resolve({ status: "backgrounded" });
};
try {
if (!he && O && R !== null) {
if (R === 0) onYieldNow();
else $ = setTimeout(onYieldNow, R);
}
const e = await _e;
if (he) throw createAbortError$1("Tool execution was aborted", { cause: m?.reason });
const t = Q.session.processActivity?.deadlineAtMs;
const n = t === void 0 ? "" : `, times out in ${formatDurationCompact(Math.max(1e3, t - Date.now()))}`;
return attachExecApprovalReview(e.status === "settled" ? buildExecForegroundResult({
outcome: e.outcome,
cwd: Q.session.cwd,
warningText: getWarningText(),
aggregateOutputDropped: Q.session.totalOutputChars > Q.session.aggregated.length
}) : {
content: [{
type: "text",
text: `${getWarningText()}Command still running (session ${Q.session.id}, pid ${Q.session.pid ?? "n/a"})${n}. ${fe}`
}],
details: {
status: "running",
sessionId: Q.session.id,
pid: Q.session.pid ?? void 0,
startedAt: Q.startedAt,
...t === void 0 ? {} : { deadlineAtMs: t },
cwd: Q.session.cwd,
tail: Q.session.tail,
...M.length ? { warningText: M.join("\n") } : {},
followUp: fe
}
}, L);
} catch (e) {
if (he) throw createAbortError$1("Tool execution was aborted", { cause: m?.reason });
throw e;
} finally {
cleanupToolRunListeners();
}
}
};
return bindAgentToolAvailability(T, {
prepare: () => void 0,
executionSchema: () => execSchema
});
}
const execTool = createExecTool();
//#endregion
//#region src/agents/pty-keys.ts
/**
* Encodes terminal key, hex, literal, and paste inputs into PTY byte
* sequences. The encoder handles xterm modifiers and DECCKM application
* cursor mode.
*/
const ESC = "\x1B";
const CR = "\r";
const TAB = " ";
const BACKSPACE = "";
const BRACKETED_PASTE_START = `${ESC}[200~`;
const BRACKETED_PASTE_END = `${ESC}[201~`;
/** SS3 sequences for DECCKM application cursor key mode (smkx). */
const DECCKM_SS3_KEYS = {
up: `${ESC}OA`,
down: `${ESC}OB`,
right: `${ESC}OC`,
left: `${ESC}OD`,
home: `${ESC}OH`,
end: `${ESC}OF`
};
const modifiableNamedKeys = /* @__PURE__ */ new Map([
["up", `${ESC}[A`],
["down", `${ESC}[B`],
["right", `${ESC}[C`],
["left", `${ESC}[D`],
["home", `${ESC}[1~`],
["end", `${ESC}[4~`],
["pageup", `${ESC}[5~`],
["pgup", `${ESC}[5~`],
["ppage", `${ESC}[5~`],
["pagedown", `${ESC}[6~`],
["pgdn", `${ESC}[6~`],
["npage", `${ESC}[6~`],
["insert", `${ESC}[2~`],
["ic", `${ESC}[2~`],
["delete", `${ESC}[3~`],
["del", `${ESC}[3~`],
["dc", `${ESC}[3~`],
["f1", `${ESC}OP`],
["f2", `${ESC}OQ`],
["f3", `${ESC}OR`],
["f4", `${ESC}OS`],
["f5", `${ESC}[15~`],
["f6", `${ESC}[17~`],
["f7", `${ESC}[18~`],
["f8", `${ESC}[19~`],
["f9", `${ESC}[20~`],
["f10", `${ESC}[21~`],
["f11", `${ESC}[23~`],
["f12", `${ESC}[24~`]
]);
const namedKeyMap = new Map([
...modifiableNamedKeys,
["enter", CR],
["return", CR],
["tab", TAB],
["escape", ESC],
["esc", ESC],
["space", " "],
["bspace", BACKSPACE],
["backspace", BACKSPACE],
["btab", `${ESC}[Z`],
["kp/", `${ESC}Oo`],
["kp*", `${ESC}Oj`],
["kp-", `${ESC}Om`],
["kp+", `${ESC}Ok`],
["kp7", `${ESC}Ow`],
["kp8", `${ESC}Ox`],
["kp9", `${ESC}Oy`],
["kp4", `${ESC}Ot`],
["kp5", `${ESC}Ou`],
["kp6", `${ESC}Ov`],
["kp1", `${ESC}Oq`],
["kp2", `${ESC}Or`],
["kp3", `${ESC}Os`],
["kp0", `${ESC}Op`],
["kp.", `${ESC}On`],
["kpenter", `${ESC}OM`]
]);
function hasCursorModeSensitiveKeys(e) {
return e.keys?.some((e) => {
const t = e.trim();
if (!t) return false;
const n = parseModifiers(t);
if (hasAnyModifier(n.mods)) return false;
return Object.hasOwn(DECCKM_SS3_KEYS, normalizeLowercaseStringOrEmpty(n.base));
}) ?? false;
}
function encodeKeySequence(e, t) {
const n = [];
const r = [];
for (const t of e.hex ?? []) {
const e = parseHexByte(t);
if (e === null) {
n.push(`Invalid hex byte: ${t}`);
continue;
}
r.push(e);
}
const i = e.keys?.map((e) => encodeKeyToken(e, n, t)).join("");
return {
data: Buffer.concat([
Buffer.from(e.literal ?? ""),
Buffer.from(r),
Buffer.from(i ?? "")
]),
warnings: n
};
}
function encodePaste(e, t = true) {
if (!t) return e;
return `${BRACKETED_PASTE_START}${e}${BRACKETED_PASTE_END}`;
}
function encodeKeyToken(e, t, n) {
const r = e.trim();
if (!r) return "";
if (r.length === 2 && r.startsWith("^")) {
const e = toCtrlChar(r.charAt(1));
if (e) return e;
}
const i = parseModifiers(r);
const a = i.base;
const o = normalizeLowercaseStringOrEmpty(a);
if (o === "tab" && i.mods.shift) return `${ESC}[Z`;
if (modifiableNamedKeys.has(o) && n === "application" && !hasAnyModifier(i.mods)) {
const e = DECCKM_SS3_KEYS[o];
if (e) return e;
}
const s = namedKeyMap.get(o);
if (s) {
if (modifiableNamedKeys.has(o) && hasAnyModifier(i.mods)) {
const e = s.slice(2, -1) || "1";
return `${ESC}[${e};${xtermModifier(i.mods)}${s.at(-1)}`;
}
return applyCharModifiers(s, i.mods);
}
if (a.length === 1) return applyCharModifiers(a, i.mods);
if (hasAnyModifier(i.mods)) t.push(`Unknown key "${a}" for modifiers; sending literal.`);
return a;
}
function parseModifiers(e) {
const t = {
ctrl: false,
alt: false,
shift: false
};
let n = e;
while (n.length > 2 && n[1] === "-") {
const e = normalizeLowercaseStringOrEmpty(n[0]);
if (e === "c") t.ctrl = true;
else if (e === "m") t.alt = true;
else if (e === "s") t.shift = true;
else break;
n = n.slice(2);
}
return {
mods: t,
base: n
};
}
function applyCharModifiers(e, t) {
let n = e;
if (t.shift && n.length === 1 && /[a-z]/.test(n)) n = n.toUpperCase();
if (t.ctrl) {
const e = toCtrlChar(n);
if (e) n = e;
}
if (t.alt) n = `${ESC}${n}`;
return n;
}
function toCtrlChar(e) {
if (e === "?") return "";
if (e === " ") return "\0";
const t = e.toUpperCase().charCodeAt(0);
if (t >= 64 && t <= 95) return String.fromCharCode(t & 31);
return null;
}
function xtermModifier(e) {
return 1 + (e.shift ? 1 : 0) + (e.alt ? 2 : 0) + (e.ctrl ? 4 : 0);
}
function hasAnyModifier(e) {
return e.ctrl || e.alt || e.shift;
}
function parseHexByte(e) {
const t = normalizeLowercaseStringOrEmpty(e);
const n = t.startsWith("0x") ? t.slice(2) : t;
if (!/^[0-9a-f]{1,2}$/.test(n)) return null;
return Number.parseInt(n, 16);
}
//#endregion
//#region src/agents/bash-tools.process.ts
const DEFAULT_LOG_TAIL_LINES = 200;
const DEFAULT_INPUT_WAIT_IDLE_MS = 15e3;
const MIN_INPUT_WAIT_IDLE_MS = 1e3;
const MAX_INPUT_WAIT_IDLE_MS = 6e5;
const PROCESS_TOOL_ACTIONS = processSchema.properties.action.enum;
const pollScopeByAssistantMessage = /* @__PURE__ */ new WeakMap();
function currentPollScope() {
const e = getAgentToolExecutionContext()?.assistantMessage;
if (!e) return;
const t = pollScopeByAssistantMessage.get(e);
if (t) return t;
const n = {};
pollScopeByAssistantMessage.set(e, n);
return n;
}
function resolveLogSliceWindow(e, t) {
const n = e === void 0 && t === void 0;
return {
effectiveOffset: e,
effectiveLimit: typeof t === "number" && Number.isFinite(t) ? t : n ? DEFAULT_LOG_TAIL_LINES : void 0,
usingDefaultTail: n
};
}
function defaultTailNote(e, t) {
if (!t || e <= DEFAULT_LOG_TAIL_LINES) return "";
return `\n\n[showing last ${DEFAULT_LOG_TAIL_LINES} of ${e} lines; pass offset/limit to page]`;
}
function retentionCapNote(e) {
return e.totalOutputChars > e.aggregated.length ? EXEC_RETENTION_CAP_NOTE : "";
}
const MAX_POLL_WAIT_MS = 3e4;
function isWritableStdin(e) {
if (!e || e.destroyed) return false;
if (e.writable === false || e.writableEnded === true || e.writableFinished === true) return false;
return true;
}
async function writeProcessStdin(e, t) {
await new Promise((n, r) => {
e.write(t, (e) => {
if (e) r(e);
else n();
});
});
}
function resolvePollWaitMs(e) {
if (typeof e === "number" && Number.isFinite(e)) return Math.max(0, Math.min(MAX_POLL_WAIT_MS, Math.floor(e)));
if (typeof e === "string" && /^[+-]?\d+$/.test(e.trim())) {
const t = Number(e.trim());
if (Number.isSafeInteger(t)) return Math.max(0, Math.min(MAX_POLL_WAIT_MS, t));
}
return 0;
}
function recordPollRetrySuggestion(e, t) {
try {
const n = getDiagnosticSessionState({ sessionId: e });
return recordCommandPoll(n, e, t);
} catch {
return;
}
}
function resetPollRetrySuggestion(e) {
try {
const t = getDiagnosticSessionState({ sessionId: e });
resetCommandPollCount(t, e);
} catch {}
}
function finishedSessionDetails(e, t) {
return {
status: t.terminalStatus === "completed" || isConfirmedRequestedStop(t) ? "completed" : "failed",
sessionId: e,
exitCode: t.exitCode ?? void 0,
...t.exitSignal != null ? { exitSignal: t.exitSignal } : {},
...t.exitReason ? {
exitReason: t.exitReason,
timedOut: t.exitReason === "overall-timeout" || t.exitReason === "no-output-timeout"
} : {},
...t.noOutputTimedOut !== void 0 ? { noOutputTimedOut: t.noOutputTimedOut } : {},
...t.finalizationFailed ? { finalizationFailed: true } : {},
name: deriveSessionName(t.command)
};
}
function finishedSessionText(e) {
if (e.exitReason === "memory-limit") return "Process killed for exceeding its host memory bound. Reduce concurrency or input size, or split the work.";
if (isConfirmedRequestedStop(e)) return `Process stopped by request (${renderExecExitLabel(e)}).`;
return `Process exited with ${renderExecExitLabel(e)}.` + (e.finalizationFailed ? " Cleanup failed; use process log for details." : "");
}
function finishedPollResult(e, t, n) {
resetPollRetrySuggestion(e);
const r = prepareSessionPoll(t, n);
const { output: i, outputDropped: a } = r;
const o = i.trim();
const s = a ? getFinishedSession(e) === t ? "[earlier output is omitted from this poll; use action=log with offset and limit to inspect retained output]\n\n" : "[earlier output is omitted from this poll; omitted output is no longer available through action=log]\n\n" : "";
const c = appendExecTimeoutRetryGuidance(retentionCapNote(t) + s + (o || "(no new output)") + `\n\n${finishedSessionText(t)}`, t.exitReason);
return attachInternalToolResultAcknowledgement(textResult(c, {
...finishedSessionDetails(e, t),
aggregated: t.aggregated
}), () => {
r.acknowledge();
acknowledgeNotifyOnExit(t);
});
}
function createAbortError(e) {
if (e instanceof Error) return e;
return createAbortError$1(typeof e === "string" ? e : "Aborted");
}
function sleepPollInterval(e, t) {
return sleep(e, t).catch((e) => {
throw t?.aborted ? createAbortError(t.reason) : e;
});
}
function assertSupportedProcessParams(e) {
if (isRecord(e) && Object.hasOwn(e, "timeoutMs")) throw new ToolInputError("process parameter \"timeoutMs\" is unsupported; use \"timeout\" instead");
}
function createProcessTool(e) {
const t = captureAgentToolSourceExecutionGuard();
const n = clampWithDefault(e?.inputWaitIdleMs ?? readEnvInt("OPENCLAW_PROCESS_INPUT_WAIT_IDLE_MS"), DEFAULT_INPUT_WAIT_IDLE_MS, MIN_INPUT_WAIT_IDLE_MS, MAX_INPUT_WAIT_IDLE_MS);
const describeRunningSession = (e) => {
const t = e.processActivity?.lastOutputAtMs ?? e.startedAt;
const r = Math.max(0, Date.now() - t);
const i = isWritableStdin(e.stdin);
return {
...!hasExitWake(e) ? { followUp: EXEC_MANUAL_COLLECTION_FOLLOW_UP } : {},
stdinWritable: i,
waitingForInput: i && r >= n,
idleMs: r,
lastOutputAt: t
};
};
const buildInputWaitHint = (e) => {
if (!e) return "";
return "\n\nNo new output; this session may be waiting for input. Use process write, send-keys, submit, or paste to provide input.";
};
return {
name: "process",
label: "process",
displaySummary: PROCESS_TOOL_DISPLAY_SUMMARY,
description: describeProcessTool({ hasCronTool: e?.hasCronTool === true }),
parameters: processSchema,
outputSchema: ProcessToolOutputSchema,
execute: async (n, r, i, a) => {
try {
var o = _usingCtx();
const assertCallerCurrent = () => {
i?.throwIfAborted();
t();
};
assertCallerCurrent();
assertSupportedProcessParams(r);
const n = r.action;
if (!PROCESS_TOOL_ACTIONS.includes(n)) return failText(`Invalid process action. Expected one of: ${PROCESS_TOOL_ACTIONS.join(", ")}`);
const a = r;
const s = o.a(createProcessToolScope(e ?? {}, assertCallerCurrent));
const { isInScope: c, assertCurrent: l } = s;
if (a.action === "list") {
await s.resolveAncestorScopes();
return await runWithAgentToolSourceExecutionScope(t, async () => {
l();
const e = [...listRunningSessions(), ...listFinishedSessions()].filter((e) => c(e)).toSorted(compareProcessSessionStartOrder).map((e) => Object.assign({
sessionId: e.id,
status: isConfirmedRequestedStop(e) ? "completed" : e.terminalStatus ?? "running",
startedAt: e.startedAt,
runtimeMs: (e.endedAt ?? Date.now()) - e.startedAt,
cwd: e.cwd,
command: e.command,
name: deriveSessionName(e.command),
tail: e.tail,
truncated: e.truncated
}, e.endedAt !== void 0 ? {
...finishedSessionDetails(e.id, e),
status: isConfirmedRequestedStop(e) ? "completed" : e.terminalStatus ?? "running",
endedAt: e.endedAt
} : Object.assign({ pid: e.pid ?? void 0 }, describeRunningSession(e))));
const t = e.map((e) => {
const t = e.name ? truncateMiddle(e.name, 80) : truncateMiddle(e.command, 120);
const n = "exitReason" in e && (e.exitReason === "overall-timeout" || e.exitReason === "no-output-timeout") ? e.exitReason : void 0;
const r = n ? ` [${n}]` : "";
const i = e.status === "completed" && "exitReason" in e && e.exitReason === "manual-cancel" ? " [stopped by request]" : "";
const a = "waitingForInput" in e && e.waitingForInput ? " [input-wait]" : "";
const o = "followUp" in e ? " [no exit wake]" : "";
return `${e.sessionId} ${e.status.padEnd(9)} ${formatDurationCompact(e.runtimeMs) ?? "n/a"}${r}${i}${a}${o} :: ${t}`;
});
const n = e.some((e) => "followUp" in e) ? `\n\n${EXEC_MANUAL_COLLECTION_FOLLOW_UP}` : "";
return textResult((t.join("\n") || "No running or recent sessions.") + n, {
status: "completed",
sessions: e
});
});
}
if (!a.sessionId) return failText("sessionId is required for this action.");
const u = a.sessionId;
const d = getSession(u);
const f = getFinishedSession(u);
const assertSelectedCurrent = (e) => {
l();
if ((getSession(e.id) ?? getFinishedSession(e.id)) !== e || !c(e)) throw new Error("The selected process changed. Check its current status before trying again.");
};
const p = d ?? f;
if (!p) {
resetPollRetrySuggestion(u);
return failText(missingProcessMessage(u));
}
if (p.scopeKey && p.agentId === e?.agentId && !c(p)) {
await s.resolveAncestorScopes();
if (c(p)) assertSelectedCurrent(p);
}
const m = c(d) ? d : void 0;
const h = c(f) ? f : void 0;
const sessionControlError = (e) => !e.backgrounded ? `Session ${u} is not backgrounded.` : e.finalizing ? `Session ${u} is finalizing.` : void 0;
const runningSessionResult = (e, t) => textResult(t, {
status: "running",
sessionId: u,
name: deriveSessionName(e.command)
});
switch (a.action) {
case "poll": {
const e = currentPollScope();
if (!m) {
if (h) return await runWithAgentToolSourceExecutionScope(t, async () => {
l();
return finishedPollResult(u, h, e);
});
resetPollRetrySuggestion(u);
return failText(missingProcessMessage(u));
}
if (!m.backgrounded) return failText(`Session ${u} is not backgrounded.`);
const n = resolvePollWaitMs(a.timeout);
if (n > 0 && !m.exited) {
if (i?.aborted) throw createAbortError(i.reason);
const e = performance.now() + n;
while (!m.exited && !hasPendingPollDelivery(m) && m.pendingStdoutChars + m.pendingStderrChars === 0 && !m.pendingOutputDropped && performance.now() < e) await sleepPollInterval(Math.max(0, Math.min(250, e - performance.now())), i);
}
return await runWithAgentToolSourceExecutionScope(t, async () => {
l();
if (m.exited) {
if (m.endedAt !== void 0 && c(m)) return finishedPollResult(u, m, e);
resetPollRetrySuggestion(u);
return failText(missingProcessMessage(u));
}
const t = prepareSessionPoll(m, e);
const { output: n, outputDropped: r } = t;
const i = n.trim();
const a = retentionCapNote(m);
const o = r ? "[earlier output is omitted from this poll; use action=log with offset and limit to inspect retained output]\n\n" : "";
const s = i.length > 0;
const d = recordPollRetrySuggestion(u, s);
const f = describeRunningSession(m);
const p = a + o + (i || "(no new output)") + (buildInputWaitHint(f.waitingForInput) || "\n\nProcess still running.") + (f.followUp ? `\n\n${f.followUp}` : "");
return attachInternalToolResultAcknowledgement(textResult(p, {
status: "running",
sessionId: u,
aggregated: m.aggregated,
name: deriveSessionName(m.command),
...f,
...typeof d === "number" ? { retryInMs: d } : {}
}), () => t.acknowledge());
});
}
case "log": return await runWithAgentToolSourceExecutionScope(t, async () => {
l();
const e = m ?? h;
if (!e) return failText(missingProcessMessage(u));
if (m && !m.backgrounded) return failText(`Session ${u} is not backgrounded.`);
const t = resolveLogSliceWindow(a.offset, a.limit);
const { slice: n, totalLines: r, totalChars: i } = sliceLogLines(e.aggregated, t.effectiveOffset, t.effectiveLimit);
const o = m ? describeRunningSession(m) : void 0;
const s = e.exited && e.endedAt !== void 0;
const c = retentionCapNote(e) + (n || (m ? "(no output yet)" : "(no output recorded)")) + defaultTailNote(r, t.usingDefaultTail) + (s ? `\n\n${finishedSessionText(e)}` : "");
const d = o ? c + buildInputWaitHint(o.waitingForInput) + (o.followUp ? `\n\n${o.followUp}` : "") : appendExecTimeoutRetryGuidance(c, e.exitReason);
const f = textResult(d, {
...o ? {
status: e.exited ? "completed" : "running",
sessionId: u,
name: deriveSessionName(e.command),
...o
} : finishedSessionDetails(u, e),
output: d,
total: r,
totalLines: r,
totalChars: i,
truncated: e.truncated
});
return s ? attachInternalToolResultAcknowledgement(f, () => acknowledgeNotifyOnExit(e)) : f;
});
case "write":
case "send-keys":
case "submit":
case "paste": return await runWithAgentToolSourceExecutionScope(t, async () => {
l();
const e = a.action;
if (!m) return failText(h ? `Session ${u} is already finished.` : missingProcessMessage(u));
const t = sessionControlError(m);
if (t) return failText(t);
const n = m.stdin;
if (!isWritableStdin(n)) return failText(`Session ${u} stdin is not writable.`);
if (e === "send-keys") {
const e = {
keys: a.keys,
hex: a.hex,
literal: a.literal
};
if (m.cursorKeyMode === "unknown" && hasCursorModeSensitiveKeys(e)) return failText(`Session ${u} cursor key mode is not known yet. Poll or log until startup output appears, then retry send-keys.`);
const t = m.cursorKeyMode === "unknown" ? void 0 : m.cursorKeyMode;
const { data: r, warnings: i } = encodeKeySequence(e, t);
if (r.length === 0) return failText("No key data provided.");
await writeProcessStdin(n, r);
const o = `Sent ${r.length} bytes to session ${u}.` + (i.length ? `\nWarnings:\n- ${i.join("\n- ")}` : "");
return runningSessionResult(m, o);
}
const r = e === "paste" ? encodePaste(a.text ?? "", a.bracketed !== false) : e === "submit" ? "\r" : a.data ?? "";
if (e === "paste" && !r) return failText("No paste text provided.");
await writeProcessStdin(n, r);
if (e === "write" && a.eof) {
l();
n.end();
}
const i = e === "paste" ? `Pasted ${a.text?.length ?? 0} chars to session ${u}.` : e === "submit" ? `Submitted session ${u} (sent CR).` : `Wrote ${Buffer.byteLength(a.data ?? "", "utf8")} bytes to session ${u}${a.eof ? " (stdin closed)" : ""}.`;
return runningSessionResult(m, i);
});
case "kill":
case "clear":
case "remove": return await runWithAgentToolSourceExecutionScope(t, async () => {
l();
if (a.action !== "clear" && m) {
const e = sessionControlError(m);
if (e) return failText(e);
const t = a.action === "remove";
if (!cancelBackgroundExecSession(m.id)) return failText(`Unable to ${t ? "remove" : "terminate"} session ${u}: no active supervisor cancellation handle. Use process poll to check whether it is already exiting.`);
assertSelectedCurrent(m);
if (t) {
m.backgrounded = false;
deleteSession(u);
}
resetPollRetrySuggestion(u);
return textResult(t ? `Removed session ${u} from the process list. Termination was requested but is not yet confirmed.` : `Termination requested for session ${u}. Use process poll to confirm exit and cleanup before reporting it stopped.`, {
status: "completed",
sessionId: u,
name: deriveSessionName(m.command),
cancellationRequested: true,
terminationConfirmed: false,
...!t ? { followUp: {
action: "poll",
sessionId: u
} } : {}
});
}
if (a.action === "kill") {
if (h) return textResult(appendExecTimeoutRetryGuidance(`Session ${u} is already finished. ${finishedSessionText(h)}`, h.exitReason), finishedSessionDetails(u, h));
return failText(missingProcessMessage(u));
}
if (h) {
resetPollRetrySuggestion(u);
assertSelectedCurrent(h);
deleteSession(u);
return textResult(`${a.action === "clear" ? "Cleared" : "Removed"} session ${u}.`, { status: "completed" });
}
return failText(missingProcessMessage(u));
});
}
return failText(`Unknown action ${a.action}`);
} catch (e) {
o.e = e;
} finally {
await o.d();
}
}
};
}
const processTool = createProcessTool();
//#endregion
export { execTool as i, processTool as n, createExecTool as r, createProcessTool as t };