UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,138 lines • 50.2 kB
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { t as pruneMapToMaxSize } from "./map-size-BBr20tbc.mjs";
import { n as getPluginRegistryState } from "./runtime-state-DVrhXeqI.mjs";
import { x as resolveSessionAgentId } from "./agent-scope-config-DmXgFGKP.mjs";
import { r as captureOpenClawStateWorkerContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs";
import { n as registerPluginMetadataProcessMemoLifecycleClear } from "./plugin-metadata-lifecycle-C9EqhiS5.mjs";
import { S as resolveRuntimeConfigCacheKey, T as selectLiveRuntimeConfig, a as getRuntimeConfigSnapshot, n as createRuntimeConfigReader } from "./runtime-snapshot-WbwbY5b7.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { n as mergeGatewayAgentCliPath } from "./openclaw-cli-shim-spskOd_w.mjs";
import { i as resolveGatewayMessageChannel } from "./message-channel-normalize-CFHSufeo.mjs";
import "./message-channel-DTYVLJT1.mjs";
import { c as hasRestrictiveAllowPolicy, o as expandPolicyWithPluginGroups, r as buildPluginToolGroups, u as replaceWithEffectiveToolAllowlist } from "./tool-policy-BR4v75RA.mjs";
import { n as CRON_SCOPED_READ_ACTIONS, r as isAutomationsToolName, t as AUTOMATIONS_TOOL_NAME } from "./automations-tool-name-DNRDs0aJ.mjs";
import { F as TOOL_CALL_RAW_TOOL_NAME } from "./tool-catalog-C1ALpCJD.mjs";
import { c as normalizeToolPolicyName, i as expandToolGroups } from "./tool-policy-shared-BHvBopvF.mjs";
import { r as createToolPolicyMatcher } from "./tool-policy-match-DzwVnbV4.mjs";
import { r as projectEffectiveExecPolicy } from "./session-permission-exec-mode-vqqWNPSg.mjs";
import { g as wrapToolWithGatewayCallerIdentity, o as getGatewayToolCallerIdentity } from "./gateway-caller-context-BNidAW8G.mjs";
import { i as getPluginToolMeta } from "./tool-metadata-rqUpUHlb.mjs";
import { i as gateAgentToolExecution, r as finalizeAgentToolAvailability, s as markAgentToolExecutionUnavailable } from "./agent-tool-availability-ecKW8hOH.mjs";
import { D as isToolWrappedWithBeforeToolCallHook, a as copyAgentToolMetadata, r as bindAssembledAgentToolActionDescriptor, y as pinExecToolTarget } from "./agent-tool-metadata-nrQgRaqv.mjs";
import { m as readToolStringParam } from "./common-njQNtpnW.mjs";
import { s as withPreparedSessionCapabilityRead } from "./subagent-session-store--G7wm9iV.mjs";
import { n as getSessionRowProjection } from "./session-row-projection-access-CjLImwLs.mjs";
import { r as resolveSandboxRuntimeStatus, s as withSandboxRuntimeStatusInWorker } from "./runtime-status-C5ZOG7YR.mjs";
import { i as logWarn } from "./logger-CIwfuhOU.mjs";
import { u as captureDelegatedToolPolicyAssertion } from "./subagent-capabilities-D82nSYzB.mjs";
import { t as resolveScheduledToolCallerContext } from "./scheduled-tool-policy-CXHVgGTq.mjs";
import { i as resolveConversationCapabilityProfile, n as prepareDelegatedToolDenyFloor, t as prepareConversationCapabilityProfile, u as resolveSessionPlacementComputer } from "./conversation-capability-profile-Be5DqCww.mjs";
import { t as applyToolPolicyPipeline } from "./tool-policy-pipeline-D-pE_49H.mjs";
import { i as resolveConversationToolPolicies, n as isConversationToolAllowed, t as buildConversationToolPolicyPipelineSteps } from "./conversation-tool-policy-pipeline-DIjQjgsq.mjs";
import { i as resolveGatewayOwnerOnlyToolDenylist } from "./dangerous-tools-DsHfDX-_.mjs";
import { o as rewrapToolWithBeforeToolCallHook } from "./agent-tools.before-tool-call.wrapper-Dh3maIc2.mjs";
import { p as resolveGatewayExecAuthority } from "./session-utils-store-CiI_s_OK.mjs";
import { o as prepareExecApprovalsCurrentRead, r as loadExecApprovals } from "./exec-approvals-store-BUZ9uOWF.mjs";
import "./exec-approvals-rOfoWejC.mjs";
import { t as prepareExecDefaults } from "./exec-defaults-BaVI-sJD.mjs";
import { r as isGatewayToolAllowedWithoutAction, t as applyGatewayToolPolicy } from "./gateway-tool-policy-Bz1T20RP.mjs";
import { t as appendRuntimePluginToolGrant } from "./tool-grant-allowlist-BZ6u_mqs.mjs";
import { t as bindAgentToolSourceExecutionGuard } from "./agent-tool-source-execution-guard-CD-ezY7E.mjs";
import { i as bindCronManagementGrant, n as bindActiveCronCreatorAuthorityResolver } from "./cron-creator-authority-context-D4fHKVAj.mjs";
import { f as replaceWithEffectiveCronCreatorToolAllowlist, h as prepareCronToolArguments } from "./cron-tool-creator-cap-sxVcNlMi.mjs";
import { a as getInProcessGatewayToolContext } from "./in-process-gateway-Cy0xoBmg.mjs";
import { n as resolveExecToolConfig } from "./lazy-exec-tool-C-cI3niu.mjs";
import { t as prepareCoreToolPolicy } from "./prepared-tool-surface-CsmkqTkz.mjs";
import { t as buildDeclaredToolAllowlistContext } from "./tool-policy-declared-context-CTgN6gTo.mjs";
import { n as wrapToolWithAbortSignal } from "./agent-tools.abort-BN-GwRlX.mjs";
import { n as resolveSandboxFileIdentity } from "./file-mutation-identity-B9yq_vIv.mjs";
import { t as withPreparedToolConstruction } from "./tool-construction-preparation-BaP4H0mb.mjs";
import { i as messageToolOwnsVisibleReply } from "./source-reply-delivery-mode-CYtLiYyC.mjs";
import { a as readScheduledOccurrenceAutomationsScope, c as readScheduledToolTargets, n as readScheduledAutomationsSelfJobId, r as readScheduledIngressAutomationsScope } from "./execution-context-registry-DYmFlODi.mjs";
import { n as resolveEventSessionRoutingPolicy } from "./event-session-routing-QCFK39bz.mjs";
import { t as applyToolAvailabilityDescriptions } from "./agent-tools.deferred-followup-Bljf_rSv.mjs";
import { a as warnIfMemoryFlushFileWriterUnavailable, i as resolveMemoryFlushToolSetup, n as assertMemoryFlushPersistenceToolAvailable, o as filterToolsByMessageProvider, r as projectMemoryFlushTools } from "./agent-tools.memory-flush-t5TUoO5U.mjs";
import { a as filterToolsByClientCaps, c as githubPublishToolDefinition, o as resolveSessionToolListingClientCaps, t as applySwarmCollectorToolContract } from "./openclaw-tools.swarm-BsHx1S11.mjs";
import { A as resolveLocalModelLeanPreserveToolNames, O as filterLocalModelLeanTools, h as resolveToolSearchConfig, n as createToolSearchTools } from "./tool-search-DcQ9xra6.mjs";
import { t as resolveNativeWebSearchRoute } from "./native-web-search-BwWfYAuV.mjs";
import { r as mergeAgentRingZeroTools, t as getActiveAgentRingZeroTools } from "./agent-tools.ring-zero-context-Cg68_lTM.mjs";
import { o as registerOneShotExecScopeCleanup } from "./bash-process-control-aLfvOIsE.mjs";
import { n as resolveProcessToolScopeKey } from "./bash-process-scope-B7TaQfLU.mjs";
import { t as applyDelegationCapability } from "./delegation-capability-BKV6nmg1.mjs";
import { t as createMemoryWriteProvenanceObserver } from "./memory-write-provenance-z3UaKwZY.mjs";
import { r as subagentAttachmentRootForRun } from "./subagent-attachment-paths-Ck2AIUx4.mjs";
import { t as resolveToolLoopDetectionConfig } from "./tool-loop-detection-config-Dzb0KwUj.mjs";
import { a as TOOL_SEARCH_RAW_TOOL_NAME, n as TOOL_DESCRIBE_RAW_TOOL_NAME } from "./tool-search-types-BgcAJ6c_.mjs";
import { t as captureSessionPortalTarget } from "./session-portal-target-dsSXsBa2.mjs";
import { isStrictOpenAIJsonSchemaCompatible, normalizeOpenAIStrictToolParameters, normalizeToolParameterSchema, prepareAnthropicInputSchema, publishRuntimeToolInputSchema } from "@openclaw/ai/internal/tool-schema";
//#region src/agents/agent-tools.caller.ts
/** Carries the coding surface's prepared policy and requesting route into plugin delegation. */
function createCodingToolsGatewayCaller(e) {
	const { options: t, agentId: n, sessionKey: r, capabilityProfile: i } = e;
	const a = /* @__PURE__ */ new Map();
	for (const t of e.tools ?? []) {
		const e = getPluginToolMeta(t);
		if (e) a.set(normalizeToolPolicyName(t.name), { pluginId: e.pluginId });
	}
	const o = getGatewayToolCallerIdentity();
	const s = i.policy.delegatedToolPolicy;
	if (s && !t?.config) throw new Error("Delegated execution requires its source configuration.");
	const c = t?.config ? captureDelegatedToolPolicyAssertion(t.config, s) : void 0;
	const allowedWithoutDelegation = (e) => createToolPolicyMatcher(expandPolicyWithPluginGroups(i.policy.inheritedToolPolicyForSpawn, buildPluginToolGroups({
		tools: [e],
		toolMeta: getPluginToolMeta
	})))(e.name);
	const l = i.policy.requesterPolicySource === "completion-handoff" ? t?.trustedInternalHandoff?.settleBatch : void 0;
	const u = t && n && r?.trim() ? {
		agentId: n,
		sessionKey: r.trim(),
		requesterOrigin: o?.agentId === n && o.sessionKey === r.trim() ? o.requesterOrigin ?? i.requesterOrigin : i.requesterOrigin,
		sessionEventToolsAllow: e.sessionEventSourcePolicy?.toolsAllow,
		sessionEventSettings: e.sessionEventSourcePolicy?.settings ?? { permissionMode: t.sessionPermissionPolicy?.mode },
		...t.sourceReplyDeliveryMode === "message_tool_only" ? { sessionEventDelivery: false } : {},
		receiptAuthority: l?.isCurrent,
		receiptAdmissions: l?.receiptAdmission ? [l.receiptAdmission] : void 0,
		assertToolAllowed: (e) => {
			if (!isConversationToolAllowed(i, e, a.get(normalizeToolPolicyName(e)))) throw new Error(`${e} is not allowed by this conversation's tool policy`);
		},
		...t.abortSignal ? { approvalSignals: [t.abortSignal] } : {},
		turnSourceChannel: resolveGatewayMessageChannel(t.messageChannel ?? t.messageProvider),
		turnSourceTo: t.currentMessagingTarget ?? t.currentChannelId ?? t.messageTo,
		turnSourceAccountId: e.accountId,
		turnSourceThreadId: t.currentThreadTs ?? t.messageThreadId
	} : void 0;
	return (e) => {
		if (!u || !c || allowedWithoutDelegation(e)) return wrapToolWithGatewayCallerIdentity(e, u);
		const t = bindAgentToolSourceExecutionGuard(e, c);
		return wrapToolWithGatewayCallerIdentity(isToolWrappedWithBeforeToolCallHook(t) ? rewrapToolWithBeforeToolCallHook(t) : t, {
			...u,
			receiptAuthority: () => {
				c();
				return u.receiptAuthority?.() ?? true;
			}
		});
	};
}
//#endregion
//#region src/agents/agent-tools.execution-policy.ts
/** Bind the config owner before asynchronous catalog preparation starts. */
function captureLocalBrowserLoopbackConfig(e) {
	const t = e ? createRuntimeConfigReader(e) : () => selectLiveRuntimeConfig();
	const n = t();
	return () => {
		if (t() !== n) throw new Error("Automatic loopback preview policy changed; retry with the current tool catalog");
	};
}
function canPrepareLocalBrowserLoopback(e) {
	return !e.sandboxed && !e.workspaceOnly && e.options?.config?.browser?.ssrfPolicy === void 0 && isConversationToolAllowed(e.capabilityProfile, "exec") && (e.options?.nativeHarnessExecution === true || isGatewayToolAllowedWithoutAction("exec", e.options?.config));
}
/** Browser previews inherit only existing unrestricted execution on this host. */
function prepareLocalBrowserLoopbackPolicy(e, t) {
	if (!canPrepareLocalBrowserLoopback(e) || t?.sandboxed) return;
	const n = e.options?.sessionPermissionPolicy;
	const r = prepareExecDefaults({
		cfg: e.options?.config,
		execApprovals: e.execApprovals,
		agentId: e.capabilityProfile.policy.agentId,
		sessionKey: e.options?.sessionKey,
		sandboxAvailable: false,
		sessionEntry: n ? { permissionMode: n.mode } : void 0,
		execOverrides: e.effectiveExecPolicy
	}, t);
	const i = r.kind === "resolved" ? r.defaults : r.resolve({ version: 1 });
	return i.effectiveHost === "gateway" && i.security === "full" && i.ask === "off" ? r : void 0;
}
/** Capture session/config policy once; only the approval owner is read at effect. */
function createLocalBrowserLoopbackAssertion(e, t, n = prepareLocalBrowserLoopbackPolicy(e)) {
	if (!n) return;
	const r = e.assertConfigCurrent ?? captureLocalBrowserLoopbackConfig(e.options?.config);
	r();
	const i = n.kind === "resolved" ? () => n.defaults : () => n.resolve(t?.() ?? e.execApprovals ?? loadExecApprovals());
	const allowed = () => {
		const e = i();
		return e.security === "full" && e.ask === "off";
	};
	if (!allowed()) return;
	return () => {
		e.options?.abortSignal?.throwIfAborted();
		e.options?.assertInvocationCurrent?.();
		r();
		if (!allowed()) throw new Error("Automatic loopback preview requires current unrestricted local execution");
	};
}
/** Optional policy preparation must never disable ordinary browser tools. */
function createLocalBrowserLoopbackPreparation(e) {
	if (!canPrepareLocalBrowserLoopback(e)) return;
	const t = {
		assertCurrent: void 0,
		sync() {
			try {
				const n = prepareLocalBrowserLoopbackPolicy(e, e.options?.sessionKey ? resolveSandboxRuntimeStatus({
					cfg: e.options.config,
					agentId: e.capabilityProfile.policy.agentId,
					sessionKey: e.options.sessionKey
				}) : void 0);
				if (n) t.assertCurrent = createLocalBrowserLoopbackAssertion(e, loadExecApprovals, n);
			} catch {
				t.assertCurrent = void 0;
			}
		},
		async prepare(n) {
			try {
				const prepare = async (r) => {
					const i = prepareLocalBrowserLoopbackPolicy(e, r);
					if (!i) return;
					const a = i.kind === "needs-approvals" ? await prepareExecApprovalsCurrentRead(captureOpenClawStateWorkerContext({ env: n.env })) : void 0;
					n.assertCurrent();
					t.assertCurrent = createLocalBrowserLoopbackAssertion(e, a, i);
				};
				if (e.options?.sessionKey) await withSandboxRuntimeStatusInWorker({
					cfg: e.options.config,
					agentId: e.capabilityProfile.policy.agentId,
					sessionKey: e.options.sessionKey
				}, n, prepare);
				else await prepare();
			} catch {
				t.assertCurrent = void 0;
			}
			n.assertCurrent();
		}
	};
	return t;
}
//#endregion
//#region src/agents/agent-tools.finalize.ts
const snapshots = /* @__PURE__ */ new Map();
const latestByKey = /* @__PURE__ */ new Map();
registerPluginMetadataProcessMemoLifecycleClear(() => {
	snapshots.clear();
	latestByKey.clear();
});
function isObjectSchemaWithNoRequiredParams(e) {
	if (!isRecord(e)) return false;
	const t = e.type;
	if (!(t === "object" || Array.isArray(t) && t.some((e) => e === "object"))) return false;
	return !schemaHasRequiredParams(e);
}
function schemaHasRequiredParams(e) {
	if (Array.isArray(e.required) && e.required.length > 0) return true;
	for (const t of [
		"allOf",
		"anyOf",
		"oneOf"
	]) {
		const n = e[t];
		if (!Array.isArray(n)) continue;
		if (n.some((e) => isRecord(e) && schemaHasRequiredParams(e))) return true;
	}
	return false;
}
function normalizeToolParameters(e, t) {
	const n = e.parameters && typeof e.parameters === "object" ? e.parameters : void 0;
	if (!n) return e;
	return bindToolParameterSchema(e, normalizeToolParameterSchema(n, {
		...t,
		toolName: e.name
	}));
}
/** Bind a prepared descriptor to this attempt's argument preparation and metadata. */
function bindToolParameterSchema(e, t) {
	const n = {
		...e,
		parameters: t
	};
	if (isObjectSchemaWithNoRequiredParams(t)) n.prepareArguments = (t) => {
		const n = e.prepareArguments ? e.prepareArguments(t) : t;
		return n === null || n === void 0 ? {} : n;
	};
	return copyAgentToolMetadata(e, n);
}
function publishParameters(e, t) {
	const n = publishRuntimeToolInputSchema(e, `${t}.parameters`, t);
	return n.violations.length === 0 && isRecord(n.schema) ? n.schema : void 0;
}
function prewarmOpenAISchema(e, t) {
	for (const n of [false, true]) {
		if (n && !isStrictOpenAIJsonSchemaCompatible(e.parameters)) continue;
		normalizeOpenAIStrictToolParameters(e.parameters, n, t);
	}
}
function finalizeAgentTools(e) {
	finalizeAgentToolAvailability(e.tools, { beforeNormalization: true });
	const t = e.hookContext.sessionId;
	const n = e.preparedModelRuntime?.metadataSnapshot;
	const r = e.modelApi;
	const i = e.modelCompat;
	const a = JSON.stringify([
		e.config ? resolveRuntimeConfigCacheKey(e.config) : void 0,
		getPluginRegistryState()?.activeVersion,
		e.modelProvider,
		e.modelId,
		r,
		i,
		e.tools.map((e) => e.name)
	]);
	const o = t ? snapshots.get(t) : void 0;
	const s = o?.key === a ? o : latestByKey.get(a);
	const c = s?.pluginMetadataSnapshot === n ? s?.entries : void 0;
	const l = e.tools.map((e) => e.parameters);
	const u = e.tools.map((t, n) => {
		const r = c?.[n];
		const i = r && r.source === t.parameters ? r.normalized : void 0;
		return i ? bindToolParameterSchema(t, i) : normalizeToolParameters(t, {
			modelProvider: e.modelProvider,
			modelId: e.modelId,
			modelCompat: e.modelCompat
		});
	});
	const d = u.map((e) => e.parameters);
	e.recordToolPrepStage?.("schema-normalization");
	const f = {
		emitDiagnostics: e.emitBeforeToolCallDiagnostics,
		...e.approvalMode ? { approvalMode: e.approvalMode } : {}
	};
	const p = e.hookContext.config || !e.config ? e.hookContext : {
		...e.hookContext,
		config: e.config
	};
	const m = e.wrapBeforeToolCallHook === false ? u : u.map((t) => typeof e.wrapBeforeToolCallHook === "function" && !e.wrapBeforeToolCallHook(t) ? t : rewrapToolWithBeforeToolCallHook(t, p, f));
	e.recordToolPrepStage?.("tool-hooks");
	const h = e.abortSignal;
	const g = h ? m.map((e) => wrapToolWithAbortSignal(e, h)) : m;
	e.recordToolPrepStage?.("abort-wrappers");
	const _ = applyToolAvailabilityDescriptions(g).map((e, t) => {
		const n = c?.[t];
		if (!n || e.description !== n.descriptor.description || e.parameters !== n.finalSource || e.outputSchema !== n.outputSource) return e;
		return copyAgentToolMetadata(e, {
			...e,
			...n.descriptor
		});
	});
	e.recordToolPrepStage?.("deferred-followup-descriptions");
	const v = e.registerRunCleanup;
	if (!t) return _;
	const y = _.map((e, t) => {
		const n = c?.[t];
		if (n && n.source === l[t] && n.descriptor.parameters === e.parameters && n.descriptor.outputSchema === e.outputSchema && n.descriptor.description === e.description) return n;
		return {
			source: l[t],
			normalized: d[t],
			finalSource: e.parameters,
			outputSource: e.outputSchema,
			descriptor: {
				name: e.name,
				description: e.description,
				parameters: e.parameters,
				outputSchema: e.outputSchema
			}
		};
	});
	if (c?.length === y.length && y.every((e, t) => e === c[t])) return _;
	const publish = () => {
		const e = latestByKey.get(a);
		const o = e?.pluginMetadataSnapshot === n ? e?.entries : void 0;
		const s = y.map((e, t) => {
			if (e === c?.[t]) return e;
			const n = o?.[t];
			if (n && n.descriptor.name === e.descriptor.name && n.source === e.source && n.outputSource === e.outputSource && n.descriptor.description === e.descriptor.description && (e.finalSource === e.normalized ? n.finalSource === n.normalized : n.finalSource === e.finalSource)) return n;
			const a = publishParameters(e.normalized, e.descriptor.name);
			const s = e.finalSource === e.normalized ? a : publishParameters(e.finalSource, e.descriptor.name);
			const l = e.outputSource ? publishParameters(e.outputSource, e.descriptor.name) : void 0;
			if (!a || !s || e.outputSource && !l) return;
			const u = {
				...e.descriptor,
				parameters: s,
				outputSchema: l
			};
			if (!r || r === "openai-responses" || r === "openai-completions") prewarmOpenAISchema(u, i);
			else if (r === "anthropic-messages") prepareAnthropicInputSchema(s);
			return {
				source: e.source,
				outputSource: e.outputSource,
				normalized: a,
				finalSource: e.finalSource === e.normalized ? a : e.finalSource,
				descriptor: u
			};
		});
		const l = {
			key: a,
			pluginMetadataSnapshot: n,
			entries: s
		};
		snapshots.delete(t);
		snapshots.set(t, l);
		pruneMapToMaxSize(snapshots, 64);
		latestByKey.delete(a);
		latestByKey.set(a, l);
		pruneMapToMaxSize(latestByKey, 16);
	};
	if (v) v(async () => publish());
	else publish();
	return _;
}
//#endregion
//#region src/agents/agent-tools.inheritance.ts
/** Record parent restrictions for future children without adding callable parent tools. */
function captureChildToolAllowlist(e) {
	const { options: t, capabilityProfile: n } = e;
	const r = n.policy.inheritancePolicies.some(hasRestrictiveAllowPolicy);
	const i = t?.additionalInheritedToolNamesRef ?? [];
	i.length = 0;
	if ((r || t?.additionalInheritedToolNamesRef) && e.includeOpenClawTools && !e.isMemoryFlushRun && t?.githubPublicationAvailable === false) {
		const e = filterToolsByMessageProvider([githubPublishToolDefinition], t?.toolPolicyMessageProvider ?? t?.messageProvider).filter(({ name: e }) => isConversationToolAllowed(n, e));
		i.push(...applyGatewayToolPolicy(e, t?.config).map((e) => e.name));
	}
	if (r) replaceWithEffectiveToolAllowlist(e.inheritedToolAllowlist, [...e.tools, ...i.map((e) => ({ name: e }))]);
}
//#endregion
//#region src/agents/agent-tools.model-provider-policy.ts
function applyModelProviderToolPolicy(e, t) {
	const n = filterLocalModelLeanTools({
		tools: e,
		config: t?.config,
		agentId: t?.agentId,
		sessionKey: t?.sessionKey,
		preserveToolNames: t?.localModelLeanPreserveToolNames ?? t?.runtimeToolAllowlist
	});
	if (t?.suppressManagedWebSearch !== false && resolveNativeWebSearchRoute({
		config: t?.config,
		modelProvider: t?.modelProvider,
		modelApi: t?.modelApi,
		modelBaseUrl: t?.modelBaseUrl,
		modelParams: t?.modelParams,
		modelId: t?.modelId,
		agentId: t?.agentId,
		sessionKey: t?.sessionKey,
		agentDir: t?.agentDir,
		runtimeToolAllowlist: t?.runtimeToolAllowlist,
		preparedRequesterPolicy: t?.preparedRequesterPolicy,
		pluginMetadataSnapshot: t?.preparedModelRuntime?.metadataSnapshot
	}).kind === "native") return n.filter((e) => e.name !== "web_search");
	return n;
}
//#endregion
//#region src/agents/agent-tools.turn-authority.ts
/**
* A host system turn: a session event the Gateway started (a scheduler notice or repair,
* a completion, a resume). The session-event executor derives the `event` trigger;
* clients cannot set it. Scheduled runs (`cron` trigger) are excluded: hook-mapped jobs
* carry external content. Without owner authority such a turn still reads the
* automations its caller scope can see.
*/
function isHostSystemTurn(e) {
	return e.trigger === "event" && e.inputProvenance?.kind === "internal_system";
}
/**
* Offers the session's tool surface on every turn, so the provider prompt prefix
* stays cacheable, and gates the calls this turn's authority does not cover.
* Owner-only tools and a completion handoff's replayed requester policy are
* per-turn authority; they never hide a tool definition.
*/
function resolveTurnToolSurface(e) {
	const t = new Set(e.turnTools.filter((t) => !e.ownerOnlyDenied.has(t.name)).map((e) => e.name));
	const turnAuthorized = (e) => t.has(e.name);
	const n = new Map(e.turnTools.map((e) => [e.name, e]));
	const r = e.sessionTools ?? e.turnTools;
	return {
		tools: r.map((t) => {
			if (turnAuthorized(t)) return t;
			const r = e.ownerOnlyDenied.has(t.name);
			const i = n.get(t.name);
			const a = r && e.hostSystemTurn === true && i !== void 0 && isAutomationsToolName(t.name) && (!i.prepareArguments || i.prepareArguments === prepareCronToolArguments) && !i.prepareBeforeToolCallParams && !i.finalizeBeforeToolCallParams;
			const o = gateAgentToolExecution(t, !i ? `${t.name} is not available during a child-completion turn because it is outside the authority carried from its requester. Do not retry ${t.name}.` : a ? `On this system-started turn, ${t.name} runs only the ${CRON_SCOPED_READ_ACTIONS.join(", ")} actions. Other actions need the owner's authority, and this turn was not started by the owner. Do not retry them.` : `${t.name} needs the owner's authority, and this turn was not started by the owner. ${t.requiredClientCaps?.length ? `Ask the owner to request it again from the open Control UI with ${t.requiredClientCaps.join(", ")}.` : `Do not retry ${t.name}.`}`);
			return markAgentToolExecutionUnavailable(copyAgentToolMetadata(t, a && i ? {
				...o,
				execute: splitScopedReadExecutor(i, o)
			} : o));
		}),
		turnAuthorized,
		/** Policy-approved tools for descendant snapshots. */
		exportedTools: e.turnTools.filter(turnAuthorized),
		/** Tools this turn may call. */
		callableTools: r.filter(turnAuthorized)
	};
}
/**
* Without an owner grant the scheduler serves only caller-visible records;
* management and every write keep their owner gate.
*/
function splitScopedReadExecutor(e, t) {
	return async (n, r, ...i) => {
		const a = isRecord(r) ? readToolStringParam(r, "action") : void 0;
		return a !== void 0 && CRON_SCOPED_READ_ACTIONS.includes(a) ? await e.execute(n, r, ...i) : await t.execute(n, r, ...i);
	};
}
//#endregion
//#region src/agents/automations-run-scope.ts
/**
* The automations scope a cron-runner turn's tools get. Scheduled occurrences and
* ingress turns (hook and channel join introduction) read it from their admitted
* execution context.
*/
/** Resolves the automations scope for one tool construction. */
function resolveAutomationsRunScope(e) {
	const t = e?.jobId?.trim();
	if (!t || e?.trigger !== "event" && e?.trigger !== "cron") return { denied: false };
	const n = e.trigger === "event" ? readScheduledIngressAutomationsScope(e) : readScheduledOccurrenceAutomationsScope(e);
	if (n) {
		const e = readScheduledAutomationsSelfJobId(n);
		return e ? {
			selfJobId: e,
			denied: false
		} : { denied: true };
	}
	return e.trigger === "cron" ? {
		selfJobId: t,
		denied: false
	} : { denied: true };
}
//#endregion
//#region src/agents/harness/host-requester.ts
/** Requester facts a harness host forwards to tool hooks, frozen from the admitted attempt. */
function buildHarnessHostRequester(e) {
	const t = e.messageChannel ?? e.messageProvider;
	return {
		...t ? { channel: t } : {},
		...e.agentAccountId ? { accountId: e.agentAccountId } : {},
		...e.senderId ? { senderId: e.senderId } : {},
		...e.senderIsOwner !== void 0 ? { senderIsOwner: e.senderIsOwner } : {},
		...e.memberRoleIds?.length ? { roleIds: Object.freeze([...e.memberRoleIds]) } : {}
	};
}
//#endregion
//#region src/agents/scheduled-message-invocation.ts
/** Admit each new invocation against published policy without changing an accepted invocation. */
function createScheduledMessageInvocationAdmission(e) {
	let t;
	return () => {
		const n = getRuntimeConfigSnapshot() ?? e.config;
		if (!n) throw new Error("Scheduled message tools require an active runtime configuration.");
		if (t?.config !== n) t = {
			config: n,
			allowed: e.isAllowed(n)
		};
		if (!t.allowed) throw new Error("Scheduled message invocation is not allowed by the current tool policy.");
		return n;
	};
}
/** Reuse the assembled embedded catalog and resource ceilings for prospective message policy. */
function createEmbeddedMessageInvocationPolicy(e) {
	const resolvePolicies = (t) => resolveConversationToolPolicies({
		capabilityProfile: t,
		additionalProfileAllow: e.runtimeProfileAlsoAllow,
		additionalPolicyAllow: e.toolSearchControlAllowlist
	});
	const t = resolvePolicies(e.capabilityProfile);
	const filter = (n = e.capabilityProfile, r, i = "turn") => {
		const a = n === e.capabilityProfile ? t : resolvePolicies(n);
		const { tools: o, declaredToolAllowlist: s, unavailableCoreToolReason: c } = e.catalog();
		return applyToolPolicyPipeline({
			tools: o,
			toolMeta: (e) => getPluginToolMeta(e),
			warn: logWarn,
			steps: buildConversationToolPolicyPipelineSteps({
				capabilityProfile: n,
				policies: {
					...a,
					groupPolicy: t.groupPolicy,
					senderPolicy: t.senderPolicy,
					sandboxPolicy: t.sandboxPolicy,
					subagentPolicy: t.subagentPolicy,
					runtimeToolPolicy: t.runtimeToolPolicy,
					inheritedToolPolicy: i === "session" ? e.capabilityProfile.policy.sessionInheritedToolPolicy : t.inheritedToolPolicy
				},
				includeRuntimeToolPolicy: true,
				unavailableCoreToolReason: c
			}),
			declaredToolAllowlist: s,
			onFilter: r
		});
	};
	return {
		filter,
		admit: createScheduledMessageInvocationAdmission({
			config: e.config,
			isAllowed: (t) => {
				const n = e.capabilityProfile;
				const r = t === e.config ? n : resolveConversationCapabilityProfile({
					...n.conversation,
					config: t,
					agentId: n.policy.agentId,
					sessionKey: n.policy.sessionKey,
					agentAccountId: n.serviceIdentity.accountId,
					modelProvider: n.model.provider,
					modelId: n.model.id,
					senderIsOwner: n.sender.isOwner,
					scheduledToolPolicy: e.scheduledToolPolicy,
					runtimePluginToolGrant: n.policy.runtimePluginToolGrant,
					pluginMetadataSnapshot: e.pluginMetadataSnapshot,
					preparedSessionCapabilityStore: {}
				});
				return e.isAvailable() && filter(r).some((e) => e.name === "message");
			}
		})
	};
}
//#endregion
//#region src/agents/tools/session-portal-target.ts
function prepareSessionPortalToolAccess(e) {
	const t = bindActiveCronCreatorAuthorityResolver(e.runId);
	const n = Boolean(e.cronSelfRemoveOnlyJobId || t || bindCronManagementGrant(e.runId));
	const r = e.senderIsOwner === false && !e.sandboxed ? prepareSessionPortalToolTarget(e) : void 0;
	return {
		sessionPortalTarget: r,
		ownerOnlyCoreToolDenylist: resolveGatewayOwnerOnlyToolDenylist(e.senderIsOwner).filter((e) => (e !== "portal" || !r) && e !== "sessions" && (e !== "automations" || !n)),
		cronCreatorAuthorityResolver: t
	};
}
/** Availability uses resident execution facts; the scoped RPC still authorizes every call. */
function prepareSessionPortalToolTarget(e) {
	if (!e.sessionId || !e.sessionKey || !e.agentId) return;
	const t = getInProcessGatewayToolContext();
	const n = t?.workerEnvironmentService;
	const r = getSessionRowProjection(t);
	const i = {
		agentId: e.agentId,
		key: e.sessionKey
	};
	const readCurrentTarget = () => {
		const e = r?.capture(i);
		const t = r?.sharingTargetState(i);
		if (!e?.storedEntry || e.unresolvedDatabaseFacts || !r?.isCurrent(e) || t?.status !== "ready" || t.target.generation !== e.generation || t.target.agentId !== e.agentId || t.target.canonicalKey !== e.key || t.target.storePath !== e.storeTarget.storePath || t.target.entry.sessionId !== e.storedEntry.sessionId || t.target.entry.lifecycleRevision !== e.storedEntry.lifecycleRevision || e.storedEntry.modelSelectionLocked === true) return;
		return t.target;
	};
	const a = readCurrentTarget();
	const o = a?.generation;
	const s = a && {
		agentId: a.agentId,
		sessionKey: a.canonicalKey,
		sessionId: a.entry.sessionId,
		sessionLifecycleRevision: a.entry.lifecycleRevision
	};
	if (!t?.portalService || !n || !s || s.sessionKey !== e.sessionKey || s.agentId !== e.agentId || s.sessionId !== e.sessionId) return;
	try {
		const e = captureSessionPortalTarget(n, s);
		return {
			sessionKey: s.sessionKey,
			agentId: s.agentId,
			environmentId: e.binding.environmentId,
			assertCurrent: () => {
				if (getInProcessGatewayToolContext() !== t) throw new Error("Session preview belongs to a different or retired Gateway");
				const n = readCurrentTarget();
				if (!n || n.generation !== o || n.entry.sessionId !== s.sessionId || n.entry.lifecycleRevision !== s.sessionLifecycleRevision) throw new Error("Conversation preview policy or session identity changed");
				e.assertCurrent();
			}
		};
	} catch {
		return;
	}
}
//#endregion
//#region src/agents/agent-tools.assembly.ts
/**
* Builds one turn's tool list and records restrictions for work it can create.
*
* 1. Resolve the turn's identity, workspace and policy. For a child, this policy
*    already includes restrictions inherited from its parent.
* 2. Assemble coding, Gateway, channel and plugin tools, then apply policy.
*    Apply deployment policy after ordinary grants so plugins cannot bypass it.
* 3. Record tool limits for future children and scheduled runs. These records
*    do not add callable tools to the current turn.
* 4. Finalize schemas and execution hooks, and bind the Gateway caller identity.
*
* Tool factories and policy modules implement each rule; this module orders
* their application. Sync and async callers share the same assembly.
*/
function* assembleOpenClawCodingTools(e, t, n, r, i = captureLocalBrowserLoopbackConfig(e?.config)) {
	const a = r?.tools;
	const o = e?.listingClientCaps ?? resolveSessionToolListingClientCaps(e ?? {});
	const s = e?.sandbox?.enabled ? e.sandbox : void 0;
	const { isMemoryFlushRun: c, memoryFlush: l, memoryFlushWritePath: u } = resolveMemoryFlushToolSetup(e);
	const d = resolveAutomationsRunScope(e);
	const f = d.selfJobId;
	const p = e?.conversationCapabilityProfile ?? resolveConversationCapabilityProfile({
		...e,
		agentId: e?.policyAgentId ?? e?.agentId,
		sandboxToolPolicy: s?.tools,
		pluginMetadataSnapshot: e?.preparedModelRuntime?.metadataSnapshot
	});
	const { agentId: m, runtimePluginToolGrant: h } = p.policy;
	const g = p.policy.globalPolicy?.deny?.some((e) => e.trim() === "*") === true && !(e?.swarmCollector && e.swarmOutputSchema);
	const _ = e?.agentId ?? (e?.runSessionKey ? resolveSessionAgentId({
		config: e.config,
		sessionKey: e.runSessionKey
	}) : m);
	const v = e?.runSessionKey ?? e?.sessionKey;
	const y = subagentAttachmentRootForRun(_, v);
	const ee = resolveToolSearchConfig(e?.config);
	const te = e?.includeToolSearchControls === true && ee.enabled;
	const b = te ? [
		TOOL_SEARCH_RAW_TOOL_NAME,
		TOOL_DESCRIBE_RAW_TOOL_NAME,
		TOOL_CALL_RAW_TOOL_NAME
	] : [];
	const ne = expandToolGroups(e?.runtimeToolAllowlist ?? []).some((e) => {
		const t = normalizeToolPolicyName(e);
		return t === "*" || t === "message";
	});
	const re = p.policy.requesterPolicySource === "completion-handoff" && e?.sourceReplyDeliveryMode === "message_tool_only";
	const ie = resolveLocalModelLeanPreserveToolNames({
		toolNames: p.policy.explicitToolOverrideAllowlist,
		forceMessageTool: e?.forceMessageTool,
		sourceReplyDeliveryMode: e?.sourceReplyDeliveryMode
	});
	const ae = [
		...e && messageToolOwnsVisibleReply(e) ? ["message"] : [],
		...ne ? ["message"] : [],
		...b
	];
	const oe = isConversationToolAllowed(p, "read");
	const x = resolveProcessToolScopeKey({
		scopeKey: e?.exec?.scopeKey,
		sessionKey: v,
		sessionId: e?.sessionId,
		agentId: _
	});
	registerOneShotExecScopeCleanup(e, x);
	e?.recordToolPrepStage?.("tool-policy");
	const S = resolveExecToolConfig({
		cfg: e?.config,
		agentId: m
	});
	const C = e?.sessionPermissionPolicy;
	const w = r?.policy ?? prepareCoreToolPolicy({
		...e,
		agentId: m
	}, S);
	const T = s?.workspaceDir;
	const E = s?.fsBridge;
	const se = s?.workspaceAccess !== "ro";
	const { workspaceRoot: D, runtimeRoot: O } = p.workspace;
	const k = T ?? O;
	const ce = T ?? C?.root ?? k;
	const A = createMemoryWriteProvenanceObserver({
		mutationRoot: T ?? D,
		workspaceDir: T ?? D,
		resolvePath: E ? (t) => resolveSandboxFileIdentity({
			bridge: E,
			filePath: t,
			cwd: T,
			signal: e?.abortSignal
		}) : void 0,
		resolveOriginClass: () => e?.senderIsOwner === false || e?.isTurnTainted?.() === true ? "untrusted" : "agent",
		sessionId: e?.sessionId,
		sessionKey: e?.runSessionKey ?? e?.sessionKey
	});
	const j = e?.includeCoreTools !== false;
	const M = e?.toolConstructionPlan ?? {
		includeBaseCodingTools: j,
		includeShellTools: j,
		includeChannelTools: j,
		includeOpenClawTools: j,
		includePluginTools: true
	};
	const le = j && M.includeBaseCodingTools;
	const ue = j && M.includeShellTools;
	const N = j && M.includeOpenClawTools;
	const de = M.includeChannelTools;
	const P = M.includePluginTools;
	const fe = {
		workspaceOnly: w.workspaceOnly,
		...C ? { root: C.root } : {},
		...y ? { readOnlyRoots: [y] } : {}
	};
	e?.recordToolPrepStage?.("workspace-policy");
	const F = e?.scheduledToolPolicy?.execTarget;
	const I = projectEffectiveExecPolicy({
		base: S,
		overrides: e?.exec,
		permissionPolicy: C,
		scheduledExecTarget: F
	});
	const L = createLocalBrowserLoopbackPreparation({
		options: e,
		capabilityProfile: p,
		effectiveExecPolicy: I,
		sandboxed: Boolean(s),
		workspaceOnly: w.workspaceOnly,
		assertConfigCurrent: i
	});
	if (L) yield { prepareBrowserLoopback: L };
	const R = a === void 0 && !g ? yield { coreTools: {
		abortSignal: e?.abortSignal,
		attachmentReadRoot: y,
		codingRoot: k,
		containmentRoot: ce,
		includeBaseCodingTools: le,
		shellTools: ue ? "full" : "disabled",
		...w,
		sandbox: s,
		skillsSnapshot: e?.skillsSnapshot,
		skillReadResources: t,
		skillInstructionPaths: e?.skillUsagePaths?.map((e) => e.readPath),
		skillInstructionDeliveryCache: e?.skillInstructionDeliveryCache,
		memoryWriteProvenance: A,
		execDefaults: {
			...e?.exec,
			...I,
			config: e?.exec?.config ?? e?.config,
			preparedRunEnvironment: e?.exec?.preparedRunEnvironment,
			reviewer: e?.exec?.reviewer ?? S.reviewer,
			reviewTranscript: e?.exec?.reviewTranscript,
			trigger: e?.trigger,
			node: e?.exec?.node ?? S.node,
			pathPrepend: mergeGatewayAgentCliPath(e?.exec?.pathPrepend ?? S.pathPrepend),
			safeBins: e?.exec?.safeBins ?? S.safeBins,
			strictInlineEval: e?.exec?.strictInlineEval ?? S.strictInlineEval,
			commandHighlighting: e?.exec?.commandHighlighting ?? S.commandHighlighting,
			safeBinTrustedDirs: e?.exec?.safeBinTrustedDirs ?? S.safeBinTrustedDirs,
			safeBinProfiles: e?.exec?.safeBinProfiles ?? S.safeBinProfiles,
			agentId: m,
			executionAgentId: _,
			cleanupMs: e?.exec?.cleanupMs ?? S.cleanupMs,
			scopeKey: x,
			sessionKey: e?.sessionKey,
			runId: e?.runId,
			operationalRunInstance: e?.operationalRunInstance,
			runSessionKey: v,
			sessionId: e?.sessionId,
			sessionStore: e?.config?.session?.store,
			eventRouting: resolveEventSessionRoutingPolicy({
				cfg: e?.config,
				sessionKey: e?.runSessionKey ?? e?.sessionKey,
				channel: e?.messageProvider,
				accountId: e?.agentAccountId
			}),
			messageProvider: e?.messageProvider,
			currentChannelId: e?.currentChannelId,
			currentMessagingTarget: e?.currentMessagingTarget,
			currentThreadTs: e?.currentThreadTs,
			channelContext: e?.channelContext,
			accountId: e?.agentAccountId,
			approvalReviewerDeviceId: e?.approvalReviewerDeviceId,
			nonInteractiveApproval: e?.swarmCollector,
			backgroundMs: e?.exec?.backgroundMs ?? S.backgroundMs,
			timeoutSec: e?.exec?.timeoutSec ?? S.timeoutSec,
			approvalRunningNoticeMs: e?.exec?.approvalRunningNoticeMs ?? S.approvalRunningNoticeMs,
			notifyOnExit: e?.exec?.notifyOnExit ?? S.notifyOnExit,
			notifyOnExitEmptySuccess: e?.exec?.notifyOnExitEmptySuccess ?? S.notifyOnExitEmptySuccess
		},
		processDefaults: {
			scopeKey: x,
			sessionKey: v,
			agentId: _,
			sessionStore: e?.config?.session?.store
		},
		recordToolPrepStage: e?.recordToolPrepStage
	} } : [];
	const z = prepareSessionPortalToolAccess({
		sessionKey: v,
		agentId: _,
		sessionId: e?.sessionId,
		senderIsOwner: e?.senderIsOwner,
		sandboxed: Boolean(s),
		runId: e?.runId,
		cronSelfRemoveOnlyJobId: f
	});
	const { sessionPortalTarget: pe, cronCreatorAuthorityResolver: me } = z;
	const B = d.denied ? [...z.ownerOnlyCoreToolDenylist, AUTOMATIONS_TOOL_NAME] : z.ownerOnlyCoreToolDenylist;
	const he = appendRuntimePluginToolGrant(p.policy.explicitToolAllowlist, h);
	const V = [...p.policy.explicitToolDenylist];
	const H = V.concat(p.policy.inheritedToolPolicy?.deny ?? [], B);
	const ge = H.concat(p.policy.inheritedToolPolicyForSpawn?.deny ?? []);
	const _e = prepareDelegatedToolDenyFloor(p, B);
	const U = e?.inheritedToolAllowlistRef ?? [];
	const W = e?.cronCreatorToolAllowlistRef ?? [];
	const G = resolveScheduledToolCallerContext({
		scheduledToolPolicy: e?.scheduledToolPolicy,
		accountId: e?.agentAccountId,
		channel: resolveGatewayMessageChannel(e?.messageChannel ?? e?.messageProvider)
	});
	const K = {
		...e,
		listingClientCaps: o,
		agentSessionKey: e?.sessionKey,
		agentChannel: resolveGatewayMessageChannel(e?.messageChannel ?? e?.messageProvider),
		agentTo: e?.messageTo,
		agentThreadId: e?.messageThreadId,
		workspaceDir: D,
		fsPolicy: fe,
		requesterSenderId: e?.senderId,
		memoryFlush: l,
		sandboxBrowserBridgeUrl: s?.browser?.bridgeUrl,
		allowHostBrowserControl: s ? s.browserAllowHostControl : true,
		allowLocalBrowserLoopback: L?.assertCurrent !== void 0,
		assertLocalBrowserLoopbackCurrent: L?.assertCurrent,
		sandboxed: Boolean(s),
		pluginToolAllowlist: he,
		pluginToolDenylist: V,
		disableMessageTool: e?.disableMessageTool || e?.swarmCollector,
		requesterAgentIdOverride: _
	};
	const ve = filterToolsByClientCaps(g || N || !P ? [] : yield { pluginTools: {
		options: K,
		resolvedConfig: e?.config
	} }, o, e?.clientCaps);
	const q = N && !c ? getActiveAgentRingZeroTools() : [];
	const ye = te && q.length === 0 ? createToolSearchTools({
		...e,
		runtimeConfig: e?.config,
		agentId: m,
		catalogRef: e?.toolSearchCatalogRef,
		executeTool: e?.toolSearchCatalogExecutor
	}) : [];
	const J = F ? R.map((e) => e.name === "exec" ? copyAgentToolMetadata(e, pinExecToolTarget(e, F)) : e) : R;
	const Y = createEmbeddedMessageInvocationPolicy({
		config: e?.config,
		capabilityProfile: p,
		runtimeProfileAlsoAllow: ae,
		toolSearchControlAllowlist: b,
		scheduledToolPolicy: e?.scheduledToolPolicy,
		pluginMetadataSnapshot: e?.preparedModelRuntime?.metadataSnapshot,
		catalog: () => ({
			tools: we,
			declaredToolAllowlist: Te,
			unavailableCoreToolReason: Se
		}),
		isAvailable: () => Ee({ name: "message" })
	});
	const X = [
		...J,
		...!g && de ? yield { channelTools: { cfg: e?.config } } : [],
		...!g && N ? mergeAgentRingZeroTools(q, yield {
			...K,
			cronSandboxContext: s,
			sessionPortalTarget: pe,
			sandboxSessionRenameOnly: p.policy.sandboxSessionRenameOnly,
			questionInputMode: p.conversation.questionInputMode,
			sessionPermissionPolicy: C,
			requesterIsSubagent: p.policy.subagentPolicy !== void 0,
			execSession: C ? { permissionMode: C.mode } : void 0,
			delegationExecAuthority: () => resolveGatewayExecAuthority(e, J, De),
			execOverrides: {
				host: I.host,
				mode: I.mode,
				security: I.security,
				ask: I.ask,
				node: e?.exec?.node ?? S.node
			},
			approvalReviewerDeviceIds: e?.approvalReviewerDeviceId ? [e.approvalReviewerDeviceId] : void 0,
			gatewayCallerAccountId: G.accountId,
			gatewayCallerChannel: G.channel,
			gatewayCallerLocal: G.local,
			gatewayCallerScheduled: G.scheduled,
			scheduledToolTargets: readScheduledToolTargets(e),
			admitScheduledMessageInvocation: e?.messageActionTurnCapability ? Y.admit : void 0,
			agentGroupId: e?.groupId ?? null,
			agentGroupChannel: e?.groupChannel ?? null,
			agentGroupSpace: e?.groupSpace ?? null,
			agentMemberRoleIds: e?.memberRoleIds,
			sandboxRoot: T,
			sandboxAgentId: s?.agentId,
			sandboxContainerWorkdir: s?.containerWorkdir,
			sandboxFsBridge: E,
			sandboxReadOnlyResourceMounts: s?.readOnlyResourceMounts,
			sandboxWorkspaceMediaReadAllowed: oe,
			spawnWorkspaceDir: p.workspace.spawnWorkspaceRoot,
			cwd: s ? p.workspace.spawnWorkspaceRoot ?? O : O,
			gatewayConfigReadAllowed: p.policy.gatewayConfigReadAllowed,
			cronCreatorToolAllowlist: W,
			cronCreatorToolAllowlistCaptureRef: e?.cronCreatorToolAllowlistCaptureRef,
			resolveCronCreatorToolAuthority: me,
			currentChatType: e?.chatType,
			computerTransport: e?.computerTransport === null ? null : e?.computerTransport ?? resolveSessionPlacementComputer(e?.operationalRunInstance),
			sourceReplyOnly: re,
			disablePluginTools: !P,
			wrapBeforeToolCallHook: false,
			...f ? { cronSelfRemoveOnlyJobId: f } : {},
			inheritedToolAllowlist: U,
			inheritedToolDenylist: ge,
			delegatedToolDenyFloor: _e,
			requesterToolDenylist: H,
			readDelegationConfig: e?.readDelegationConfig ?? (e?.config ? createRuntimeConfigReader(e.config) : void 0),
			inheritedToolPolicySource: p.policy.inheritedToolPolicySource,
			processScopeKey: x
		}) : ve,
		...ye
	];
	e?.recordToolPrepStage?.("openclaw-tools");
	const Z = a ? [...new Map([...X, ...a].map((e) => [e.name, e])).values()] : X;
	const be = e?.swarmCollector && e.swarmOutputSchema ? Z.find((e) => e.name === "structured_output") : void 0;
	const xe = projectMemoryFlushTools(Z, c && u ? {
		root: T ?? D,
		relativePath: u,
		memoryWriteProvenance: A,
		containerWorkdir: s?.containerWorkdir,
		sandbox: T && E ? {
			root: T,
			bridge: E
		} : void 0
	} : c ? e?.memoryFlushTools : void 0);
	const Se = c && u ? "memory-triggered compaction runs expose only read and append-only write" : void 0;
	const Ce = filterToolsByMessageProvider(xe, e?.toolPolicyMessageProvider ?? e?.messageProvider);
	e?.recordToolPrepStage?.("message-provider-policy");
	const we = applyModelProviderToolPolicy(Ce, {
		...e,
		agentId: m,
		preparedRequesterPolicy: p.policy,
		localModelLeanPreserveToolNames: ie
	});
	e?.recordToolPrepStage?.("model-provider-policy");
	const Te = buildDeclaredToolAllowlistContext({
		config: e?.config,
		metadataSnapshot: e?.preparedModelRuntime?.metadataSnapshot,
		workspaceDir: D,
		toolDenylist: V
	});
	const completeTurnTools = (t) => applyGatewayToolPolicy(applySwarmCollectorToolContract(applyDelegationCapability(mergeAgentRingZeroTools(q, t), e?.delegationCapability), {
		swarmCollector: e?.swarmCollector,
		structuredOutputTool: be
	}), e?.config);
	const { tools: Q, turnAuthorized: Ee, callableTools: De, exportedTools: Oe } = resolveTurnToolSurface({
		turnTools: completeTurnTools(Y.filter(p, n)),
		sessionTools: p.policy.requesterPolicySource === "completion-handoff" ? completeTurnTools(Y.filter(p, void 0, "session")) : void 0,
		ownerOnlyDenied: new Set(B),
		hostSystemTurn: isHostSystemTurn(e ?? {})
	});
	assertMemoryFlushPersistenceToolAvailable(Q, e?.memoryFlushTools);
	Q.forEach(bindAssembledAgentToolActionDescriptor);
	captureChildToolAllowlist({
		options: e,
		capabilityProfile: p,
		tools: Oe,
		inheritedToolAllowlist: U,
		includeOpenClawTools: N,
		isMemoryFlushRun: c
	});
	replaceWithEffectiveCronCreatorToolAllowlist(W, De, (e) => getPluginToolMeta(e));
	warnIfMemoryFlushFileWriterUnavailable({
		tools: Q,
		relativePath: u,
		messageProvider: e?.toolPolicyMessageProvider ?? e?.messageProvider
	});
	e?.recordToolPrepStage?.("authorization-policy");
	const ke = e?.messageChannel ?? e?.messageProvider;
	const Ae = e?.currentMessagingTarget ?? e?.currentChannelId;
	const je = buildHarnessHostRequester(e ?? {});
	const Me = {
		awaitSessionDiffBaseline: e?.awaitSessionDiffBaseline,
		getRunAbortDeadlineAtMs: e?.getRunAbortDeadlineAtMs,
		agentId: _,
		...e?.config ? { config: e.config } : {},
		cwd: k,
		workspaceDir: D,
		...e?.skillsSnapshot ? { skillsSnapshot: e.skillsSnapshot } : {},
		...e?.skillUsagePaths ? { skillUsagePaths: e.skillUsagePaths } : {},
		...T && E && se ? { sandbox: {
			root: T,
			bridge: E
		} } : {},
		sessionKey: v,
		sessionId: e?.sessionId,
		runId: e?.runId,
		trigger: e?.trigger,
		approvalReviewerDeviceId: e?.approvalReviewerDeviceId,
		channelId: e?.hookChannelId ?? e?.currentChannelId,
		...Object.keys(je).length > 0 ? { requester: je } : {},
		...ke ? { turnSourceChannel: ke } : {},
		...Ae ? { turnSourceTo: Ae } : {},
		...e?.agentAccountId ? { turnSourceAccountId: e.agentAccountId } : {},
		...e?.currentThreadTs ? { turnSourceThreadId: e.currentThreadTs } : {},
		...e?.trace ? { trace: e.trace } : {},
		loopDetection: resolveToolLoopDetectionConfig({
			cfg: e?.config,
			agentId: m
		}),
		onToolOutcome: e?.onToolOutcome,
		allocateToolOutcomeOrdinal: e?.allocateToolOutcomeOrdinal
	};
	const $ = finalizeAgentTools({
		...e,
		tools: Q,
		wrapBeforeToolCallHook: a ? (t) => e?.wrapBeforeToolCallHook !== false && !a.some((e) => e.name === t.name) : e?.wrapBeforeToolCallHook,
		hookContext: Me,
		...e?.swarmCollector ? { approvalMode: "deny" } : {}
	});
	return $.map(createCodingToolsGatewayCaller({
		options: e,
		agentId: _,
		sessionKey: v,
		accountId: G.accountId,
		capabilityProfile: p,
		tools: $,
		sessionEventSourcePolicy: e?.sessionEventSourcePolicy ?? { toolsAllow: [...$.filter(Ee).map((e) => e.name), ...!$.some((e) => e.name === "web_search") && isConversationToolAllowed(p, "web_search") ? ["web_search"] : []] }
	}));
}
//#endregion
//#region src/agents/agent-tools.preparation.ts
async function prepareCodingToolAssemblyAsync(e, t) {
	let n = e.next();
	while (!n.done) {
		if ("prepareBrowserLoopback" in n.value) {
			await n.value.prepareBrowserLoopback.prepare(t);
			n = e.next([]);
			continue;
		}
		let r;
		if ("coreTools" in n.value) {
			const { createCoreCodingTools: e } = await import("./core-coding-tools-CHcxNird.mjs");
			t.assertCurrent();
			r = e(n.value.coreTools);
		} else if ("channelTools" in n.value) {
			const { listChannelAgentTools: e } = await import("./channel-tools-CHcaHtpf.mjs");
			t.assertCurrent();
			r = e(n.value.channelTools);
		} else if ("pluginTools" in n.value) {
			const { resolveOpenClawPluginToolsForOptionsAsync: e } = await import("./openclaw-plugin-tools-BUWQ97ZS.mjs");
			t.assertCurrent();
			r = await e(n.value.pluginTools);
		} else {
			const { createOpenClawToolsWithPreparation: e } = await import("./openclaw-tools-LxjxZJmr.mjs");
			t.assertCurrent();
			r = await e(n.value, t);
		}
		t.assertCurrent();
		n = e.next(r);
	}
	return n.value;
}
//#endregion
//#region src/agents/agent-tools.async.ts
/** Internal preparation data stays outside the public harness factory options. */
async function createOpenClawCodingToolsInternalAsync(e, t, n, r, i = {}) {
	const a = captureLocalBrowserLoopbackConfig(e?.config);
	return withPreparedToolConstruction(e?.config, {
		...i,
		signal: e?.abortSignal && i.signal ? AbortSignal.any([e.abortSignal, i.signal]) : e?.abortSignal ?? i.signal
	}, async (i) => {
		const o = e?.conversationCapabilityProfile ?? await prepareConversationCapabilityProfile({
			...e,
			config: i.config,
			agentId: e?.policyAgentId ?? e?.agentId,
			sandboxToolPolicy: e?.sandbox?.enabled ? e.sandbox.tools : void 0,
			pluginMetadataSnapshot: e?.preparedModelRuntime?.metadataSnapshot
		});
		const s = e?.listingClientCaps ?? await withPreparedSessionCapabilityRead(() => resolveSessionToolListingClientCaps({
			...e,
			config: i.config
		}));
		const c = assembleOpenClawCodingTools({
			...e,
			config: i.config,
			conversationCapabilityProfile: o,
			listingClientCaps: s
		}, t, n, r, a);
		return prepareCodingToolAssemblyAsync(c, i);
	});
}
/** Build the SDK tool list with a fresh, source-bound exec policy. */
function createOpenClawCodingToolsAsync(e) {
	return createOpenClawCodingToolsInternalAsync({
		...e,
		unverifiedExecutionPolicy: true,
		readDelegationConfig: void 0
	});
}
//#endregion
export { createScheduledMessageInvocationAdmission as a, resolveTurnToolSurface as c, prepareSessionPortalToolTarget as i, createOpenClawCodingToolsInternalAsync as n, buildHarnessHostRequester as o, assembleOpenClawCodingTools as r, isHostSystemTurn as s, createOpenClawCodingToolsAsync as t };