openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
16 lines • 42.2 kB
JavaScript
import{a as addTimerTimeoutGraceMs}from"./number-coercion-B3CfI447.mjs";import{r as truncateUtf16Safe}from"./utf16-slice-DA3Mllbx.mjs";import{t as createDeferredCore}from"./deferred-QsZCoVH-.mjs";import"./utils-Dlk0IYAa.mjs";import{t as isPlainObject}from"./plain-object-CHrMoU5Q.mjs";import{t as pruneMapToMaxSize}from"./map-size-DLQqorvK.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.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-BYBrlAdF.mjs";import{b as freezeDiagnosticTraceContext,g as createChildDiagnosticTraceContext}from"./diagnostics-timeline-Wd4cnAkV.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{n as monotonicNow}from"./monotonic-time-DjtFTu2s.mjs";import{c as normalizeToolPolicyName}from"./tool-policy-shared-KKJW93v9.mjs";import{m as resolveAgentRunAbortLifecycleFields}from"./run-termination-vr_m9wT0.mjs";import"./tool-policy-Bsc3kFBH.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-CNDO-Zgv.mjs";import{d as withGatewayToolApprovalOwner,o as getGatewayToolCallerIdentity,t as captureGatewayToolCallerAssertion}from"./gateway-caller-context-Dw9IijqV.mjs";import{_ as getInternalToolResultContentSource,i as attachInternalToolExecutionPreparer}from"./internal-hooks-Bn77tst6.mjs";import{i as getPluginToolMeta}from"./tool-metadata-Cb5nBZYD.mjs";import{i as markToolExecutionRefused,r as markToolExecutionNotStarted}from"./tool-effect-receipt-B6D3MzWJ.mjs";import{C as bindBeforeToolCallMetadata,D as getBeforeToolCallHookContext,E as getBeforeToolCallExecutionWrappers,O as getBeforeToolCallSourceTool,T as getBeforeToolCallDiagnosticOptions,p as getToolTerminalPresentation,s as copyBeforeToolCallWrapperMetadata,w as clearBeforeToolCallWrappedMarker}from"./agent-tool-metadata-D7ctyGhj.mjs";import{n as getChannelAgentToolMeta}from"./channel-tool-metadata-u9xIQtTP.mjs";import{_ as registerActiveEmbeddedRunHumanInputWaitForRun}from"./run-state-Bd0P0LYH.mjs";import{r as resolveSkillFileHost}from"./skill-file-host-D4Dltnrr.mjs";import{n as resolveSkillReadPath,t as isWorkspaceSkillReadPath}from"./workspace-skill-read-path-h3bWxMAN.mjs";import{a as resolveToolResultFailureKind}from"./tool-result-error-DAdEhHzf.mjs";import{t as DEFAULT_AGENT_TIMEOUT_MS}from"./timeout-B3hylhqM.mjs";import{c as getGlobalHookRunnerRegistry,n as getGlobalHookRunner}from"./hook-runner-global-DNCi6wD6.mjs";import{h as cloneHookIsolationValue}from"./hooks-Bu2gwS_g.mjs";import{d as recordStructuredReplaySafeToolCall,f as recordToolExecutionStarted,l as preExecutionBlockedToolCallIds,m as structuredReplaySafeToolCallIds,n as clearTrackedToolExecution,p as recordToolExecutionTracked,t as buildAdjustedParamsKey,u as recordAdjustedParamsForToolCall}from"./agent-tools.before-tool-call.state-BXmY3Lwr.mjs";import{a as copyAgentToolSourceExecutionGuard,l as runWithBoundAgentToolSourceExecutionScope,r as captureAgentToolExecutionBudget}from"./agent-tool-source-execution-guard-D2z6vTFX.mjs";import{i as getTrustedToolPolicyDiagnosticEntries,n as createGatewayToolPolicyAssertion,o as hasTrustedToolPolicies,s as runTrustedToolPolicies}from"./gateway-tool-policy-B3gT1TWd.mjs";import{t as captureAgentPluginRuntimeRefresh}from"./plugin-runtime-refresh-Ef2Z3MyC.mjs";import{n as resolveSkillTelemetrySource,r as resolveSkillTelemetrySourceValue}from"./source-BOELnZ7V.mjs";import{t as captureDiagnosticToolProgress}from"./diagnostic-run-activity-D_NQZV7c.mjs";import{n as resolveDiagnosticModelContentCapturePolicy,t as cloneDiagnosticContentValue}from"./diagnostic-llm-content-BlP6pSYe.mjs";import{t as GatewayClientRequestError}from"./request-error-DCrb--_5.mjs";import{i as diagnosticHttpStatusCode,t as diagnosticErrorCategory}from"./diagnostic-error-metadata-BqX0x6ks.mjs";import{n as recordRunSkillUsage}from"./run-usage-CyNM3bV6.mjs";import{i as normalizeFileToolPathParam}from"./agent-tools.params-B4FAxIj6.mjs";import{r as getSkillInstructionFingerprint}from"./skill-instruction-result-mm50jgMT.mjs";import{i as resolveToolExecutionErrorKind,n as isTrustedToolExecutionPreflightError,r as protectNetworkToolExecutionError,t as formatToolExecutionErrorMessage}from"./tool-execution-error-C60NwMfa.mjs";import{t as canonicalizePath}from"./paths-Bavn25Xo.mjs";import"./client-BH-Snzbs.mjs";import{t as sanitizeApprovalScope}from"./approval-scope-BgbNHTF5.mjs";import{t as isEmbeddedMode}from"./embedded-mode-CWH0_8k1.mjs";import{n as MAX_PLUGIN_APPROVAL_TIMEOUT_MS,t as DEFAULT_PLUGIN_APPROVAL_TIMEOUT_MS}from"./plugin-approvals-NfNDMxex.mjs";import{t as resolveCanonicalPluginApprovalRequestAllowedDecisions}from"./plugin-approval-canonical-decisions-CtlPZigd.mjs";import{r as getEmbeddedPluginApprovalBroker}from"./embedded-plugin-approval-broker-BEtSVTTi.mjs";import{i as resolveApprovalInitiatingSurfaceStateAsync,n as describeNativePluginApprovalClientSetup}from"./exec-approval-surface-D6pya3Sh.mjs";import{t as callGatewayTool,u as hasInProcessGatewayToolCaller}from"./gateway-Bf9f0Pcc.mjs";import{n as extractResolvedApplyPatchTargetPaths}from"./apply-patch-paths-CZk-3KH8.mjs";import{n as recordGenericToolActionDecision,r as runWithGenericToolActionDecision}from"./agent-tools.before-tool-call.decision-kOa4S0Cs.mjs";import{r as validateToolExecutionParams}from"./agent-tools.execution-validation-H5xesDQ3.mjs";import{t as buildToolMutationState}from"./tool-mutation-CL1BUV0M.mjs";import{t as createToolSkillUseRecorder}from"./tool-skill-use-scope-BeKqN4oe.mjs";import path from"node:path";import os from"node:os";import{isDeepStrictEqual}from"node:util";
//!src/plugins/hook-before-tool-call-result.ts
const PluginApprovalResolutions={ALLOW_ONCE:`allow-once`,ALLOW_ALWAYS:`allow-always`,DENY:`deny`,TIMEOUT:`timeout`,CANCELLED:`cancelled`};
//!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 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)}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`,...i!==void 0?{toolCallOrdinal:i}:{},terminalPresentation:e.isError?void 0:n?.project?.(e.result),presentationOnly:true})}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}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}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===`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:`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 observeToolOutcome(e){e.ctx?.onToolOutcome?.({toolName:e.toolName,...e.resultContentSource?{resultContentSource:e.resultContentSource}:{},...e.toolCallOrdinal!==void 0?{toolCallOrdinal:e.toolCallOrdinal}:{},...e.terminalPresentation?{terminalPresentation:e.terminalPresentation}:{}})}
//!src/agents/agent-tools.before-tool-call.approval.ts
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(`
`),`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.`}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()}}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})}
//!src/plugins/host-tool-param-parsers.ts
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)}:{}}
//!src/agents/agent-tools.before-tool-call.policy.ts
const BEFORE_TOOL_CALL_HOOK_FAILURE_REASON=`Tool call blocked because before_tool_call hook failed`;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;if(e.ctx?.awaitSessionDiffBaseline){await e.ctx.awaitSessionDiffBaseline();e.signal?.throwIfAborted()}try{const r=getGlobalHookRunner();const i=r?.hasHooks(`before_tool_call`)===true;const a=getGlobalHookRunnerRegistry()??void 0;const o=hasTrustedToolPolicies(a);const s=isPlainObject(n)?n:{};if(!o&&!i)return{blocked:false,params:n};const c=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 l=await deriveToolParams(t,s,c);const deriveToolEventParams=async e=>{const n=await deriveToolParams(t,e,c);return n.derivedPaths?{derivedPaths:n.derivedPaths}:{}};const u={...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 d=buildToolContext(u);let f=s;const p=o?await runTrustedToolPolicies({toolName:t,params:s,...u,...e.ctx?.runId&&{runId:e.ctx.runId},...e.toolCallId&&{toolCallId:e.toolCallId},...l.derivedPaths?{derivedPaths:l.derivedPaths}:{}},d,{...a?{registry:a}:{},...e.ctx?.config?{config:e.ctx.config}:{},deriveEvent:deriveToolEventParams,normalizeEvent(e){const t=reconcileCodeModeExecBeforeHookParams({owner:{toolKind:e.toolKind},originalParams:f,hookParams:f,adjustedParams:e.params});if(!isPlainObject(t))return;f=t;const n=getCodeModeExecBeforeHookMetadataForToolKind({toolKind:e.toolKind,params:t});return{params:t,...n?{event:n,ctx:n}:{}}}}):void 0;if(p?.block){const e={blocked:true,kind:`veto`,deniedReason:`plugin-before-tool-call`,reason:p.blockReason||`Tool call blocked by trusted plugin policy`,params:n};markPrivateDecision(e,`genericDecision`);return e}let m;let h;let g=false;if(p?.requireApproval){const r=await resolveBeforeToolCallApprovalOutcome({result:p,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 r;m=r.params;h=r.approvalResolution;g=true}}const _=m??p?.params??n;const v=g;const y=getCodeModeExecBeforeHookMetadataForToolKind({toolKind:e.toolKind,params:_})??u;const b=buildToolContext(y);const x=p?.params&&isPlainObject(_)?await deriveToolParams(t,_,c):l;const S=v&&i?cloneHookIsolationValue(`before_tool_call`,_):void 0;let C=S??_;let w=h;let T=false;if(i){const n=v?cloneHookIsolationValue(`before_tool_call`,S):_;const i=isPlainObject(n)?n:{};const a=getGatewayToolCallerIdentity();const o=a?.executionIdentityToken&&a.receiptAuthority?{token:a.executionIdentityToken,assertAuthority:a.receiptAuthority,markOwnerDecision:()=>{T=true}}:void 0;const s=await r.runBeforeToolCall({toolName:t,params:i,...y,...e.ctx?.runId&&{runId:e.ctx.runId},...e.toolCallId&&{toolCallId:e.toolCallId},...x.derivedPaths?{derivedPaths:x.derivedPaths}:{}},b,o);if(s?.block)return{blocked:true,kind:`veto`,deniedReason:`plugin-before-tool-call`,reason:s.blockReason||`Tool call blocked by plugin hook`,params:_};const c=s?.params===void 0?isPlainObject(n)?i:S:mergeParamsWithApprovalOverrides(i,s.params);const l=s?.params===void 0?c:reconcileCodeModeExecBeforeHookParams({owner:{toolKind:e.toolKind},originalParams:i,hookParams:i,adjustedParams:c});if(s?.requireApproval){const n=await resolveBeforeToolCallApprovalOutcome({result:v?{...s,params:void 0}:s,approvalMode:e.approvalMode,toolName:t,...e.toolCallId?{toolCallId:e.toolCallId}:{},...e.ctx?{ctx:e.ctx}:{},signal:e.signal,baseParams:v?l:_});if(n){if(n.blocked)return n;if(n.deferredApproval)return n;C=n.params;w=n.approvalResolution??w}}else if(v&&!isDeepStrictEqual(S,l))return{blocked:true,kind:`failure`,disposition:`blocked`,deniedReason:`plugin-approval`,reason:`Tool call parameters changed after trusted approval`,params:S};if(!v&&s?.params)C=reconcileCodeModeExecBeforeHookParams({owner:{toolKind:e.toolKind},originalParams:_,hookParams:_,adjustedParams:mergeParamsWithApprovalOverrides(C,s.params)})}const E={blocked:false,params:C};if(T||w)markPrivateDecision(E,`ownerDecision`);if(w)E.approvalResolution=w;return E}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}}}
//!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)}}}}}
//!src/agents/agent-tools.before-tool-call.wrapper.ts
const MAX_TRACKED_TOOL_CALL_IDS=1024;const INTERNAL_DISPOSED_RESULT={content:[],details:{status:`skipped`,deniedReason:`internal-dispose`}};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}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}}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});observeToolOutcome({ctx:_,toolName:x,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)}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;let M;const N=Date.now();let P=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);const t=createToolSkillUseRecorder(e=>recordSkillUsed({ctx:_,match:e,toolName:x,toolCallId:n}));M=t;return j.run(()=>{const n=Date.now();const i=_?.getRunAbortDeadlineAtMs?.();const o=e.getExecutionTimeoutMs?.(D,{parentTimeoutMs:i===void 0?DEFAULT_AGENT_TIMEOUT_MS:Math.max(0,i-n)});if(o!==void 0)recordDiagnosticToolExecutionDeadline(n+o);return t.run(()=>r(...a))})});t=E.ownerDecision?await invoke():await runWithGenericToolActionDecision(e,n,invoke)}catch(t){throw d.protectNetworkErrors!==false&&e.resultContentSource===`network`&&getBeforeToolCallFailureDisposition(t)===void 0?protectNetworkToolExecutionError(t,`Tool execution failed.`,p):t}const a=Date.now()-N;const s=prepareToolTerminalPresentation({ctx:_,tool:e,toolParams:D,toolCallId:n,toolCallOrdinal:y});observeToolOutcome({ctx:_,toolName:x,resultContentSource:getInternalToolResultContentSource(t)??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){P=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 t}catch(t){if(d.emitDiagnostics)emitTrustedDiagnosticEventWithPrivateData({type:`tool.execution.error`,...k,durationMs:Date.now()-N,...resolveToolErrorDiagnostic(t,p)},buildToolContentPrivateData(f,{input:D,includeOutput:false}));observeToolOutcome({ctx:_,toolName:x,resultContentSource:isTrustedToolExecutionPreflightError(t)||p?.aborted&&t===p.reason?void 0:e.resultContentSource,toolCallOrdinal:y});throw t}finally{M?.close();j?.close(P)}}};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}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)}}export{resolvedSkillUsageMatch as _,recordStructuredReplayTrustForToolCall as a,createInternalExecutionPreparer as c,hasBeforeToolCallPolicy as d,runBeforeToolCallHook as f,recordSkillUsed as g,finalizeToolTerminalPresentation as h,prepareBeforeToolCallExecutionParams as i,readInternalExecutionControl as l,requestDeferredPluginToolApproval as m,finalizeBeforeToolCallExecutionParams as n,rewrapToolWithBeforeToolCallHook as o,cancelDeferredPluginToolApproval as p,getBeforeToolCallFailureDisposition as r,wrapToolWithBeforeToolCallHook as s,buildBlockedToolResult as t,getBeforeToolCallPolicyDiagnosticState as u,PluginApprovalResolutions as v};