UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,765 lines • 62 kB
import { a as addTimerTimeoutGraceMs } from "./number-coercion-D6u-4YD8.mjs";
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { t as pruneMapToMaxSize } from "./map-size-BBr20tbc.mjs";
import { t as isPlainObject } from "./plain-object-CGY5w7fM.mjs";
import "./utils-C8YECn2Q.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { E as recordDiagnosticToolExecutionDeadline, T as markToolExecutionLivenessDiagnosticEvent, c as emitTrustedDiagnosticEventWithPrivateData, l as emitTrustedSecurityEvent, s as emitTrustedDiagnosticEvent, u as emitTrustedSkillUsedDiagnosticEvent, w as createDiagnosticToolExecutionLiveness } from "./diagnostic-events-BjAH1Kbx.mjs";
import { h as createChildDiagnosticTraceContext, y as freezeDiagnosticTraceContext } from "./diagnostics-timeline-CSwiG24r.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { a as createLazyRuntimeSurface } from "./lazy-runtime-zGjszCtt.mjs";
import { p as resolveAgentRunAbortLifecycleFields } from "./run-termination-0Ig0-bk6.mjs";
import { d as isIncognitoDiagnosticSession } from "./diagnostic-runtime-BxwnWXDu.mjs";
import "./tool-policy-BR4v75RA.mjs";
import { c as normalizeToolPolicyName } from "./tool-policy-shared-BHvBopvF.mjs";
import { a as getCodeModeExecBeforeHookMetadataForToolKind, i as getCodeModeExecBeforeHookMetadata, l as normalizeCodeModeExecBeforeHookParams, n as CODE_MODE_WAIT_TOOL_NAME, o as isCodeModeControlTool, u as reconcileCodeModeExecBeforeHookParams } from "./code-mode-control-tools-2pBIuXDg.mjs";
import { d as withGatewayToolApprovalOwner, o as getGatewayToolCallerIdentity, t as captureGatewayToolCallerAssertion } from "./gateway-caller-context-BNidAW8G.mjs";
import { r as appendToolLoopWarning, s as attachInternalToolExecutionPreparer, t as InternalToolLoopBlocked } from "./internal-hooks-Ch3rqxs-.mjs";
import { i as getPluginToolMeta } from "./tool-metadata-rqUpUHlb.mjs";
import { i as markToolExecutionRefused, r as markToolExecutionNotStarted } from "./tool-effect-receipt-BbbEwqBS.mjs";
import { C as getBeforeToolCallDiagnosticOptions, E as getBeforeToolCallSourceTool, S as clearBeforeToolCallWrappedMarker, T as getBeforeToolCallHookContext, d as getToolTerminalPresentation, o as copyBeforeToolCallWrapperMetadata, w as getBeforeToolCallExecutionWrappers, x as bindBeforeToolCallMetadata } from "./agent-tool-metadata-nrQgRaqv.mjs";
import { n as getChannelAgentToolMeta } from "./channel-tool-metadata-ZKqhsBg_.mjs";
import { _ as registerActiveEmbeddedRunHumanInputWaitForRun } from "./run-state-jrY5s7TG.mjs";
import { r as resolveSkillFileHost } from "./skill-file-host-DYVvMKod.mjs";
import { n as resolveSkillReadPath, t as isWorkspaceSkillReadPath } from "./workspace-skill-read-path-nJAkXHnD.mjs";
import { n as monotonicNow } from "./monotonic-time-Cc4T2fkU.mjs";
import { t as DEFAULT_AGENT_TIMEOUT_MS } from "./timeout-BEnEcjB4.mjs";
import { c as getGlobalHookRunnerRegistry, n as getGlobalHookRunner } from "./hook-runner-global-DmYyIVDp.mjs";
import { u as cloneHookIsolationValue } from "./hooks-BiZpB_10.mjs";
import { _ as releaseBatchAdmittedToolCalls, a as consumeBatchAdmittedToolCall, d as preExecutionBlockedToolCallIds, f as recordAdjustedParamsForToolCall, g as recordToolExecutionTracked, h as recordToolExecutionStarted, m as recordStructuredReplaySafeToolCall, p as recordBatchAdmittedToolCall, r as clearTrackedToolExecution, t as buildAdjustedParamsKey, v as structuredReplaySafeToolCallIds } from "./agent-tools.before-tool-call.state-C5F7vnXY.mjs";
import { i as getTrustedToolPolicyDiagnosticEntries, n as createGatewayToolPolicyAssertion, o as hasTrustedToolPolicies, s as runTrustedToolPolicies } from "./gateway-tool-policy-Bz1T20RP.mjs";
import { t as captureAgentPluginRuntimeRefresh } from "./plugin-runtime-refresh-DCHb6kdS.mjs";
import { n as resolveSkillTelemetrySource, r as resolveSkillTelemetrySourceValue } from "./source-CoV2hxdc.mjs";
import { t as captureDiagnosticToolProgress } from "./diagnostic-run-activity-BzWz2WN_.mjs";
import { n as resolveDiagnosticModelContentCapturePolicy, t as cloneDiagnosticContentValue } from "./diagnostic-llm-content-CvUZCA61.mjs";
import { t as GatewayClientRequestError } from "./request-error-C4C6eD0S.mjs";
import { i as diagnosticHttpStatusCode, t as diagnosticErrorCategory } from "./diagnostic-error-metadata-Cc4dyoSL.mjs";
import { n as recordRunSkillUsage } from "./run-usage-B_SnZDI8.mjs";
import { i as normalizeFileToolPathParam } from "./agent-tools.params-D3Fjhk01.mjs";
import { r as getSkillInstructionFingerprint } from "./skill-instruction-result-RZ7WPgCg.mjs";
import { c as resolveToolResultFailureKind, i as protectNetworkToolExecutionError, r as isTrustedToolExecutionPreflightError, s as resolveToolExecutionErrorKind, t as formatToolExecutionErrorMessage } from "./tool-result-error-B2GHe83l.mjs";
import { t as canonicalizePath } from "./paths-CS5Q7ATF.mjs";
import "./client-cXg8kULv.mjs";
import { t as sanitizeApprovalScope } from "./approval-scope-DOnX7GXe.mjs";
import { t as isEmbeddedMode } from "./embedded-mode-CncGOzNj.mjs";
import { n as MAX_PLUGIN_APPROVAL_TIMEOUT_MS, t as DEFAULT_PLUGIN_APPROVAL_TIMEOUT_MS } from "./plugin-approvals-DAqwCYQr.mjs";
import { t as resolveCanonicalPluginApprovalRequestAllowedDecisions } from "./plugin-approval-canonical-decisions-CVZjVlcb.mjs";
import { r as getEmbeddedPluginApprovalBroker } from "./embedded-plugin-approval-broker-DbncI1uW.mjs";
import { i as resolveApprovalInitiatingSurfaceStateAsync, n as describeNativePluginApprovalClientSetup } from "./exec-approval-surface-B1PpwJWS.mjs";
import { t as callGatewayTool, u as hasInProcessGatewayToolCaller } from "./gateway-DL_Nxi-v.mjs";
import { n as extractResolvedApplyPatchTargetPaths } from "./apply-patch-paths-CccblVw-.mjs";
import { n as hashToolCall } from "./tool-loop-detection-CR_Hr4G6.mjs";
import { c as runWithBoundAgentToolSourceExecutionScope, i as copyAgentToolSourceExecutionGuard, n as captureAgentToolExecutionBudget } from "./agent-tool-source-execution-guard-CD-ezY7E.mjs";
import { n as recordGenericToolActionDecision, r as runWithGenericToolActionDecision } from "./agent-tools.before-tool-call.decision-NP6t8oB5.mjs";
import { r as validateToolExecutionParams } from "./agent-tools.execution-validation-COq3xpqN.mjs";
import { t as buildToolMutationState } from "./tool-mutation-BBJdXAL6.mjs";
import path from "node:path";
import os from "node:os";
import { isDeepStrictEqual } from "node:util";
//#region src/plugins/hook-before-tool-call-result.ts
const PluginApprovalResolutions = {
	ALLOW_ONCE: "allow-once",
	ALLOW_ALWAYS: "allow-always",
	DENY: "deny",
	TIMEOUT: "timeout",
	CANCELLED: "cancelled"
};
//#endregion
//#region src/agents/agent-tools.before-tool-call.diagnostics.ts
const beforeToolCallLog = createSubsystemLogger("agents/tools");
function startToolExecutionLiveness(e, t, n, r) {
	const i = createDiagnosticToolExecutionLiveness(n, r ? {
		attempt: r,
		toolCallId: e.toolCallId ?? e.toolName,
		toolName: e.toolName
	} : void 0);
	if (t) emitTrustedDiagnosticEvent(markToolExecutionLivenessDiagnosticEvent({
		type: "tool.execution.started",
		...e
	}, i.view));
	return i;
}
const log$1 = beforeToolCallLog;
const MAX_PENDING_TERMINAL_PRESENTATIONS = 1024;
const LOOP_WARNING_BUCKET_SIZE = 10;
const MAX_LOOP_WARNING_KEYS = 256;
const MAX_TERMINAL_PRESENTATION_CHARS = 2e3;
const pendingTerminalPresentationByToolCall = /* @__PURE__ */ new Map();
function prepareToolTerminalPresentation({ ctx: e, tool: t, toolParams: n, toolCallId: r, toolCallOrdinal: i }) {
	const a = t.name;
	const o = r ? e?.onToolOutcome : void 0;
	const s = getToolTerminalPresentation(getBeforeToolCallSourceTool(t) ?? t);
	if (!s && !o) return;
	let project;
	if (s) {
		const e = o ? structuredClone(n) : n;
		project = (t) => {
			try {
				const n = s(e, t)?.text.trim();
				return n ? truncateUtf16Safe(n, MAX_TERMINAL_PRESENTATION_CHARS) : void 0;
			} catch (e) {
				log$1.warn(`terminal tool presentation failed: tool=${a || "tool"} error=${String(e)}`);
				return;
			}
		};
	}
	return {
		observer: o,
		toolName: a,
		project,
		toolCallOrdinal: i
	};
}
function rememberPendingTerminalPresentation(e, t, n) {
	if (!e?.observer || !n) return;
	const r = buildAdjustedParamsKey({
		runId: t,
		toolCallId: n
	});
	pendingTerminalPresentationByToolCall.set(r, e);
	pruneMapToMaxSize(pendingTerminalPresentationByToolCall, MAX_PENDING_TERMINAL_PRESENTATIONS);
}
/** Finalizes a trusted terminal summary after harness result middleware. */
function finalizeToolTerminalPresentation(e) {
	const t = buildAdjustedParamsKey({
		runId: e.runId,
		toolCallId: e.toolCallId
	});
	const n = pendingTerminalPresentationByToolCall.get(t);
	pendingTerminalPresentationByToolCall.delete(t);
	const r = n?.observer ?? e.observer;
	if (!r) return;
	const i = n?.toolCallOrdinal ?? e.toolCallOrdinal;
	r({
		toolName: n?.toolName || e.toolName || "tool",
		argsHash: "",
		resultHash: "",
		...i !== void 0 ? { toolCallOrdinal: i } : {},
		terminalPresentation: e.isError ? void 0 : n?.project?.(e.result),
		presentationOnly: true
	});
}
const loadBeforeToolCallRuntime = createLazyRuntimeSurface(() => import("./agent-tools.before-tool-call.runtime.js"), ({ beforeToolCallRuntime: e }) => e);
function unwrapErrorCause(e) {
	try {
		if (!(e instanceof Error)) return e;
		const t = Object.getOwnPropertyDescriptor(e, "cause");
		if (t && "value" in t && t.value !== void 0) return t.value;
	} catch {
		return e;
	}
	return e;
}
function resolveToolErrorDiagnostic(e, t, n) {
	const r = unwrapErrorCause(e);
	const i = diagnosticHttpStatusCode(r);
	const a = resolveAgentRunAbortLifecycleFields(t);
	const o = !a.aborted ? resolveToolExecutionErrorKind(r) : a.stopReason === "timeout" ? "timed_out" : "cancelled";
	return {
		errorCategory: o === "cancelled" ? "aborted" : n ?? diagnosticErrorCategory(r),
		terminalReason: o,
		...i ? { errorCode: i } : {}
	};
}
function resolveToolResultTerminalDiagnostic(e, t) {
	const n = resolveToolResultFailureKind(e);
	if (!n) return {
		type: "tool.execution.completed",
		durationMs: t
	};
	if (n === "blocked") return {
		type: "tool.execution.blocked",
		deniedReason: "tool_result_blocked",
		reason: "tool_result_blocked"
	};
	return {
		type: "tool.execution.error",
		durationMs: t,
		errorCategory: "tool_result_error",
		terminalReason: n
	};
}
function resolveToolDiagnosticIdentity(e) {
	const t = getPluginToolMeta(e);
	if (t) return t.pluginId === "bundle-mcp" ? {
		toolSource: "mcp",
		toolOwner: t.pluginId
	} : {
		toolSource: "plugin",
		toolOwner: t.pluginId
	};
	const n = getChannelAgentToolMeta(e);
	if (n) return {
		toolSource: "channel",
		toolOwner: n.channelId
	};
	return { toolSource: "core" };
}
function canonicalSkillFile(e) {
	const t = e?.trim();
	return t && path.isAbsolute(t) ? canonicalizePath(path.resolve(t)) : void 0;
}
/** Builds the usage match for one resolved skill, keyed by its canonical SKILL.md file. */
function resolvedSkillUsageMatch(e) {
	const t = canonicalSkillFile(e.skill.filePath);
	return {
		skillName: e.skill.name.trim(),
		skillSource: resolveSkillTelemetrySource(e.skill),
		activation: e.activation,
		...t ? { skillFile: t } : {}
	};
}
function findResolvedSkillUsageMatch(e) {
	const t = e.skillName.trim();
	const n = (e.snapshot?.resolvedSkills ?? []).filter((e) => e.name.trim() === t);
	const r = n.find((t) => resolveSkillTelemetrySource(t) === e.skillSource) ?? (n.length === 1 ? n[0] : void 0);
	return r ? resolvedSkillUsageMatch({
		activation: "command",
		skill: r
	}) : void 0;
}
function resolveRelativeToolPath(e, t) {
	const n = e.trim();
	if (!n) return;
	if (n.startsWith("node://") || isWorkspaceSkillReadPath(n)) return n;
	if (n === "~") return os.homedir();
	if (n.startsWith("~/")) return path.resolve(os.homedir(), n.slice(2));
	if (path.isAbsolute(n)) return path.resolve(n);
	const r = t?.workspaceDir ?? t?.cwd;
	return r ? path.resolve(r, n) : void 0;
}
function readToolPathCandidate(e, t) {
	return isPlainObject(e) && typeof e.path === "string" ? resolveRelativeToolPath(normalizeFileToolPathParam(e.path), t) : void 0;
}
function findSkillInstructionMatch(e, t) {
	const n = e.resolvedSkills?.findLast((e) => {
		if (typeof e.name !== "string" || !e.name.trim()) return false;
		const n = typeof e.filePath === "string" ? e.filePath.trim() : "";
		const r = typeof e.baseDir === "string" ? e.baseDir.trim() : "";
		if (n && resolveSkillReadPath(e) === t) return true;
		if (resolveSkillFileHost(e) === "workspace") return false;
		return n && (n.startsWith("node://") ? n === t : path.isAbsolute(n) && path.resolve(n) === t) || r && path.isAbsolute(r) && path.resolve(r, "SKILL.md") === t;
	});
	return n ? resolvedSkillUsageMatch({
		activation: "read",
		skill: n
	}) : void 0;
}
function findSkillUsageMatch(e) {
	const t = e.ctx?.skillCommand;
	if (t) {
		const n = normalizeToolPolicyName(t.toolName ?? e.toolName);
		if (!n || n === e.toolName) {
			const n = resolveSkillTelemetrySourceValue(t.skillSource);
			const r = findResolvedSkillUsageMatch({
				skillName: t.skillName,
				skillSource: n,
				snapshot: e.ctx?.skillsSnapshot
			});
			const i = canonicalSkillFile(t.skillFile) ?? r?.skillFile;
			return {
				skillName: t.skillName,
				skillSource: n,
				activation: "command",
				...i ? { skillFile: i } : {}
			};
		}
	}
	if (e.toolName === "skills_read") {
		const t = isPlainObject(e.toolParams) ? e.toolParams.name : void 0;
		if (typeof t !== "string") return;
		const n = t.trim();
		const r = e.ctx?.skillsSnapshot;
		const i = (r?.discoverySkills ?? r?.resolvedSkills)?.find((e) => e.name === n && !e.disableModelInvocation);
		if (!i) return;
		const a = e.ctx?.skillUsagePaths?.find((e) => e.skillName === i.name && e.readPath === i.filePath);
		return a ? {
			skillFile: a.skillFile,
			skillName: a.skillName,
			skillSource: a.skillSource,
			activation: "read"
		} : resolvedSkillUsageMatch({
			activation: "read",
			skill: i
		});
	}
	if (e.toolName !== "read") return;
	const n = readToolPathCandidate(e.toolParams, e.ctx);
	if (!n) return;
	if (e.ctx?.skillsSnapshot?.resolvedSkills?.length) return findSkillInstructionMatch(e.ctx.skillsSnapshot, n);
	const r = e.ctx?.skillUsagePaths?.findLast((e) => path.resolve(e.readPath) === n);
	return r ? {
		skillFile: r.skillFile,
		skillName: r.skillName,
		skillSource: r.skillSource,
		activation: "read"
	} : void 0;
}
/**
* Records one demonstrated skill use: this run's usage receipt (review trigger) and the
* trusted skill.used event (skill_usage rows, unused-skill archive clock).
*/
function recordSkillUsed(e) {
	const t = getSkillInstructionFingerprint(e.result);
	recordRunSkillUsage({
		runId: e.ctx?.runId,
		name: e.match.skillName,
		source: e.match.skillSource,
		activation: e.match.activation,
		...e.match.skillFile ? { skillFile: e.match.skillFile } : {}
	});
	const n = e.ctx?.trace ? freezeDiagnosticTraceContext(createChildDiagnosticTraceContext(e.ctx.trace)) : void 0;
	emitTrustedSkillUsedDiagnosticEvent({
		type: "skill.used",
		...e.ctx?.runId && { runId: e.ctx.runId },
		...e.ctx?.sessionKey && { sessionKey: e.ctx.sessionKey },
		...e.ctx?.sessionId && { sessionId: e.ctx.sessionId },
		...e.ctx?.agentId && { agentId: e.ctx.agentId },
		...n && { trace: n },
		skillName: e.match.skillName,
		skillSource: e.match.skillSource,
		activation: e.match.activation,
		...t ? { skillFingerprint: t } : {},
		toolName: e.toolName,
		...e.toolCallId && { toolCallId: e.toolCallId }
	}, e.match.skillFile ? { skillUsage: { skillFile: e.match.skillFile } } : void 0);
}
function emitToolBlockedSecurityEvent(e) {
	const t = e.deniedReason === "tool-loop" ? "tool-loop-detection" : e.deniedReason === "plugin-approval" ? "plugin-tool-approval" : "plugin-before-tool-call";
	emitTrustedSecurityEvent({
		category: "tool",
		action: "tool.execution.blocked",
		outcome: "denied",
		severity: "medium",
		reason: e.deniedReason,
		...e.trace ? { trace: e.trace } : {},
		actor: { kind: "agent" },
		target: {
			kind: "tool",
			name: e.toolName,
			...e.toolIdentity.toolOwner ? { owner: e.toolIdentity.toolOwner } : {}
		},
		policy: {
			id: t,
			decision: "deny",
			reason: e.deniedReason
		},
		control: {
			id: t === "plugin-before-tool-call" ? "before-tool-call" : t,
			family: t === "tool-loop-detection" ? "authorization" : "approval"
		},
		attributes: {
			tool_source: e.toolIdentity.toolSource,
			...e.paramsSummary ? { params_kind: e.paramsSummary.kind } : {}
		}
	});
}
function buildToolContentPrivateData(e, t) {
	if (!e.toolInputs && !e.toolOutputs) return;
	const n = {};
	if (e.toolInputs) n.toolInput = cloneDiagnosticContentValue(t.input);
	if (t.includeOutput && e.toolOutputs) n.toolOutput = cloneDiagnosticContentValue(t.output);
	return Object.keys(n).length > 0 ? { toolContent: n } : void 0;
}
function summarizeToolParams(e) {
	if (e === null) return { kind: "null" };
	if (e === void 0) return { kind: "undefined" };
	if (Array.isArray(e)) return {
		kind: "array",
		length: e.length
	};
	if (typeof e === "object") return { kind: "object" };
	if (typeof e === "string") return {
		kind: "string",
		length: e.length
	};
	if (typeof e === "number") return { kind: "number" };
	if (typeof e === "boolean") return { kind: "boolean" };
	return { kind: "other" };
}
function shouldEmitLoopWarning(e, t, n) {
	if (!e.toolLoopWarningBuckets) e.toolLoopWarningBuckets = /* @__PURE__ */ new Map();
	const r = Math.floor(n / LOOP_WARNING_BUCKET_SIZE);
	if (r <= (e.toolLoopWarningBuckets.get(t) ?? 0)) return false;
	e.toolLoopWarningBuckets.set(t, r);
	pruneMapToMaxSize(e.toolLoopWarningBuckets, MAX_LOOP_WARNING_KEYS);
	return true;
}
/** Reconcile loop liveness with the final post-policy arguments before execution. */
async function reconcileLoopCallExecutionParams(e) {
	if (!e.ctx?.sessionKey && !e.ctx?.sessionId || e.ctx.loopDetection?.enabled !== true) return;
	try {
		const { getDiagnosticSessionState: t, markDiagnosticArgumentChurnObservation: n, reconcileToolCallExecutionParams: r } = await loadBeforeToolCallRuntime();
		const i = r(t({
			sessionKey: e.ctx.sessionKey,
			sessionId: e.ctx.sessionId
		}), {
			toolName: e.toolName,
			toolParams: e.toolParams,
			toolCallId: e.toolCallId,
			runId: e.ctx.runId,
			warningThreshold: 10
		});
		n({
			watchdogAttempt: e.ctx.watchdogAttempt,
			sessionKey: e.ctx.sessionKey,
			sessionId: e.ctx.sessionId,
			runId: e.ctx.runId,
			active: i
		});
	} catch (t) {
		log$1.warn(`tool loop execution-param reconciliation failed: tool=${e.toolName} error=${String(t)}`);
	}
}
async function recordLoopOutcome(e) {
	if (!e.ctx?.sessionKey && !e.ctx?.sessionId) return;
	let t;
	try {
		const { getArgumentChurnNoProgressStreak: n, getDiagnosticSessionState: r, markDiagnosticArgumentChurnObservation: i, recordToolCallOutcome: a } = await loadBeforeToolCallRuntime();
		const o = r({
			sessionKey: e.ctx.sessionKey,
			sessionId: e.ctx.sessionId
		});
		const s = a(o, {
			toolName: e.toolName,
			toolParams: e.toolParams,
			toolCallId: e.toolCallId,
			result: e.result,
			error: e.error,
			...e.ctx.runId && { runId: e.ctx.runId }
		});
		const c = s !== void 0 && n((o.toolCallHistory ?? []).filter((e) => e.runId === s.runId), s.toolName, s.argsHash).count > 0;
		i({
			watchdogAttempt: e.ctx.watchdogAttempt,
			sessionKey: e.ctx.sessionKey,
			sessionId: e.ctx.sessionId,
			runId: e.ctx.runId,
			active: c,
			existingOnly: true
		});
		if (s?.resultHash && e.ctx.onToolOutcome) t = {
			toolName: s.toolName,
			argsHash: s.argsHash,
			resultHash: s.resultHash,
			...e.resultContentSource ? { resultContentSource: e.resultContentSource } : {},
			...e.toolCallOrdinal !== void 0 ? { toolCallOrdinal: e.toolCallOrdinal } : {},
			...e.terminalPresentation ? { terminalPresentation: e.terminalPresentation } : {}
		};
	} catch (t) {
		log$1.warn(`tool loop outcome tracking failed: tool=${e.toolName} error=${String(t)}`);
	}
	if (t) e.ctx.onToolOutcome?.(t);
}
//#endregion
//#region src/agents/agent-tools.before-tool-call.approval.ts
/**
* Owns request/wait routing, embedded approval bridging, deferred approvals,
* timeout classification, and owner-provided approval outcomes.
*/
const log = createSubsystemLogger("agents/tools");
function pluginApprovalFailure(e, t, n, r = "plugin-approval") {
	return {
		blocked: true,
		kind: "failure",
		disposition: n,
		deniedReason: r,
		reason: t,
		params: e
	};
}
function pluginApprovalDeniedOutcome(e) {
	return pluginApprovalFailure(e, [
		"Denied by user. The tool call did not run.",
		"This denial is final: the approval request is closed. Do not mention /approve or any other approval command to the user.",
		"Do not run the tool call again or ask the user to approve it again.",
		"If the user still wants the action, explain that a new tool call will trigger a fresh approval request."
	].join("\n"), "blocked");
}
function resolvePluginToolApprovalTimeoutMs(e) {
	if (typeof e.timeoutMs !== "number" || !Number.isFinite(e.timeoutMs) || e.timeoutMs <= 0) return DEFAULT_PLUGIN_APPROVAL_TIMEOUT_MS;
	return Math.min(Math.floor(e.timeoutMs), MAX_PLUGIN_APPROVAL_TIMEOUT_MS);
}
function mergeParamsWithApprovalOverrides(e, t) {
	if (!isPlainObject(t)) return e;
	if (!isPlainObject(e)) return t;
	return Object.defineProperties({}, {
		...Object.getOwnPropertyDescriptors(e),
		...Object.getOwnPropertyDescriptors(t)
	});
}
function notifyPluginApprovalResolution(e, t) {
	const n = e.onResolution;
	if (typeof n !== "function") return;
	try {
		Promise.resolve(n(t)).catch((e) => {
			log.warn(`plugin onResolution callback failed: ${String(e)}`);
		});
	} catch (e) {
		log.warn(`plugin onResolution callback failed: ${String(e)}`);
	}
}
function resolvePermittedPluginApprovalResolution(e, t) {
	if ((e === PluginApprovalResolutions.ALLOW_ONCE || e === PluginApprovalResolutions.ALLOW_ALWAYS || e === PluginApprovalResolutions.DENY) && t.includes(e)) return e;
	return PluginApprovalResolutions.TIMEOUT;
}
async function buildPluginApprovalFailureReason(e) {
	const t = e.ctx?.turnSourceChannel;
	if (!t?.trim()) return e.fallbackReason;
	const n = await resolveApprovalInitiatingSurfaceStateAsync({
		channel: t,
		accountId: e.ctx?.turnSourceAccountId,
		cfg: e.ctx?.config,
		approvalKind: "plugin"
	});
	const r = describeNativePluginApprovalClientSetup({
		channel: n.channel,
		channelLabel: n.channelLabel,
		accountId: n.accountId
	});
	if (!r) return e.fallbackReason;
	if (e.noRoute) return `${e.fallbackReason}\n\n${r}`;
	if ((n.kind === "disabled" ? n : await resolveApprovalInitiatingSurfaceStateAsync({
		channel: t,
		accountId: e.ctx?.turnSourceAccountId,
		cfg: e.ctx?.config,
		approvalKind: "exec"
	})).kind !== "disabled") return e.fallbackReason;
	return `${e.fallbackReason}\n\n${r}`;
}
async function resolveUnavailablePluginApprovalSurfaceReason(e) {
	const t = e?.trigger?.trim();
	if (!t) return;
	const n = await resolveApprovalInitiatingSurfaceStateAsync({
		channel: e?.turnSourceChannel,
		accountId: e?.turnSourceAccountId,
		cfg: e?.config,
		approvalKind: "plugin"
	});
	if (t !== "user") return `Plugin approval unavailable: ${t} runs have no approval-capable initiating surface.`;
	if (!e?.turnSourceChannel?.trim() && !e?.approvalReviewerDeviceId?.trim()) return "Plugin approval unavailable: non-interactive CLI runs have no approval-capable initiating surface.";
	if (n.kind === "disabled") return `Plugin approval unavailable: the ${n.channelLabel} initiating surface is disabled.`;
	if (n.kind === "unsupported") return `Plugin approval unavailable: the ${n.channelLabel} initiating surface does not support approvals.`;
}
/**
* A pending plugin approval is the owning run's human-input wait, like an agent
* question: stuck-session recovery must not abort the turn while the approver
* can still answer. The approval's own timeout plus the gateway grace bounds it.
*/
async function requestPluginToolApproval(e) {
	const t = monotonicNow() + (addTimerTimeoutGraceMs(resolvePluginToolApprovalTimeoutMs(e.approval), 1e4) ?? 12e4 + 1e4);
	let n = true;
	let r = false;
	const i = e.ctx?.runId ? registerActiveEmbeddedRunHumanInputWaitForRun(e.ctx.runId, () => n && e.signal?.aborted !== true && monotonicNow() < t) : void 0;
	try {
		return await requestPluginToolApprovalDecision(e, () => {
			r = true;
		});
	} finally {
		n = false;
		i?.(r);
	}
}
async function requestPluginToolApprovalDecision(e, t) {
	const n = e.approval;
	const r = e.ctx?.toolOwnerPluginId ? {
		pluginKey: e.ctx.toolOwnerPluginId,
		tool: e.toolName
	} : void 0;
	const i = resolvePluginToolApprovalTimeoutMs(n);
	const a = addTimerTimeoutGraceMs(i, 1e4) ?? 12e4 + 1e4;
	const o = resolveCanonicalPluginApprovalRequestAllowedDecisions(n);
	const resolveDecision = (r) => {
		const i = resolvePermittedPluginApprovalResolution(r, o);
		notifyPluginApprovalResolution(n, i);
		if (i === PluginApprovalResolutions.ALLOW_ONCE || i === PluginApprovalResolutions.ALLOW_ALWAYS || i === PluginApprovalResolutions.DENY) t();
		if (i === PluginApprovalResolutions.ALLOW_ONCE || i === PluginApprovalResolutions.ALLOW_ALWAYS) return {
			blocked: false,
			params: mergeParamsWithApprovalOverrides(e.baseParams, e.overrideParams),
			approvalResolution: i
		};
		return i === PluginApprovalResolutions.DENY ? pluginApprovalDeniedOutcome(e.baseParams) : void 0;
	};
	let s = "none";
	const c = e.ctx?.watchdogAttempt ?? getGatewayToolCallerIdentity()?.watchdogAttempt;
	const l = captureGatewayToolCallerAssertion();
	let u;
	const beginApprovalWait = (t) => {
		u?.close();
		u = c?.beginWait({
			kind: "approval",
			deadlineAtMs: t,
			isCurrent: () => {
				e.signal?.throwIfAborted();
				l?.();
				return true;
			}
		});
	};
	try {
		const t = {
			toolName: e.toolName,
			toolCallId: e.toolCallId,
			...r ? { policySubject: r } : {},
			agentId: e.ctx?.agentId,
			sessionKey: e.ctx?.sessionKey,
			turnSourceChannel: e.ctx?.turnSourceChannel,
			turnSourceTo: e.ctx?.turnSourceTo,
			turnSourceAccountId: e.ctx?.turnSourceAccountId,
			turnSourceThreadId: e.ctx?.turnSourceThreadId
		};
		const o = isEmbeddedMode() ? getEmbeddedPluginApprovalBroker() : null;
		if (o) {
			beginApprovalWait(Date.now() + i);
			const r = resolveDecision((await o.request({
				request: {
					pluginId: n.pluginId,
					title: n.title,
					description: n.description,
					...n.scope ? { scope: sanitizeApprovalScope(n.scope) } : {},
					severity: n.severity,
					allowedDecisions: n.allowedDecisions,
					...t
				},
				timeoutMs: i,
				signal: e.signal
			})).decision);
			if (r) return r;
			return n.timeoutReason ? {
				blocked: true,
				kind: "veto",
				deniedReason: "plugin-approval",
				reason: n.timeoutReason,
				params: e.baseParams
			} : pluginApprovalFailure(e.baseParams, "Approval timed out", "timed_out");
		}
		const c = await resolveUnavailablePluginApprovalSurfaceReason(e.ctx);
		if (c) {
			notifyPluginApprovalResolution(n, PluginApprovalResolutions.CANCELLED);
			return pluginApprovalFailure(e.baseParams, c, "failed", "plugin-approval-unavailable");
		}
		const l = hasInProcessGatewayToolCaller();
		s = "request";
		const u = await withGatewayToolApprovalOwner(n.pluginId, async () => await callGatewayTool("plugin.approval.request", { timeoutMs: a }, {
			title: n.title,
			description: n.description,
			...n.scope ? { scope: n.scope } : {},
			severity: n.severity,
			allowedDecisions: n.allowedDecisions,
			...t,
			...e.ctx?.approvalReviewerDeviceId ? { approvalReviewerDeviceIds: [e.ctx.approvalReviewerDeviceId] } : {},
			timeoutMs: i,
			twoPhase: !l
		}, {
			expectFinal: l,
			signal: e.signal
		}));
		s = "none";
		const d = u?.id;
		if (!d) {
			notifyPluginApprovalResolution(n, PluginApprovalResolutions.CANCELLED);
			return pluginApprovalFailure(e.baseParams, n.description || "Plugin approval request failed", "failed");
		}
		const f = Object.hasOwn(u ?? {}, "decision");
		let p;
		if (f) {
			p = u?.decision;
			if (p === null) {
				notifyPluginApprovalResolution(n, PluginApprovalResolutions.CANCELLED);
				return pluginApprovalFailure(e.baseParams, await buildPluginApprovalFailureReason({
					fallbackReason: "Plugin approval unavailable (no approval route)",
					ctx: e.ctx,
					noRoute: true
				}), "failed");
			}
		} else {
			s = "wait";
			if (typeof u.expiresAtMs === "number") beginApprovalWait(u.expiresAtMs);
			const t = await callGatewayTool("plugin.approval.waitDecision", { timeoutMs: a }, { id: d }, { signal: e.signal });
			p = t?.id === d ? t.decision : void 0;
		}
		const m = resolveDecision(p);
		if (m) return m;
		const h = n.timeoutReason ?? "Approval timed out";
		const g = u?.deliveryRoute === "turn-source" ? await buildPluginApprovalFailureReason({
			fallbackReason: h,
			ctx: e.ctx
		}) : h;
		return {
			blocked: true,
			kind: n.timeoutReason ? "veto" : "failure",
			disposition: "timed_out",
			deniedReason: "plugin-approval",
			reason: g,
			params: e.baseParams
		};
	} catch (t) {
		notifyPluginApprovalResolution(n, PluginApprovalResolutions.CANCELLED);
		const r = e.signal;
		if (r?.aborted === true && (t === r.reason || t instanceof Error && (t.name === "AbortError" || "cause" in t && t.cause === r.reason))) {
			log.warn(`plugin approval wait cancelled by run abort: ${String(t)}`);
			return pluginApprovalFailure(e.baseParams, "Approval cancelled (run aborted)", resolveToolErrorDiagnostic(t, r).terminalReason);
		}
		const i = t instanceof GatewayClientRequestError && t.gatewayCode === "INVALID_REQUEST";
		const a = i && s === "request" ? `Plugin approval request rejected: ${formatErrorMessage(t)}` : i && s === "wait" ? `Plugin approval no longer available: ${formatErrorMessage(t)}` : "Plugin approval required (gateway unavailable)";
		log.warn(`plugin approval gateway request failed; blocking tool call: ${String(t)}`);
		return pluginApprovalFailure(e.baseParams, a, resolveToolErrorDiagnostic(t, r).terminalReason);
	} finally {
		u?.close();
	}
}
/** Resolve a deferred plugin approval request at the later execution boundary. */
async function requestDeferredPluginToolApproval(e) {
	const t = e.deferredApproval;
	return requestPluginToolApproval({
		approval: t.approval,
		toolName: t.toolName,
		...t.toolCallId ? { toolCallId: t.toolCallId } : {},
		...t.ctx ? { ctx: t.ctx } : {},
		signal: e.signal,
		baseParams: t.baseParams,
		overrideParams: t.overrideParams
	});
}
function cancelDeferredPluginToolApproval(e) {
	notifyPluginApprovalResolution(e.approval, PluginApprovalResolutions.CANCELLED);
}
async function resolveBeforeToolCallApprovalOutcome(e) {
	const t = e.result?.requireApproval;
	if (!t) return;
	const n = cloneHookIsolationValue("before_tool_call", e.baseParams);
	const r = e.result?.params === void 0 ? void 0 : cloneHookIsolationValue("before_tool_call", e.result.params);
	const createDeferredApproval = () => ({
		approval: t,
		toolName: e.toolName,
		...e.toolCallId ? { toolCallId: e.toolCallId } : {},
		...e.ctx ? { ctx: e.ctx } : {},
		baseParams: n,
		overrideParams: r
	});
	if (e.approvalMode === "defer") return {
		blocked: false,
		params: cloneHookIsolationValue("before_tool_call", n),
		deferredApproval: createDeferredApproval()
	};
	if (e.approvalMode === "report") {
		notifyPluginApprovalResolution(t, PluginApprovalResolutions.CANCELLED);
		return pluginApprovalFailure(n, t.description || t.title || "Plugin approval required", "blocked");
	}
	if (e.approvalMode === "deny") {
		notifyPluginApprovalResolution(t, PluginApprovalResolutions.DENY);
		return {
			blocked: true,
			kind: "veto",
			deniedReason: "plugin-approval",
			reason: "approval_required",
			params: n
		};
	}
	return await requestPluginToolApproval({
		...createDeferredApproval(),
		signal: e.signal
	});
}
//#endregion
//#region src/plugins/host-tool-param-parsers.ts
/**
* Derive host-owned metadata for a tool call. Returns an empty object when no
* parser is registered for the tool, which lets callers spread the result
* unconditionally without a nullability check.
*/
async function deriveToolParams(e, t, n) {
	if (e !== "apply_patch") return {};
	const r = await extractResolvedApplyPatchTargetPaths(t, n);
	return r.length > 0 ? { derivedPaths: Object.freeze(r) } : {};
}
//#endregion
//#region src/agents/tool-loop-admission.ts
function evaluateToolLoopCall(e, t, n, r) {
	const i = normalizeToolPolicyName(e.toolName || "tool");
	const { getDiagnosticSessionState: a, logToolLoopAction: o, detectToolCallLoop: s } = n;
	const c = a({
		sessionKey: t.sessionKey,
		sessionId: t.sessionId
	});
	const l = s(r ?? c, i, e.params, t.runId ? { runId: t.runId } : void 0);
	if (!l.stuck) return;
	const u = {
		sessionKey: t.sessionKey,
		sessionId: t.sessionId,
		...t.agentId ? { agentId: t.agentId } : {},
		toolName: i,
		level: l.level,
		detector: l.detector,
		count: l.count,
		message: l.message,
		pairedToolName: l.pairedToolName
	};
	if (l.level === "critical") {
		if (!isIncognitoDiagnosticSession(c)) beforeToolCallLog.error(`Blocking ${i} due to critical loop: ${l.message}`);
		o({
			...u,
			action: "block"
		});
		return {
			kind: "critical-tool-loop",
			toolCallId: e.toolCallId ?? "",
			toolName: i,
			actionKey: hashToolCall(i, e.params),
			detector: l.detector,
			count: l.count,
			reason: l.message
		};
	}
	const d = l.warningKey ?? `${l.detector}:${i}`;
	const f = t.runId ? `${t.runId}:${d}` : d;
	if (shouldEmitLoopWarning(c, f, l.count)) {
		if (!isIncognitoDiagnosticSession(c)) beforeToolCallLog.warn(`Loop warning for ${i}: ${l.message}`);
		o({
			...u,
			action: "warn"
		});
		return {
			kind: "tool-loop-warning",
			toolCallId: e.toolCallId ?? "",
			count: l.count
		};
	}
}
/** Preserve the existing single-call admission path for harnesses without batch control. */
async function admitSingleToolCallLoop(e, t) {
	if (!t.sessionKey || t.loopDetection?.enabled !== true) return;
	const n = await loadBeforeToolCallRuntime();
	const r = evaluateToolLoopCall(e, t, n);
	if (r?.kind !== "critical-tool-loop") n.recordToolCall(n.getDiagnosticSessionState({
		sessionKey: t.sessionKey,
		sessionId: t.sessionId
	}), normalizeToolPolicyName(e.toolName || "tool"), e.params, e.toolCallId, t.runId ? { runId: t.runId } : void 0);
	return r;
}
/**
* Admit an assistant tool batch atomically. Successful prepared calls reserve
* exact markers here; calls rejected by argument validation never reach the
* wrapper and reserve none. Agent-core commits both in assistant order at the
* final launch boundary, and a released call is dropped. A later veto still
* records only denial evidence.
*/
async function admitToolCallBatch(e, t) {
	if (!t.sessionKey || t.loopDetection?.enabled !== true) return {};
	const n = await loadBeforeToolCallRuntime();
	const { getDiagnosticSessionState: r, markDiagnosticArgumentChurnObservation: i, reconcileToolCallExecutionParams: a, recordToolCall: o, recordToolCallOutcome: s } = n;
	const c = 10;
	const l = r({
		sessionKey: t.sessionKey,
		sessionId: t.sessionId
	});
	const u = {
		...l,
		toolCallHistory: [...l.toolCallHistory ?? []]
	};
	const recordLoopVeto = (e, n) => {
		o(e, normalizeToolPolicyName(n.toolCall.name || "tool"), n.args, n.toolCall.id, t.runId ? { runId: t.runId } : void 0);
		const r = e.toolCallHistory?.at(-1);
		if (r) r.outcomeKind = "tool-loop-veto";
	};
	const projectLoopVeto = (e) => {
		const t = {
			...l,
			toolCallHistory: []
		};
		recordLoopVeto(t, e);
		const n = t.toolCallHistory?.at(-1);
		if (n) u.toolCallHistory?.push(n);
	};
	const d = [];
	for (const r of e) {
		const i = evaluateToolLoopCall({
			toolName: normalizeToolPolicyName(r.toolCall.name || "tool"),
			params: r.args,
			toolCallId: r.toolCall.id
		}, t, n, u);
		if (i?.kind === "critical-tool-loop") {
			for (const t of e) if (hashToolCall(normalizeToolPolicyName(t.toolCall.name || "tool"), t.args) === i.actionKey) recordLoopVeto(l, t);
			return { intervention: i };
		}
		if (i) d.push(i);
		projectLoopVeto(r);
	}
	for (const n of e) if (!n.validationFailure) recordBatchAdmittedToolCall(n.toolCall.id, t.runId);
	const f = new Map(e.map((e) => [e.toolCall.id, {
		toolName: normalizeToolPolicyName(e.toolCall.name || "tool"),
		validationFailure: e.validationFailure
	}]));
	const p = /* @__PURE__ */ new Set();
	const commitReadyCall = (e) => {
		const n = f.get(e.toolCallId);
		if (!n || p.has(e.toolCallId)) return;
		o(l, n.toolName, e.args, e.toolCallId, t.runId ? { runId: t.runId } : void 0);
		if (n.validationFailure) {
			p.add(e.toolCallId);
			const r = s(l, {
				toolName: n.toolName,
				toolParams: e.args,
				toolCallId: e.toolCallId,
				result: n.validationFailure,
				runId: t.runId
			});
			if (r) r.outcomeKind = "argument-validation";
			return;
		}
		const r = a(l, {
			toolName: n.toolName,
			toolParams: e.args,
			toolCallId: e.toolCallId,
			runId: t.runId,
			warningThreshold: c
		});
		i({
			watchdogAttempt: t.watchdogAttempt,
			sessionKey: t.sessionKey,
			sessionId: t.sessionId,
			runId: t.runId,
			active: r
		});
		p.add(e.toolCallId);
	};
	return {
		warnings: d,
		commitReadyCalls(t) {
			if (t.length === 1 && t[0]) {
				commitReadyCall(t[0]);
				return;
			}
			const n = new Map(t.map((e) => [e.toolCallId, e]));
			for (const t of e) {
				const e = n.get(t.toolCall.id);
				if (e) commitReadyCall(e);
			}
		},
		releaseSkippedCalls(e) {
			for (const t of e) f.delete(t);
			releaseBatchAdmittedToolCalls(e, t.runId);
		}
	};
}
//#endregion
//#region src/agents/agent-tools.before-tool-call.policy.ts
/**
* Ordered before_tool_call policy chain.
*
* Ordering is behavior: loop admission, owner probes,
* trusted policies, approvals, normal hooks, and final owner approval must
* remain in this sequence.
*/
const BEFORE_TOOL_CALL_HOOK_FAILURE_REASON = "Tool call blocked because before_tool_call hook failed";
/** Keep receipt routing private without widening observable hook outcomes. */
function markPrivateDecision(e, t) {
	Object.defineProperty(e, t, { value: true });
}
function getBeforeToolCallPolicyDiagnosticState() {
	const e = getGlobalHookRunnerRegistry() ?? void 0;
	return {
		hasBeforeToolCallHook: getGlobalHookRunner()?.hasHooks("before_tool_call") === true,
		trustedToolPolicies: getTrustedToolPolicyDiagnosticEntries(e)
	};
}
function hasBeforeToolCallPolicy() {
	return getGlobalHookRunner()?.hasHooks("before_tool_call") === true || hasTrustedToolPolicies(getGlobalHookRunnerRegistry() ?? void 0);
}
async function runBeforeToolCallHook(e) {
	const t = normalizeToolPolicyName(e.toolName || "tool");
	const n = e.params;
	let r;
	const withLoopWarning = (e) => {
		if (!e.blocked && r) e.loopWarning = r;
		return e;
	};
	let releaseArgumentChurnPolicyWait;
	if (e.ctx?.awaitSessionDiffBaseline) {
		await e.ctx.awaitSessionDiffBaseline();
		e.signal?.throwIfAborted();
	}
	try {
		if (e.ctx?.sessionKey) {
			if (e.ctx.loopDetection?.enabled === true) {
				const { markDiagnosticArgumentChurnObservation: t } = await loadBeforeToolCallRuntime();
				const n = Symbol("before-tool-call-policy-wait");
				const r = {
					sessionKey: e.ctx.sessionKey,
					sessionId: e.ctx.sessionId,
					runId: e.ctx.runId,
					policyWaitToken: n
				};
				t({
					...r,
					policyWait: "enter"
				});
				releaseArgumentChurnPolicyWait = () => t({
					...r,
					policyWait: "exit"
				});
			}
			if (!(e.toolCallId !== void 0 && consumeBatchAdmittedToolCall(e.toolCallId, e.ctx.runId))) {
				const i = await admitSingleToolCallLoop({
					toolName: t,
					params: n,
					toolCallId: e.toolCallId
				}, e.ctx);
				if (i?.kind === "critical-tool-loop") {
					const e = {
						blocked: true,
						kind: "veto",
						deniedReason: "tool-loop",
						reason: i.reason,
						params: n
					};
					markPrivateDecision(e, "genericDecision");
					return e;
				}
				r = i;
			}
		}
		const i = getGlobalHookRunner();
		const a = i?.hasHooks("before_tool_call") === true;
		const o = getGlobalHookRunnerRegistry() ?? void 0;
		const s = hasTrustedToolPolicies(o);
		const c = isPlainObject(n) ? n : {};
		if (!s && !a) return withLoopWarning({
			blocked: false,
			params: n
		});
		const l = e.ctx?.cwd || e.ctx?.sandbox ? {
			...e.ctx.cwd ? { cwd: e.ctx.cwd } : {},
			...e.ctx.sandbox ? { sandbox: e.ctx.sandbox } : {},
			...e.signal ? { signal: e.signal } : {}
		} : void 0;
		const u = await deriveToolParams(t, c, l);
		const deriveToolEventParams = async (e) => {
			const n = await deriveToolParams(t, e, l);
			return n.derivedPaths ? { derivedPaths: n.derivedPaths } : {};
		};
		const d = {
			...e.toolKind && { toolKind: e.toolKind },
			...e.toolInputKind && { toolInputKind: e.toolInputKind }
		};
		const buildToolContext = (n) => ({
			toolName: t,
			...n,
			...e.ctx?.agentId && { agentId: e.ctx.agentId },
			...e.ctx?.sessionKey && { sessionKey: e.ctx.sessionKey },
			...e.ctx?.sessionId && { sessionId: e.ctx.sessionId },
			...e.ctx?.runId && { runId: e.ctx.runId },
			...e.signal ? { abortSignal: e.signal } : {},
			...e.ctx?.trace && { trace: freezeDiagnosticTraceContext(e.ctx.trace) },
			...e.toolCallId && { toolCallId: e.toolCallId },
			...e.ctx?.channelId && { channelId: e.ctx.channelId },
			...e.ctx?.requester ? { requester: e.ctx.requester } : {},
			...e.ctx?.trigger && { trigger: e.ctx.trigger }
		});
		const f = buildToolContext(d);
		let p = c;
		const m = s ? await runTrustedToolPolicies({
			toolName: t,
			params: c,
			...d,
			...e.ctx?.runId && { runId: e.ctx.runId },
			...e.toolCallId && { toolCallId: e.toolCallId },
			...u.derivedPaths ? { derivedPaths: u.derivedPaths } : {}
		}, f, {
			...o ? { registry: o } : {},
			...e.ctx?.config ? { config: e.ctx.config } : {},
			deriveEvent: deriveToolEventParams,
			normalizeEvent(e) {
				const t = reconcileCodeModeExecBeforeHookParams({
					owner: { toolKind: e.toolKind },
					originalParams: p,
					hookParams: p,
					adjustedParams: e.params
				});
				if (!isPlainObject(t)) return;
				p = t;
				const n = getCodeModeExecBeforeHookMetadataForToolKind({
					toolKind: e.toolKind,
					params: t
				});
				return {
					params: t,
					...n ? {
						event: n,
						ctx: n
					} : {}
				};
			}
		}) : void 0;
		if (m?.block) {
			const e = {
				blocked: true,
				kind: "veto",
				deniedReason: "plugin-before-tool-call",
				reason: m.blockReason || "Tool call blocked by trusted plugin policy",
				params: n
			};
			markPrivateDecision(e, "genericDecision");
			return e;
		}
		let h;
		let g;
		let _ = false;
		if (m?.requireApproval) {
			const r = await resolveBeforeToolCallApprovalOutcome({
				result: m,
				approvalMode: e.approvalMode,
				toolName: t,
				...e.toolCallId ? { toolCallId: e.toolCallId } : {},
				...e.ctx ? { ctx: e.ctx } : {},
				signal: e.signal,
				baseParams: n
			});
			if (r) {
				if (r.blocked) return r;
				if (r.deferredApproval) return withLoopWarning(r);
				h = r.params;
				g = r.approvalResolution;
				_ = true;
			}
		}
		const v = h ?? m?.params ?? n;
		const y = _;
		const b = getCodeModeExecBeforeHookMetadataForToolKind({
			toolKind: e.toolKind,
			params: v
		}) ?? d;
		const x = buildToolContext(b);
		const S = m?.params && isPlainObject(v) ? await deriveToolParams(t, v, l) : u;
		const C = y && a ? cloneHookIsolationValue("before_tool_call", v) : void 0;
		let w = C ?? v;
		let T = g;
		let E = false;
		if (a) {
			const n = y ? cloneHookIsolationValue("before_tool_call", C) : v;
			const r = isPlainObject(n) ? n : {};
			const a = getGatewayToolCallerIdentity();
			const o = a?.executionIdentityToken && a.receiptAuthority ? {
				token: a.executionIdentityToken,
				assertAuthority: a.receiptAuthority,
				markOwnerDecision: () => {
					E = true;
				}
			} : void 0;
			const s = await i.runBeforeToolCall({
				toolName: t,
				params: r,
				...b,
				...e.ctx?.runId && { runId: e.ctx.runId },
				...e.toolCallId && { toolCallId: e.toolCallId },
				...S.derivedPaths ? { derivedPaths: S.derivedPaths } : {}
			}, x, o);
			if (s?.block) return {
				blocked: true,
				kind: "veto",
				deniedReason: "plugin-before-tool-call",
				reason: s.blockReason || "Tool call blocked by plugin hook",
				params: v
			};
			const c = s?.params === void 0 ? isPlainObject(n) ? r : C : mergeParamsWithApprovalOverrides(r, s.params);
			const l = s?.params === void 0 ? c : reconcileCodeModeExecBeforeHookParams({
				owner: { toolKind: e.toolKind },
				originalParams: r,
				hookParams: r,
				adjustedParams: c
			});
			if (s?.requireApproval) {
				const n = await resolveBeforeToolCallApprovalOutcome({
					result: y ? {
						...s,
						params: void 0
					} : s,
					approvalMode: e.approvalMode,
					toolName: t,
					...e.toolCallId ? { toolCallId: e.toolCallId } : {},
					...e.ctx ? { ctx: e.ctx } : {},
					signal: e.signal,
					baseParams: y ? l : v
				});
				if (n) {
					if (n.blocked) return n;
					if (n.deferredApproval) return withLoopWarning(n);
					w = n.params;
					T = n.approvalResolution ?? T;
				}
			} else if (y && !isDeepStrictEqual(C, l)) return {
				blocked: true,
				kind: "failure",
				disposition: "blocked",
				deniedReason: "plugin-approval",
				reason: "Tool call parameters changed after trusted approval",
				params: C
			};
			if (!y && s?.params) w = reconcileCodeModeExecBeforeHookParams({
				owner: { toolKind: e.toolKind },
				originalParams: v,
				hookParams: v,
				adjustedParams: mergeParamsWithApprovalOverrides(w, s.params)
			});
		}
		const D = {
			blocked: false,
			params: w
		};
		if (E || T) markPrivateDecision(D, "ownerDecision");
		if (T) D.approvalResolution = T;
		return withLoopWarning(D);
	} catch (r) {
		const i = e.toolCallId ? ` toolCallId=${e.toolCallId}` : "";
		const a = unwrapErrorCause(r);
		beforeToolCallLog.error(`before_tool_call hook failed: tool=${t}${i} error=${String(a)}`);
		return {
			blocked: true,
			kind: "failure",
			deniedReason: "plugin-before-tool-call",
			disposition: resolveToolErrorDiagnostic(a, e.signal).terminalReason,
			reason: BEFORE_TOOL_CALL_HOOK_FAILURE_REASON,
			params: n
		};
	} finally {
		try {
			releaseArgumentChurnPolicyWait?.();
		} catch (e) {
			beforeToolCallLog.warn(`before_tool_call policy-wait release failed: tool=${t} error=${String(e)}`);
		}
	}
}
//#endregion
//#region src/agents/agent-tools.execution-preparer.ts
const INTERNAL_EXECUTION_CONTROL = Symbol("openclawInternalExecutionControl");
function readInternalExecutionControl(e) {
	return e && typeof e === "object" && e[INTERNAL_EXECUTION_CONTROL] === true ? e : void 0;
}
function createInternalExecutionPreparer(e) {
	return async (t) => {
		const n = createDeferredCore();
		const r = createDeferredCore();
		const i = {
			[INTERNAL_EXECUTION_CONTROL]: true,
			ready: n.promise,
			pause: (e) => {
				n.resolve(e);
				return r.promise;
			},
			launch: (e) => r.resolve({
				launch: true,
				start: e
			}),
			dispose: () => r.resolve({ launch: false })
		};
		const a = e(t, i);
		const o = await Promise.race([i.ready.then((e) => ({
			kind: "ready",
			args: e
		})), a.then((e) => ({
			kind: "result",
			result: e
		}), (e) => ({
			kind: "error",
			error: e
		}))]);
		if (o.kind !== "ready") return {
			kind: "immediate",
			outcome: o.kind === "result" ? {
				kind: "result",
				result: o.result,
				isError: false
			} : {
				kind: "error",
				error: o.error
			},
			dispose() {}
		};
		let s = false;
		return {
			kind: "ready",
			args: o.args,
			execute(e) {
				if (!s) i.launch(e);
				return a;
			},
			dispose() {
				if (!s) {
					s = true;
					i.dispose();
					a.catch(() => void 0);
				}
			}
		};
	};
}
//#endregion
//#region src/agents/agent-tools.before-tool-call.wrapper.ts
/**
* Owns tool preparation/finalization, adjusted-param replay state, terminal
* results, diagnostics around execution, and wrapper metadata.
*/
const MAX_TRACKED_TOOL_CALL_IDS = 1024;
const INTERNAL_DISPOSED_RESULT = {
	content: [],
	details: {
		status: "skipped",
		deniedReason: "internal-dispose"
	}
};
/** Run tool-owned preparation while retaining the exact prepared object. */
async function prepareBeforeToolCallExecutionParams(e) {
	const t = e.tool.prepareBeforeToolCallParams;
	if (t && e.ctx?.awaitSessionDiffBaseline) {
		await e.ctx.awaitSessionDiffBaseline();
		e.signal?.throwIfAborted();
	}
	return t ? await t(e.params, {
		...e.toolCallId ? { toolCallId: e.toolCallId } : {},
		...e.ctx ? { hookContext: e.ctx } : {},
		...e.signal ? { signal: e.signal } : {}
	}) : e.params;
}
/** Reconcile hook rewrites and restore tool-owned state before execution. */
function finalizeBeforeToolCallExecutionParams(e) {
	const t = reconcileCodeModeExecBeforeHookParams({
		owner: { tool: e.tool },
		originalParams: e.preparedParams,
		hookParams: e.hookParams,
		adjustedParams: e.adjustedParams
	});
	const n = e.tool.finalizeBeforeToolCallParams;
	if (!n) return t;
	if (e.finalizerMode === "adapter") return n(t, e.preparedParams);
	return n.call(e.tool, t, e.preparedParams) ?? t;
}
var BeforeToolCallFailureError = class extends Error {
	constructor(e, t, n) {
		super(e, n === void 0 ? void 0 : { cause: n });
		this.disposition = t;
		this.name = "BeforeToolCallFailureError";
	}
};
function tagBeforeToolCallFailure(e, t, n) {
	try {
		if (e instanceof BeforeToolCallFailureError) return e;
	} catch {}
	const r = formatToolExecutionErrorMessage(e, "before_tool_call failed");
	const i = resolveToolErrorDiagnostic(e, t).terminalReason;
	const a = new BeforeToolCallFailureError(r, i, e);
	if (n === "tool_preparation" && isTrustedToolExecutionPreflightError(e)) markToolExecutionNotStarted(a);
	return a;
}
function getBeforeToolCallFailureDisposition(e) {
	try {
		return e instanceof BeforeToolCallFailureError ? e.disposition : void 0;
	} catch {
		return;
	}
}
/** Record that one concrete core-owned tool call may use structured replay classification. */
function recordStructuredReplayTrustForToolCall(e, t, n) {
	if (!e || getPluginToolMeta(t) || getChannelAgentToolMeta(t)) return;
	recordStructuredReplaySafeToolCall(e, n);
	pruneTrackedToolCallIds(structuredReplaySafeToolCallIds);
}
function buildBlockedToolResult(e) {
	recordPreExecutionBlockedToolCall(e.toolCallId, e.runId);
	const t = {
		content: [{
			type: "text",
			text: e.reason
		}],
		details: {
			status: "blocked",
			deniedReason: e.deniedReason ?? "plugin-before-tool-call",
			reason: e.reason
		}
	};
	return markToolExecutionRefused(t, {
		kind: "blocked",
		reason: e.reason
	});
}
function wrapToolWithBeforeToolCallHook(e, t, n = {}) {
	const r = e.execute;
	const i = createGatewayToolPolicyAssertion(e, t?.config);
	const a = captureAgentPluginRuntimeRefresh();
	const o = isCodeModeControlTool(e) && e.name === "wait" ? a.assertActive : a.assertCurrent;
	if (!r) return e;
	const s = e.name || "tool";
	const c = getPluginToolMeta(e)?.pluginId;
	const l = captureAgentToolExecutionBudget();
	const u = resolveToolDiagnosticIdentity(e);
	const d = {
		...n,
		emitDiagnostics: n.emitDiagnostics !== false
	};
	const f = resolveDiagnosticModelContentCapturePolicy(t?.config);
	const p = {
		...e,
		execute: async (n, a, p, m, ...h) => {
			const g = t?.watchdogAttempt ?? getGatewayToolCallerIdentity()?.watchdogAttempt;
			const _ = g ? {
				...t,
				watchdogAttempt: g
			} : t;
			o();
			const v = readInternalExecutionControl(h.at(-1));
			if (v) h.pop();
			const y = _?.allocateToolOutcomeOrdinal?.(n);
			const b = Date.now();
			const x = normalizeToolPolicyName(s || "tool");
			const S = d.emitDiagnostics && _?.trace ? freezeDiagnosticTraceContext(createChildDiagnosticTraceContext(_.trace)) : void 0;
			const buildEventBase = (e) => ({
				..._?.runId && { runId: _.runId },
				..._?.sessionKey && { sessionKey: _.sessionKey },
				..._?.sessionId && { sessionId: _.sessionId },
				..._?.agentId && { agentId: _.agentId },
				...S && { trace: S },
				toolName: x,
				...u,
				...n && { toolCallId: n },
				paramsSummary: summarizeToolParams(e),
				mutatingAction: buildToolMutationState(x, e).mutatingAction
			});
			const recordPreExecutionError = (e, t, r) => {
				recordPreExecutionBlockedToolCall(n, _?.runId);
				if (!d.emitDiagnostics) return;
				emitTrustedDiagnosticEvent({
					type: "tool.execution.error",
					...buildEventBase(t),
					durationMs: Date.now() - b,
					...resolveToolErrorDiagnostic(e, p, r)
				});
			};
			const recordPreExecutionDisposition = (e, t, r, i) => {
				recordPreExecutionBlockedToolCall(n, _?.runId);
				if (!d.emitDiagnostics) return;
				const a = buildEventBase(e);
				if (t === "blocked") {
					const e = i ?? "plugin-before-tool-call";
					emitTrustedDiagnosticEvent({
						type: "tool.execution.blocked",
						...a,
						deniedReason: e,
						reason: e
					});
					return;
				}
				emitTrustedDiagnosticEvent({
					type: "tool.execution.error",
					...a,
					durationMs: Date.now() - b,
					errorCategory: t === "cancelled" ? "aborted" : r,
					terminalReason: t
				});
			};
			const blockToolCall = async (t) => {
				if (t.genericDecision) recordGenericToolActionDecision(e, n, "denied");
				const r = buildEventBase(t.toolParams);
				if (d.emitDiagnostics) {
					emitTrustedDiagnosticEvent({
						type: "tool.execution.blocked",
						...r,
						reason: t.reason,
						deniedReason: t.deniedReason
					});
					emitToolBlockedSecurityEvent({
						ctx: _,
						deniedReason: t.deniedReason,
						toolIdentity: u,
						toolName: x,
						trace: S,
						paramsSummary: r.paramsSummary
					});
				}
				const i = buildBlockedToolResult({
					reason: t.reason,
					deniedReason: t.deniedReason,
					toolCallId: n,
					runId: _?.runId
				});
				await recordLoopOutcome({
					ctx: _,
					toolName: x,
					toolParams: t.toolParams,
					toolCallId: n,
					result: i,
					toolCallOrdinal: y
				});
				return i;
			};
			let C;
			try {
				C = await prepareBeforeToolCallExecutionParams({
					tool: e,
					params: a,
					toolCallId: n,
					ctx: _,
					signal: p
				});
			} catch (e) {
				recordPreExecutionError(e, a, "tool_preparation");
				throw tagBeforeToolCallFailure(e, p, "tool_preparation");
			}
			const w = normalizeCodeModeExecBeforeHookParams({
				tool: e,
				params: C
			});
			const T = getCodeModeExecBeforeHookMetadata({
				tool: e,
				params: C
			});
			let E;
			try {
				E = await runBeforeToolCallHook({
					toolName: s,
					params: w,
					...T,
					toolCallId: n,
					ctx: _ ? {
						..._,
						toolOwnerPluginId: c
					} : c ? { toolOwnerPluginId: c } : void 0,
					signal: p,
					approvalMode: d.approvalMode
				});
			} catch (e) {
				recordPreExecutionError(e, w, "before_tool_call");
				throw tagBeforeToolCallFailure(e, p, "before_tool_call");
			}
			if (E.blocked) {
				if (E.kind !== "veto") {
					recordPreExecutionDisposition(E.params ?? w, E.disposition, E.deniedReason === "plugin-approval" ? "plugin_approval" : "before_tool_call", E.deniedReason);
					throw new BeforeToolCallFailureError(E.reason, E.disposition);
				}
				return await blockToolCall({
					reason: E.reason,
					deniedReason: E.deniedReason ?? "plugin-before-tool-call",
					toolParams: E.params ?? w,
					genericDecision: E.genericDecision
				});
			}
			let D;
			try {
				p?.throwIfAborted();
				D = finalizeBeforeToolCallExecutionParams({
					tool: e,
					preparedParams: C,
					hookParams: w,
					adjustedParams: E.params,
					finalizerMode: "wrapped"
				});
				await validateToolExecutionParams(n, D);
				await reconcileLoopCallExecutionParams({
					ctx: _,
					toolName: x,
					toolParams: D,
					toolCallId: n
				});
			} catch (e) {
				recordPreExecutionError(e, E.params ?? w, "tool_preparation");
				throw tagBeforeToolCallFailure(e, p, "tool_preparation");
			}
			let O;
			if (v) {
				const t = await v.pause(D);
				if (!t.launch) {
					recordGenericToolActionDecision(e, n, "suppressed");
					return INTERNAL_DISPOSED_RESULT;
				}
				O = t.start;
			}
			const k = buildEventBase(D);
			const A = captureDiagnosticToolProgress(k);
			let j;
			const M = Date.now();
			let N = false;
			try {
				let t;
				try {
					const a = [
						n,
						D,
						p,
						m,
						...h
					];
					const invoke = () => runWithBoundAgentToolSourceExecutionScope(e, () => {
						p?.throwIfAborted();
						o();
						i(D);
						l?.();
						O?.();
						recordToolExecutionStarted(n, _?.runId);
						j = startToolExecutionLiveness(k, d.emitDiagnostics, p, _?.watchdogAttempt);
						recordAdjustedParamsForToolCall(n, D, _?.runId);
						return j.run(() => {
							const t = Date.now();
							const n = _?.getRunAbortDeadlineAtMs?.();
							const i = e.getExecutionTimeoutMs?.(D, { parentTimeoutMs: n === void 0 ? DEFAULT_AGENT_TIMEOUT_MS : Math.max(0, n - t) });
							if (i !== void 0) recordDiagnosticToolExecutionDeadline(t + i);
							return r(...a);
						});
					});
					t = E.ownerDecision ? await invoke() : await runWithGenericToolActionDecision(e, n, invoke);
				} catch (t) {
					throw d.protectNetworkErrors !== false && e.resultContentSource === "network" && !(t instanceof InternalToolLoopBlocked) && getBeforeToolCallFailureDisposition(t) === void 0 ? protectNetworkToolExecutionError(t, "Tool execution failed.", p) : t;
				}
				const a = Date.now() - M;
				const s = prepareToolTerminalPresentation({
					ctx: _,
					tool: e,
					toolParams: D,
					toolCallId: n,
					toolCallOrdinal: y
				});
				await recordLoopOutcome({
					ctx: _,
					toolName: x,
					toolParams: D,
					toolCallId: n,
					result: t,
					resultContentSource: e.resultContentSource,
					toolCallOrdinal: y,
					terminalPresentation: s?.project?.(t)
				});
				if (!p?.aborted) rememberPendingTerminalPresentation(s, _?.runId, n);
				const c = resolveToolResultTerminalDiagnostic(t, a);
				if (c.type === "tool.execution.completed" && !p?.aborted) {
					N = true;
					A?.();
				}
				const u = findSkillUsageMatch({
					toolName: x,
					toolParams: D,
					ctx: _
				});
				if (u && c.type === "tool.execution.completed") recordSkillUsed({
					ctx: _,
					match: u,
					toolName: x,
					toolCallId: n,
					result: p?.aborted ? void 0 : t
				});
				if (d.emitDiagnostics) emitTrustedDiagnosticEventWithPrivateData({
					...k,
					...c
				}, buildToolContentPrivateData(f, {
					input: D,
					output: t,
					includeOutput: true
				}));
				return E.loopWarning ? appendToolLoopWarning(t, E.loopWarning) : t;
			} catch (t) {
				if (t instanceof InternalToolLoopBlocked) {
					recordPreExecutionDisposition(D, "blocked", "tool-loop", "tool-loop");
					throw t;
				}
				if (d.emitDiagnostics) emitTrustedDiagnosticEventWithPrivateData({
					type: "tool.execution.error",
					...k,
					durationMs: Date.now() - M,
					...resolveToolErrorDiagnostic(t, p)
				}, buildToolContentPrivateData(f, {
					input: D,
					includeOutput: false
				}));
				await recordLoopOutcome({
					ctx: _,
					toolName: x,
					toolParams: D,
					toolCallId: n,
					error: t,
					resultContentSource: isTrustedToolExecutionPreflightError(t) || p?.aborted && t === p.reason ? void 0 : e.resultContentSource,
					toolCallOrdinal: y
				});
				throw t;
			} finally {
				j?.close(N);
			}
		}
	};
	const m = p.execute;
	const h = createInternalExecutionPreparer(async (e, n) => {
		recordToolExecutionTracked(e.toolCallId, t?.runId);
		try {
			return await Reflect.apply(m, p, [
				e.toolCallId,
				e.args,
				e.signal,
				e.onUpdate,
				...e.executionArgs ?? [],
				n
			]);
		} finally {
			clearTrackedToolExecution(e.toolCallId, t?.runId);
		}
	});
	attachInternalToolExecutionPreparer(p, h);
	p.execute = async (e, t, n, r, ...i) => {
		const a = await h({
			toolCallId: e,
			args: t,
			signal: n,
			onUpdate: r,
			executionArgs: i
		});
		try {
			if (a.kind === "immediate") {
				if (a.outcome.kind === "error") throw a.outcome.error;
				return a.outcome.result;
			}
			return await a.execute();
		} finally {
			a.dispose();
		}
	};
	copyBeforeToolCallWrapperMetadata(e, p);
	bindBeforeToolCallMetadata(p, {
		options: d,
		sourceTool: e,
		hookContext: t
	});
	return p;
}
/** Rebuild a before_tool_call wrapper while preserving the original source tool. */
function rewrapToolWithBeforeToolCallHook(e, t, n = {}) {
	const r = getBeforeToolCallHookContext(e);
	const i = getBeforeToolCallSourceTool(e) ?? e;
	const a = {
		...getBeforeToolCallDiagnosticOptions(e),
		...n
	};
	if (i === e) return wrapToolWithBeforeToolCallHook(e, t ?? r, a);
	const o = {
		...e,
		execute: i.execute
	};
	clearBeforeToolCallWrappedMarker(o);
	copyBeforeToolCallWrapperMetadata(e, o);
	copyAgentToolSourceExecutionGuard(i, o);
	copyAgentToolSourceExecutionGuard(e, o);
	let s = wrapToolWithBeforeToolCallHook(o, t ?? r, a);
	for (const t of getBeforeToolCallExecutionWrappers(e)) s = t(s);
	return s;
}
function recordPreExecutionBlockedToolCall(e, t) {
	if (!e) return;
	preExecutionBlockedToolCallIds.add(buildAdjustedParamsKey({
		runId: t,
		toolCallId: e
	}));
	pruneTrackedToolCallIds(preExecutionBlockedToolCallIds);
}
function pruneTrackedToolCallIds(e) {
	while (e.size > MAX_TRACKED_TOOL_CALL_IDS) {
		const t = e.values().next().value;
		if (!t) break;
		e.delete(t);
	}
}
//#endregion
export { recordSkillUsed as _, recordStructuredReplayTrustForToolCall as a, createInternalExecutionPreparer as c, hasBeforeToolCallPolicy as d, runBeforeToolCallHook as f, finalizeToolTerminalPresentation as g, requestDeferredPluginToolApproval as h, prepareBeforeToolCallExecutionParams as i, readInternalExecutionControl as l, cancelDeferredPluginToolApproval as m, finalizeBeforeToolCallExecutionParams as n, rewrapToolWithBeforeToolCallHook as o, admitToolCallBatch as p, getBeforeToolCallFailureDisposition as r, wrapToolWithBeforeToolCallHook as s, buildBlockedToolResult as t, getBeforeToolCallPolicyDiagnosticState as u, resolvedSkillUsageMatch as v, PluginApprovalResolutions as y };