UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

3,048 lines • 121 kB
import { l as normalizeOptionalString, t as hasNonEmptyString } from "./string-coerce-CCIiB4H7.mjs";
import { a as resolveGlobalSingleton, r as resolveGlobalMap } from "./global-singleton-D7yf05nR.mjs";
import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs";
import { t as runInDetachedAsyncContext } from "./detached-async-context-D_mi-wUl.mjs";
import { m as normalizeTrimmedStringList, y as sortUniqueStrings } from "./string-normalization-DLmfYZXI.mjs";
import { s as redactSensitiveText } from "./redact-Mj7pppxC.mjs";
import { c as isSecretRef, i as SINGLE_VALUE_FILE_REF_ID, p as isValidSecretRef, s as isBuiltInDefaultSecretProviderRef } from "./ref-contract-b8L-9DrQ.mjs";
import { g as parseSecretRef, t as LEGACY_DOUBLE_UNDERSCORE_ENV_MARKER_PREFIX } from "./types.secrets-BmNLLnHp.mjs";
import { n as describeRootFileOpenFailure } from "./boundary-file-read-BfaFLDqt.mjs";
import { i as resolveRealpathOrAbsolute } from "./boundary-path-C2gXEiXe.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import "./utils-C8YECn2Q.mjs";
import "./paths-DAcAg5aV.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { o as getPluginRuntimeGatewayRequestScope } from "./gateway-request-scope-BvvDhs5D.mjs";
import { n as PluginRuntimeCloseRetainedError } from "./runtime-close-error-Ak-r7PLO.mjs";
import { d as getActivePluginRegistryWorkspaceDirFromStateCore, u as findProviderRuntimeRegistrationInRegistry } from "./model-ref-shared-DqE2RqZv.mjs";
import { n as getPluginRuntimeLoadContextState } from "./load-context-state-Cj2HcQlf.mjs";
import { n as prepareGatewayContextBindingOwner } from "./gateway-context-binding-owner-BGZ2bJF4.mjs";
import { o as getGatewayContextResolver, t as bindGatewayContextResolver } from "./gateway-context-binding-BdXZoMU9.mjs";
import { r as normalizeProviderId } from "./provider-id-b5XGSf9C.mjs";
import { a as resolveAgentDir, g as resolveDefaultAgentDir } from "./agent-scope-config-DmXgFGKP.mjs";
import { n as discoverOpenClawPlugins, v as resolveImmutableInstallIdentity, y as resolvePluginCandidateInstallOwner } from "./discovery-DvJYrQFY.mjs";
import { a as getPluginCache, b as retirePluginCache, g as releasePluginCacheInstance, i as createPluginCache, w as withPluginCache } from "./plugin-cache-B_eRuqTM.mjs";
import { i as PluginInventoryRetiredError } from "./plugin-instance-error-BCRn5qri.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { a as resolveCompatibilityHostVersion, t as VERSION } from "./version-GlxUMdxI.mjs";
import { a as createLazyRuntimeSurface, i as createLazyRuntimeNamedExport, r as createLazyRuntimeModule, t as createLazyRuntimeMethod } from "./lazy-runtime-zGjszCtt.mjs";
import { a as safeRealpathSync, n as isPathInside, o as safeStatSync, r as openPluginRootFileSync } from "./path-safety-CTChYC4Z.mjs";
import { m as resolvePluginRuntimeExecutionArtifact, u as prefersBuiltPluginArtifacts } from "./bundled-dir-BKvdAqkP.mjs";
import { t as isPluginEnabledByDefaultForPlatform } from "./default-enablement-DLXVIwwO.mjs";
import { t as normalizePluginPolicyId } from "./plugin-policy-id-CkilMowp.mjs";
import { C as normalizePluginsConfigWithResolverCore, D as hasKind, O as kindsEqual, _ as resolveMemorySlotDecision, p as resolveEffectivePluginActivationState, u as normalizePluginsConfig } from "./config-state-B1JlHgba.mjs";
import { n as hashStableJson } from "./installed-plugin-index-hash-BfBbMPjv.mjs";
import { p as extractPluginInstallRecordsFromInstalledPluginIndex } from "./installed-plugin-index-DYqse_gE.mjs";
import { d as clearActiveDegradedPlugin, f as degradedPluginMatchesRoot, m as findActiveDegradedPlugin } from "./discovery-availability-DtlJ7XvT.mjs";
import { t as shouldRejectHardlinkedPluginFiles } from "./hardlink-policy-Kq1Lxk7_.mjs";
import { n as cloneConfigWithResolutionFacts } from "./resolution-facts-xaIKuREs.mjs";
import { n as compareOpenClawReleaseVersions } from "./npm-registry-spec-HKkAvl6N.mjs";
import { i as loadInstalledPluginIndexInstallRecordsSync } from "./installed-plugin-index-record-reader-B-7uGQZ9.mjs";
import { t as loadPluginManifestRegistryCore } from "./manifest-registry-CuWv8ibc.mjs";
import { t as resolvePluginControlPlaneFingerprint } from "./plugin-control-plane-context-BmY6xICT.mjs";
import { n as inheritPluginNativeAdmissions, r as nativeAdmissionStateFor } from "./plugin-native-admission-state-DSOJoYAS.mjs";
import { d as hasExplicitPluginIdScope, i as getCurrentPluginMetadataSnapshot, l as withPluginMetadataSnapshotScope, p as normalizePluginIdScope, u as createPluginIdScopeSet } from "./current-plugin-metadata-snapshot-H0TP3PFt.mjs";
import { a as getRuntimeConfigSnapshot, c as getRuntimeConfigSourceSnapshot, h as readRuntimeConfig, w as selectApplicableRuntimeConfig } from "./runtime-snapshot-WbwbY5b7.mjs";
import { l as tryNativeRequireModule } from "./native-module-require-CqM0GFP3.mjs";
import { m as resolvePluginMetadataSnapshotAsync, p as resolvePluginMetadataSnapshot } from "./plugin-metadata-snapshot-By9ySblt.mjs";
import { n as getProviderOwnerIndex, r as matchesDeclaredProviderOwner, t as buildDeclaredProviderOwnerIndex } from "./provider-owner-index-6ny9zfJF.mjs";
import { a as resolveMergedModelProviderConfig } from "./model-provider-config-Bbah_2ON.mjs";
import { i as resolveProviderIdForAuth } from "./provider-auth-aliases-CgGlzANu.mjs";
import { c as toSafeImportPath, i as preparePluginModule, o as installOpenClawPluginSdkNativeResolver, t as getCachedPluginModuleLoader } from "./plugin-module-loader-cache-DgNX_BTY.mjs";
import { a as getPluginInstanceOwner, l as getPluginValueInstance, r as getPluginInstance } from "./plugin-instance-scope-oezVdCr2.mjs";
import { c as resolvePluginRuntimeModulePathWithDiagnostics, o as preparePluginLoaderAliases } from "./sdk-alias-ByYgWl8I.mjs";
import { a as resolveManifestOwnerBasePolicyBlock, t as hasExplicitManifestOwnerTrust } from "./manifest-owner-policy-B8Brw4Zo.mjs";
import { t as resolveManifestActivationPluginIds } from "./activation-planner-lvis97qI.mjs";
import { a as bindPluginInstanceModuleLoader, d as clearPluginRuntimeArtifactResolutionMemo, f as resolvePluginRuntimeArtifact, n as PluginInstance, o as hasRetainedNativeEsmArtifact, s as resolveBundledPluginStateOperationCapture, t as getPluginSetupModuleLoader } from "./plugin-setup-module-D_W6TtnO.mjs";
import { C as markPluginRecordBorrowed, c as getPluginLoaderCacheState, g as isPluginRegistryActivated, h as isPluginRecordBorrowed, j as withPluginRegistryPreparationScope, m as isPluginRecordActive, x as isPluginRegistryRetired } from "./registry-lifecycle-CJjWnl-y.mjs";
import { E as withPluginRegistrationContext, f as getActivePluginRegistryWorkspaceDir, g as recordImportedPluginId } from "./runtime-ezCEpumg.mjs";
import { t as getPluginRuntimeGenerationRegistry } from "./generation-state-CbpjEoxA.mjs";
import { t as createEmptyPluginRegistry } from "./registry-empty-Cv4VTWYA.mjs";
import { o as hasCompletedPluginRuntimeRegistration, t as bindPluginRuntimeArtifactSelection } from "./plugin-runtime-artifact-binding-BHK81c8H.mjs";
import { n as validateJsonSchemaValue } from "./schema-validator-NvoOmaWr.mjs";
import { a as resolveProviderConfigApiOwnerHint, i as resolveModelCatalogScope, n as hasConfiguredModelProvider } from "./provider-config-owner-DM1kSvAm.mjs";
import { l as createUnavailableRuntime, s as runPluginRegistration } from "./setup-registry-CgyZCdrJ.mjs";
import { t as resolvePluginModuleExport } from "./module-export-DTZ89pa-.mjs";
import { a as resolveProviderRuntimeWorkspaceDir, r as matchesProviderPluginRef } from "./provider-registry-shared-C3T4TYXW.mjs";
import { a as isAuthModeAllowedForModel, r as resolveModelRuntimePolicy } from "./model-runtime-policy-Cfudvy7O.mjs";
import { n as resolveDefaultModelForAgent } from "./model-selection-config-Bvf5WqHo.mjs";
import { t as resolvePluginActivationSourceConfig } from "./activation-source-config-BX9rE6k7.mjs";
import { a as mergeChannelPlugins } from "./channel-configured-3z7rRlJy.mjs";
import { c as mintSecretSentinel } from "./sentinel-BfPjneyJ.mjs";
import { t as quoteCliArg } from "./quote-cli-arg-J7A9UE6m.mjs";
import { i as isOAuthRefreshFence } from "./oauth-refresh-marker-Bm1Qb0ET.mjs";
import { a as resolveTokenExpiryState, r as hasUsableOAuthCredential } from "./credential-state-BiAE74F8.mjs";
import { t as warnPluginSdkDeprecation } from "./sdk-deprecation-D5N9acnu.mjs";
import { c as findActiveDegradedSecretOwner, n as SecretSurfaceUnavailableError } from "./runtime-degraded-state-BSnwk5PQ.mjs";
import { l as getActiveSecretsRuntimeSnapshotRevisionState } from "./runtime-state-Dq_fFDZp.mjs";
import { i as BOARD_WIDGET_TOOL_MAX_LENGTH, n as BOARD_CRON_TRIGGER_PREFIX, r as BOARD_DATA_BINDING_ID_MAX_LENGTH } from "./board-BHvlhllK.mjs";
import { n as GITHUB_ACTIONS_BINDING_ID, r as GITHUB_ACTIONS_GRANT_PREFIX, t as GITHUB_ACTIONS_AUTHOR_GUIDANCE } from "./github-actions-capability-ByBXQPgn.mjs";
import { t as GATEWAY_SERVER_CAPS } from "./server-capabilities-BDosLJeN.mjs";
import { t as resolveAllowedModelRefCore } from "./model-selection-resolve-CyMfPqoi.mjs";
import { o as warn } from "./globals-CgepmiqE.mjs";
import { n as getPluginRegistryInspectionResources, t as PluginRegistryInspectionResources } from "./registry-inspection-resources-CDO3vUtM.mjs";
import { a as resolveAuthProfileOrder, f as listProfilesForProvider } from "./order-jOvee2J6.mjs";
import { a as SECRETREF_ENV_HEADER_MARKER_PREFIX, c as isKnownEnvApiKeyMarker, l as isNonSecretApiKeyMarker } from "./model-auth-markers-4YSUG71a.mjs";
import { C as createExternalAuthRuntime, r as createAuthProfileStoreRuntime } from "./store-Bh2lUvOT.mjs";
import { g as readProviderTextResponse, h as readProviderJsonResponse, s as createProviderHttpError } from "./provider-http-errors-Dtgw3x-5.mjs";
import { d as resolveProviderRequestHeaders, g as attachProviderAuthAuthority } from "./provider-request-config-CCij-nof.mjs";
import { r as fetchWithSsrFGuard } from "./fetch-guard-BLMw2n18.mjs";
import { a as resolveDebugProxySettings, r as createDebugProxyWebSocketAgent } from "./env-Dhl2_42G.mjs";
import { i as captureWsEventAsync, r as captureWsEvent } from "./runtime-D7l8z_nQ.mjs";
import { t as createRealtimeTranscriptionWebSocketSession } from "./websocket-session-BzP2IWOa.mjs";
import "./installed-plugin-index-records-MNCNSlg8.mjs";
import { a as pluginRuntimeLoaderLogger, n as buildPluginRuntimeLoadOptions, o as setPluginRuntimeLoadContext, r as getPluginRuntimeLoadContext, s as resolvePluginRegistrationConfigKey } from "./load-context-CwTU1iXB.mjs";
import { a as registryContainsRuntimePluginIds, c as resolveRuntimeSubagentMode, n as getLoadedRuntimePluginRegistry, o as resolveCompatibleRuntimePluginRegistry, s as resolvePluginLoadCacheContext, t as createRuntimePluginManifestLookup } from "./active-runtime-registry-Y-wDXpG6.mjs";
import { a as normalizeAgentToolResultMiddlewareRuntimeIds } from "./agent-tool-result-middleware-C6qDSxiL.mjs";
import { i as withProfile } from "./plugin-load-profile-DzyLBTel.mjs";
import { o as enqueueSystemEventFromSdk } from "./system-events-BAzDw63i.mjs";
import { n as formatPluginTrustDiagnostic } from "./plugin-trust-CpqJ5Gqw.mjs";
import { a as matchesScopedPluginOrDreamingSidecar, c as prepareRuntimePluginConfig, d as formatPluginFailureSummary, f as markPluginActivationDisabled, h as recordPluginError, i as detailPluginStartupTrace, l as resolveAuthorizedDreamingSidecar, m as recordPluginConfiguredUnavailable, n as activatePluginRegistry, o as maybeThrowOnPluginLoadError, p as recordBundleDiagnostics, r as createPluginCandidatesFromManifestRegistry, s as preparePluginLoadRecord, u as formatMissingPluginRegisterError } from "./loader-shared-CQKSwY3n.mjs";
import { n as inspectBundleMcpRuntimeSupport } from "./bundle-mcp-DKz8uq8U.mjs";
import { c as resolvePluginCapabilityCatalog, o as projectPluginContributions, s as capabilityCatalogFamilies, t as createPluginRegistry } from "./registry-ClBzy_np.mjs";
import { a as shouldLoadChannelPluginInSetupRuntime, i as resolveSetupChannelRegistration, n as loadBundledRuntimeChannelPlugin, r as resolveBundledRuntimeChannelRegistration, t as channelPluginIdBelongsToManifest } from "./loader-channel-setup-C8SFP0j7.mjs";
import { t as encodeStartupTraceSegment } from "./startup-trace-segment-uV5tTGWs.mjs";
import { t as resolveExternalPluginRuntimeDependencyRepairHint } from "./official-external-plugin-repair-hints-CLGaUsqQ.mjs";
import { i as resolveConfiguredRuntimePluginInstallCandidate } from "./official-runtime-plugins-m31mbS3Z.mjs";
import { n as readPluginStateMigrationReadiness, r as readPluginStateMigrationReadinessAsync } from "./plugin-state-migration-readiness-BQ5cdqig.mjs";
import { n as externalCliDiscoveryForProviderAuth } from "./external-cli-discovery-DZ419koV.mjs";
import { t as canResolveEnvSecretRefInReadOnlyPath } from "./secret-ref-readonly.internal-CHEvk9t0.mjs";
import { t as resolveEnvApiKey } from "./model-auth-env-kbpGo8fU.mjs";
import { M as resolveDirectProviderCredentialMode, T as ProviderAuthError, b as resolveUsableCustomProviderApiKey, c as profileTypeToAuthMode, r as hasSecretRefProviderApiKey, u as providerConfigMatchesRuntimeSnapshot, v as resolveProviderEntryApiKeyProfileReference, y as resolveRuntimeProviderConfigApiKeyAuth } from "./model-auth-provider-config-Bnc4upRS.mjs";
import { a as resolveDiscoverableProviderOwnerPluginIds, c as resolveExternalAuthProfileProviderPluginIds, f as resolveOwningPluginIdsForProviderRef, n as resolveActivatableProviderOwnerPluginIds, o as resolveDiscoveredProviderPluginIds, r as resolveBundledProviderCompatPluginIds, s as resolveEnabledProviderPluginIds, u as resolveOwningPluginIdsForModelRefs } from "./providers-B9AkUbSZ.mjs";
import { t as attachModelProviderLocalServiceReconciler } from "./provider-local-service-reconcile-DwxowFgX.mjs";
import { n as withActivatedPluginIds, t as resolveBundledCompatActivationInputs } from "./activation-context-CKtX_5VQ.mjs";
import fs from "node:fs";
import path from "node:path";
import { availableParallelism } from "node:os";
import { isMainThread } from "node:worker_threads";
import { isDeepStrictEqual } from "node:util";
import { setImmediate } from "node:timers/promises";
//#region src/plugins/loader-cache.ts
/** Registry reuse is off for explicit opt-outs and for raw env-substituted config loads. */
function isPluginRegistryCacheEnabled(e) {
	return e.cache !== false && e.resolveRawConfigEnvVars !== true;
}
/** Loads whose finished registry the cache hands to the next caller with the same key. */
function isCachedPluginRegistryLoad(e) {
	return !e.previousRegistry && !e.borrowRegistry && !e.moduleRecoveries && isPluginRegistryCacheEnabled(e);
}
function clearPluginRegistryLoadCache() {
	clearPluginRuntimeArtifactResolutionMemo();
	getPluginLoaderCacheState().clearCachedRegistries();
}
function resolvePluginRegistryLoadCacheKey(e = {}) {
	return resolvePluginLoadCacheContext(e).cacheKey;
}
function isPluginRegistryLoadInFlight(e = {}) {
	const t = resolvePluginLoadCacheContext(e);
	return t.cacheState.isLoadInFlight(t.cacheKey);
}
//#endregion
//#region src/plugins/runtime/runtime-config.ts
function createRuntimeConfig() {
	return {
		current: (e) => {
			const t = readRuntimeConfig();
			return e?.clone ? cloneConfigWithResolutionFacts(t) : t;
		},
		mutateConfigFile: async (e) => {
			const { mutateConfigFile: t } = await import("./mutate-BsBv3lKT.mjs");
			return await t(e);
		},
		replaceConfigFile: async (e) => {
			const { replaceConfigFile: t } = await import("./mutate-BsBv3lKT.mjs");
			return await t(e);
		}
	};
}
//#endregion
//#region src/plugins/runtime/runtime-llm-facade.ts
function createRuntimeLlmFacade(e) {
	const t = createLazyRuntimeMethod(() => import("./provider-local-service-BlNZ04lO.mjs"), (t) => t.createConfiguredProviderLocalServiceAcquirer(e));
	const n = createLazyRuntimeSurface(() => import("./runtime-llm.runtime.js"), (t) => t.createRuntimeLlm({
		getConfig: e,
		authority: { allowComplete: true }
	}));
	return {
		acquireLocalService: t,
		complete: createLazyRuntimeMethod(n, (e) => e.complete)
	};
}
//#endregion
//#region src/plugins/runtime/native-deps.ts
function formatNativeDependencyHint(e) {
	const t = e.manager ?? "pnpm";
	const n = e.rebuildCommand ?? `${t === "npm" || t === "yarn" ? t : "pnpm"} rebuild ${e.packageName}`;
	const r = [
		e.approveBuildsCommand ?? (t === "pnpm" ? `pnpm approve-builds (select ${e.packageName})` : void 0),
		n,
		e.downloadCommand
	].filter((e) => Boolean(e));
	if (r.length === 0) return `Install ${e.packageName} and rebuild its native module.`;
	return `Install ${e.packageName} and rebuild its native module (${r.join("; ")}).`;
}
//#endregion
//#region src/plugins/runtime/runtime-session-events.ts
const targets = resolveGlobalSingleton(Symbol.for("openclaw.pluginSessionEventTargets"), () => /* @__PURE__ */ new WeakMap());
const loadCaptureSessionEventTarget = createLazyRuntimeNamedExport(() => runInDetachedAsyncContext(() => import("./session-event-target-DI3FzTXv.mjs")), "captureSessionEventTargetForHost");
/** Capture the original destination before asynchronous plugin work. */
async function captureSessionEventTarget(e, t) {
	const n = getPluginRuntimeGatewayRequestScope()?.assertSystemOwnerCurrent;
	n?.();
	const r = await loadCaptureSessionEventTarget();
	n?.();
	const i = await r(e, t, { assertCurrent: n });
	n?.();
	const a = Object.freeze({});
	targets.set(a, i);
	return a;
}
/** Admit a bounded internal follow-up through the destination's normal session queue. */
function enqueueSessionEvent(e, t, n) {
	const r = getPluginRuntimeGatewayRequestScope()?.assertSystemOwnerCurrent;
	r?.();
	const i = t.expectedTarget ? targets.get(t.expectedTarget) : void 0;
	if (t.expectedTarget && !i) throw new Error("Session event target was not captured by this runtime; capture it before asynchronous work");
	return n(e, {
		agentId: t.agentId,
		sessionKey: t.sessionKey,
		source: "plugin",
		contextKey: t.contextKey,
		deliveryContext: t.deliveryContext,
		abortSignal: t.abortSignal,
		expectedTarget: i,
		createIfMissing: t.createIfMissing,
		...r ? { assertCurrent: r } : {}
	});
}
/** Keep synchronous receipt admission behind the host's existing native runtime loader. */
function createSessionEventEnqueuer(e) {
	return (t, n) => enqueueSessionEvent(t, n, e);
}
//#endregion
//#region src/plugins/runtime/runtime-system.ts
/** Creates the plugin runtime system facade with session-event and process helpers. */
function createRuntimeSystem(e) {
	return {
		captureSessionEventTarget,
		enqueueSessionEvent: createSessionEventEnqueuer(e),
		enqueueSystemEvent: enqueueSystemEventFromSdk,
		async runCommandWithTimeout(...e) {
			const t = getPluginRuntimeGatewayRequestScope()?.assertSystemOwnerCurrent;
			const { runCommandWithTimeout: n } = await import("./exec-Df6gUJ1h.mjs");
			t?.();
			return await n(...e);
		},
		formatNativeDependencyHint
	};
}
//#endregion
//#region src/plugins/runtime/runtime-base.ts
const COMMAND_NATIVE_SUBAGENTS_CAPABILITY = "command-native-subagents-v1";
const NATIVE_SUBAGENT_LIST_CAPABILITY = "native-subagent-list-v1";
/** Probe before registering a command that requests `runtimeCapabilities: ["scheduledTurns"]`. */
const COMMAND_SCHEDULED_TURNS_CAPABILITY = "command-scheduled-turns-v1";
/** Accepted command schedules survive a Gateway restart; plugins need not re-enroll them. */
const COMMAND_SCHEDULED_TURNS_RESTART_CAPABILITY = "command-scheduled-turns-restart-v1";
function unavailable(e) {
	return () => {
		throw new Error(`${e} is only available through the plugin runtime proxy.`);
	};
}
/** Host-owned facades survive later path-loaded runtime materialization unchanged. */
function createRuntimeBase(e) {
	let t;
	return {
		capabilities: Object.freeze([
			GATEWAY_SERVER_CAPS.SENDER_RESTRICTED_HIDDEN_HELPERS,
			COMMAND_NATIVE_SUBAGENTS_CAPABILITY,
			"requester-model-catalog-v1",
			"requester-model-family-v1",
			NATIVE_SUBAGENT_LIST_CAPABILITY,
			"native-subagent-profiles-v1",
			"native-subagent-blind-v1",
			COMMAND_SCHEDULED_TURNS_CAPABILITY,
			COMMAND_SCHEDULED_TURNS_RESTART_CAPABILITY,
			"channel-ingress-transform-v1"
		]),
		config: createRuntimeConfig(),
		llm: createRuntimeLlmFacade(readRuntimeConfig),
		state: {
			resolveStateDir,
			openBlobStore: unavailable("openBlobStore"),
			openKeyedStore: unavailable("openKeyedStore"),
			openKeyedStoreV2: unavailable("openKeyedStoreV2"),
			openSyncKeyedStore: unavailable("openSyncKeyedStore"),
			openChannelIngressQueue: unavailable("openChannelIngressQueue"),
			openChannelIngressDrain: unavailable("openChannelIngressDrain")
		},
		get system() {
			return t ??= createRuntimeSystem(e);
		}
	};
}
//#endregion
//#region src/plugins/loader-module-runtime.ts
const LAZY_RUNTIME_PROPERTIES = {
	version: true,
	decisions: true,
	gateway: true,
	config: true,
	agent: true,
	subagent: true,
	system: true,
	media: true,
	mediaUnderstanding: true,
	tts: true,
	channel: true,
	events: true,
	logging: true,
	state: true,
	modelAuth: true,
	imageGeneration: true,
	videoGeneration: true,
	musicGeneration: true,
	llm: true,
	hooks: true,
	nodes: true,
	sandbox: true,
	worktrees: true,
	webSearch: true,
	modelConfig: true,
	capabilities: true
};
function runPluginRegisterSyncInRegistry(e, t, n, r) {
	const i = getPluginValueInstance(t);
	const run = () => withPluginRegistrationContext(n, r, () => {
		const a = getPluginRegistryInspectionResources(n);
		const registerPlugin = () => runPluginRegistration(e, t, "reject", (e) => {
			a?.trackRegistration(e);
		});
		if (a) a.runRegistration(r, registerPlugin, i ? (e) => i.runCleanup(e) : void 0);
		else registerPlugin();
	}, {
		registerMemoryCapability: t.registerMemoryCapability,
		instance: i
	});
	if (i) {
		i.run(run);
		i.toolRegistrationComplete ||= t.registrationMode === "full" || t.registrationMode === "tool-discovery";
	} else run();
}
function createDeferredGatewaySubagentRuntime(e) {
	const t = {
		get native() {
			return e.subagent.native;
		},
		complete: (...t) => e.subagent.complete(...t),
		forkSession: (...t) => e.subagent.forkSession(...t),
		run: (...t) => e.subagent.run(...t),
		waitForRun: (...t) => e.subagent.waitForRun(...t),
		getSessionMessages: (...t) => e.subagent.getSessionMessages(...t),
		deleteSession: (...t) => e.subagent.deleteSession(...t)
	};
	bindGatewayContextResolver(t, getGatewayContextResolver(e));
	return t;
}
function createDeferredGatewayNodesRuntime(e) {
	return {
		list: (...t) => e.nodes.list(...t),
		invoke: (...t) => e.nodes.invoke(...t),
		openDuplex: (...t) => e.nodes.openDuplex(...t)
	};
}
function createPluginModuleLoader(e) {
	const t = getPluginCache();
	const n = {
		...e,
		expectedSourceDigests: e.expectedSourceDigests ? { ...e.expectedSourceDigests } : void 0
	};
	const createLoaderForModule = (e) => {
		if (n.installNativeSdkResolver !== false && n.tryNative !== false) installOpenClawPluginSdkNativeResolver({
			argv1: process.argv[1],
			moduleUrl: import.meta.url,
			pluginModulePath: e,
			devSourceRoot: n.devSourceRoot,
			pluginSdkResolution: n.pluginSdkResolution
		});
		return getCachedPluginModuleLoader({
			modulePath: e,
			importerUrl: import.meta.url,
			loaderFilename: n.loaderFilename ?? e,
			devSourceRoot: n.devSourceRoot,
			pluginSdkResolution: n.pluginSdkResolution,
			...n.tryNative !== void 0 ? { tryNative: n.tryNative } : {}
		});
	};
	const inspection = (e) => getPluginRegistryInspectionResources(e.registry) === void 0 ? {} : {
		inspectionSourceIdentity: e.immutableInstallIdentity,
		inspectionRetention: nativeAdmissionStateFor(t).inspectionNativeEsm
	};
	const binding = (e, t, r) => ({
		instance: r,
		origin: t.record.origin,
		source: e,
		rootDir: t.rootDir,
		standalone: t.standalone,
		expectedSourceDigest: n.expectedSourceDigests?.[t.record.id],
		...inspection(t),
		devSourceRoot: n.devSourceRoot,
		pluginSdkResolution: n.pluginSdkResolution,
		createHostModuleLoader: () => createLoaderForModule(e)
	});
	const load = (e, r) => withPluginCache(t, () => {
		if (!r) return createLoaderForModule(e)(toSafeImportPath(e));
		let t = getPluginInstance(r.record);
		if (!t) {
			t = new PluginInstance(r.record.id, r);
			bindPluginInstanceModuleLoader(binding(e, r, t));
		}
		const i = n.expectedSourceDigests?.[r.record.id];
		if (i !== void 0 && t.sourceDigest !== i) throw new Error(`Plugin ${r.record.id} captured source changed after installation`);
		return t.loadModule(e);
	});
	return Object.assign(load, { async prepare(e, r) {
		const retained = () => hasRetainedNativeEsmArtifact({
			origin: r.record.origin,
			source: e,
			...inspection(r),
			devSourceRoot: n.devSourceRoot,
			pluginSdkResolution: n.pluginSdkResolution,
			registry: r.registry
		});
		if (!isMainThread || getPluginInstance(r.record) || retained()) return;
		await withPluginCache(t, async () => {
			const n = r.record.origin === "bundled" ? resolveBundledPluginStateOperationCapture({
				rootDir: r.rootDir,
				source: e
			}) : void 0;
			if (r.record.origin === "bundled" && !n) return;
			const { preparePluginGenerationArtifact: i } = await import("./plugin-generation-worker-qqSxhu4X.mjs");
			const a = await i(n ?? {
				rootDir: r.rootDir,
				source: e,
				standalone: r.standalone
			});
			if (t.retirement || isPluginRegistryRetired(r.registry)) {
				await a.artifact.disposeAsync();
				throw new PluginInventoryRetiredError();
			}
			try {
				if (getPluginInstance(r.record) || retained()) {
					await a.artifact.disposeAsync();
					return;
				}
				const t = new PluginInstance(r.record.id, r);
				t.run(() => bindPluginInstanceModuleLoader({
					...binding(e, r, t),
					preparedArtifact: a
				}));
			} catch (e) {
				await a.artifact.disposeAsync();
				throw e;
			}
		});
	} });
}
function formatPluginRuntimeModuleResolutionError(e) {
	const { resolution: t } = e;
	const n = t.candidates.length > 0 ? t.candidates.join(", ") : "<none>";
	return [
		"Unable to resolve plugin runtime module",
		`loader=${t.modulePath ?? "<unresolved>"}`,
		`packageRoot=${t.packageRoot ?? "<none>"}`,
		`pluginSdkResolution=${e.pluginSdkResolution ?? "auto"}`,
		`candidates=${n}`,
		...t.error ? [`resolverError=${t.error}`] : []
	].join("; ");
}
/** Lazily materializes the broad plugin runtime only when registration reads it. */
function createLazyPluginRuntime(e) {
	const t = e.inspectionResources ? new WeakRef(getPluginCache()) : getPluginCache();
	const resolveRuntimeModule = () => {
		const t = resolvePluginRuntimeModulePathWithDiagnostics({
			devSourceRoot: e.devSourceRoot,
			pluginSdkResolution: e.pluginSdkResolution
		});
		if (!t.resolvedPath) throw new Error(formatPluginRuntimeModuleResolutionError({
			resolution: t,
			pluginSdkResolution: e.pluginSdkResolution
		}));
		const n = t.resolvedPath;
		return withProfile({ source: n }, "runtime-module", () => {
			const t = tryNativeRequireModule(n, { aliasMap: preparePluginLoaderAliases({
				modulePath: n,
				moduleUrl: import.meta.url,
				devSourceRoot: e.devSourceRoot,
				pluginSdkResolution: e.pluginSdkResolution
			}).resolveAlias });
			if (!t.ok) throw new Error(`Unable to load host plugin runtime natively: ${n}. Use a supported native TypeScript loader for a source host, or rebuild the host runtime.`);
			return t.moduleExport;
		});
	};
	let n;
	const r = createRuntimeBase((...e) => {
		if (!n) {
			const e = t instanceof WeakRef ? t.deref() : t;
			if (!e) throw new PluginInventoryRetiredError();
			const r = withPluginCache(e, resolveRuntimeModule);
			if (typeof r.enqueueSessionEventForHost !== "function") throw new Error("Plugin runtime module missing enqueueSessionEventForHost export");
			n = r.enqueueSessionEventForHost;
		}
		return n(...e);
	});
	let i = null;
	const resolveRuntime = () => {
		if (i) return i;
		const n = t instanceof WeakRef ? t.deref() : t;
		if (!n) throw new PluginInventoryRetiredError();
		i = withPluginCache(n, () => {
			const { createPluginRuntime: t } = resolveRuntimeModule();
			if (typeof t !== "function") throw new Error("Plugin runtime module missing createPluginRuntime export");
			return t(e.runtimeOptions, r);
		});
		return i;
	};
	const getRuntimeProperty = (t, ...n) => {
		if (!i) {
			if (t === "gateway" || t === "hooks" || t === "nodes" || t === "subagent" || t === "modelAuth" || t === "modelConfig") {
				const n = e.runtimeOptions?.[t];
				if (n !== void 0) return n;
			}
			if (t === "version") return VERSION;
			if (t === "capabilities" || t === "config" || t === "llm" || t === "state" || t === "system") return r[t];
		}
		return n.length === 0 ? Reflect.get(resolveRuntime(), t) : Reflect.get(resolveRuntime(), t, n[0]);
	};
	const resolveLazyRuntimeDescriptor = (e) => {
		if (i || !Object.hasOwn(LAZY_RUNTIME_PROPERTIES, e)) return Reflect.getOwnPropertyDescriptor(resolveRuntime(), e);
		const t = {
			configurable: true,
			enumerable: true,
			get() {
				return getRuntimeProperty(e);
			}
		};
		if (e !== "modelAuth" && e !== "modelConfig" && e !== "llm") t.set = (t) => {
			Reflect.set(resolveRuntime(), e, t);
		};
		return t;
	};
	let a = true;
	const o = new Proxy({}, {
		get: (e, t, n) => Object.hasOwn(e, t) ? Reflect.get(e, t, n) : getRuntimeProperty(t, n),
		set(e, t, n, r) {
			return Reflect.set(Object.hasOwn(e, t) ? e : resolveRuntime(), t, n, r);
		},
		has(e, t) {
			return Object.hasOwn(e, t) || Object.hasOwn(LAZY_RUNTIME_PROPERTIES, t) || Reflect.has(resolveRuntime(), t);
		},
		ownKeys(e) {
			return [...Object.keys(LAZY_RUNTIME_PROPERTIES), ...Reflect.ownKeys(e)];
		},
		getOwnPropertyDescriptor(e, t) {
			return Reflect.getOwnPropertyDescriptor(e, t) ?? (a ? void 0 : resolveLazyRuntimeDescriptor(t));
		},
		defineProperty(e, t, n) {
			return Reflect.defineProperty(a || Object.hasOwn(e, t) ? e : resolveRuntime(), t, n);
		},
		deleteProperty(e, t) {
			return Reflect.deleteProperty(Object.hasOwn(e, t) ? e : resolveRuntime(), t);
		},
		getPrototypeOf() {
			return Reflect.getPrototypeOf(resolveRuntime());
		}
	});
	prepareGatewayContextBindingOwner(o);
	a = false;
	const s = e.runtimeOptions ? Object.getOwnPropertyDescriptor(e.runtimeOptions, "subagent")?.value : void 0;
	if (s && typeof s === "object") bindGatewayContextResolver(o, getGatewayContextResolver(s));
	return o;
}
function kindIncludes(e, t) {
	return e === t || Array.isArray(e) && e.includes(t);
}
function formatBundledChannelWrongLoaderError(e) {
	if (kindIncludes(e, "bundled-channel-setup-entry")) return "bundled channel setup entry requires setup-runtime loader";
	if (kindIncludes(e, "bundled-channel-entry")) return "bundled channel entry requires setup-runtime loader";
	return null;
}
//#endregion
//#region src/plugins/loader-provenance.ts
const lastProvenanceWarning = resolveGlobalMap(Symbol.for("openclaw.pluginProvenanceWarnings"), "close-and-restart");
function createPathMatcher() {
	return {
		exact: /* @__PURE__ */ new Set(),
		dirs: []
	};
}
function addPathToMatcher(e, t, n = process.env) {
	const r = t.trim();
	if (!r) return;
	const i = resolveUserPath(r, n);
	if (!i) return;
	const a = safeRealpathSync(i) ?? i;
	if (e.exact.has(a) || e.dirs.includes(a)) return;
	if (safeStatSync(a)?.isDirectory()) {
		e.dirs.push(a);
		return;
	}
	e.exact.add(a);
}
function matchesPathMatcher(e, t) {
	return e.exact.has(t) || e.dirs.some((e) => isPathInside(e, t));
}
function formatPluginInspectCommand(e) {
	return `openclaw plugins inspect ${quoteCliArg(e)}`;
}
/** Builds provenance matchers from configured load paths and install records. */
function buildProvenanceIndex(e) {
	const t = createPathMatcher();
	for (const n of e.normalizedLoadPaths) addPathToMatcher(t, n, e.env);
	const n = /* @__PURE__ */ new Map();
	const r = e.installRecords ?? loadInstalledPluginIndexInstallRecordsSync({ env: e.env });
	for (const [t, i] of Object.entries(r)) {
		const r = {
			record: i,
			trackedWithoutPaths: false,
			matcher: createPathMatcher()
		};
		const a = normalizeTrimmedStringList([i.installPath, i.sourcePath]);
		if (a.length === 0) r.trackedWithoutPaths = true;
		else for (const t of a) addPathToMatcher(r.matcher, t, e.env);
		n.set(t, r);
	}
	return {
		loadPathMatcher: t,
		installRules: n
	};
}
function isTrackedByProvenance(e) {
	const t = resolveUserPath(e.source, e.env);
	const n = safeRealpathSync(t) ?? t;
	const r = e.index.installRules.get(e.pluginId);
	if (r) {
		if (r.trackedWithoutPaths) return true;
		if (matchesPathMatcher(r.matcher, n)) return true;
	}
	return matchesPathMatcher(e.index.loadPathMatcher, n);
}
/** Warns when an open plugin allowlist may auto-load non-bundled plugins. */
function warnWhenAllowlistIsOpen(e) {
	if (!e.emitWarning || !e.pluginsEnabled) return;
	const t = e.discoverablePlugins.filter((t) => (t.origin === "workspace" || t.origin === "global") && !e.explicitlyEnabledPluginIds?.has(t.id));
	if (t.length === 0) return;
	const n = new Set(e.discoverablePlugins.map((e) => e.id));
	const r = e.allow.length > 0;
	if (e.allow.some((e) => n.has(e))) return;
	if (e.warningCache.hasOpenAllowlistWarning(e.warningCacheKey)) return;
	const i = t.slice(0, 6).map((e) => `${e.id} (${e.source})`).join(", ");
	const a = t.length > 6;
	const o = a ? ` (+${t.length - 6} more)` : "";
	const s = t.map((e) => `'${formatPluginInspectCommand(e.id)}'`).join(", ");
	const c = a ? "Run 'openclaw plugins list --enabled --verbose' to enumerate every discovered plugin id, inspect trusted ids with 'openclaw plugins inspect <id>', and add the ones you trust to plugins.allow in openclaw.json." : `To trust them explicitly, set plugins.allow in openclaw.json (e.g. "plugins": { "allow": [${t.map((e) => JSON.stringify(e.id)).join(", ")}] }). Run 'openclaw plugins list --enabled --verbose' or ${s} to confirm plugin ids.`;
	e.warningCache.recordOpenAllowlistWarning(e.warningCacheKey);
	if (!r) {
		e.logger.warn(`[plugins] plugins.allow is empty; discovered non-bundled plugins may auto-load: ${i}${o}. ${c}`);
		return;
	}
	const l = e.allow.filter((e) => !n.has(e));
	const u = l.slice(0, 6).map((e) => `"${e}"`).join(", ");
	const d = l.length > 6 ? ` (+${l.length - 6} more)` : "";
	e.logger.warn(`[plugins] plugins.allow entries ${u}${d} do not match any discovered plugin ids; discovered non-bundled plugins: ${i}${o}. Use the plugin id (not a channel id or npm package name).`);
}
/** Reports untracked plugins and unverified install provenance without refusing runtime access. */
function warnAboutUntrackedLoadedPlugins(e) {
	const t = new Set(e.allowlist);
	for (const n of e.registry.plugins) {
		if (n.status !== "loaded" || n.origin === "bundled") continue;
		const r = n.trust?.reason;
		const i = r === "provenance-missing" || r === "provenance-invalid" || r === "owner-ambiguous" || r === "install-path-mismatch" || r === "record-missing" && n.origin === "global";
		if (!i && t.has(n.id)) continue;
		const a = e.installOwnerByPluginId.get(n.id);
		if (!i && a && isTrackedByProvenance({
			pluginId: a,
			source: n.source,
			index: e.provenance,
			env: e.env
		})) continue;
		const o = n.trust ? ` ${formatPluginTrustDiagnostic(n.trust)}.` : "";
		const s = `OpenClaw can't verify where this plugin came from. Review it with '${formatPluginInspectCommand(n.id)}'. Adding it to plugins.allow lets it load, but does not make it trusted. If it's an official plugin, reinstall it from its official npm package or its official ClawHub listing to enable trusted features.${o}`;
		if (!e.registry.diagnostics.some((e) => e.pluginId === n.id && e.source === n.source && e.message === s)) e.registry.diagnostics.push({
			level: "warn",
			pluginId: n.id,
			source: n.source,
			message: s
		});
		if (e.emitWarning) {
			const t = hashStableJson([
				n.source,
				n.trust,
				a ? e.provenance.installRules.get(a)?.record : void 0
			]);
			if (lastProvenanceWarning.get(n.id) !== t) {
				lastProvenanceWarning.set(n.id, t);
				e.logger.warn(`[plugins] ${n.id}: ${s} (${n.source})`);
			}
		}
	}
}
//#endregion
//#region src/boards/board-host-capability-ids.ts
const CORE_BOARD_DATA_BINDING_IDS = [
	"sessions.list",
	"usage.status",
	"usage.cost",
	"cron.list",
	"cron.status",
	"agents.list",
	"health"
];
const CORE_BOARD_ACTION_VERB_IDS = ["cron.trigger"];
/** Widget grants share one string namespace across reads and actions. */
const CORE_BOARD_HOST_CAPABILITY_IDS = [
	...CORE_BOARD_DATA_BINDING_IDS,
	GITHUB_ACTIONS_BINDING_ID,
	...CORE_BOARD_ACTION_VERB_IDS
];
//#endregion
//#region src/plugins/dashboard-capabilities.ts
var PluginDashboardDeclarationError = class extends Error {
	constructor(e) {
		super(e);
		this.name = "PluginDashboardDeclarationError";
	}
};
function fail(e, t) {
	throw new PluginDashboardDeclarationError(`invalid dashboard declaration for plugin ${JSON.stringify(e)}: ${t}`);
}
function buildCapabilityId(e) {
	const t = `${e.pluginId.replaceAll("%", "%25").replaceAll(".", "%2E")}.${e.localId}`;
	if (t.length > e.maxLength) return fail(e.pluginId, `capability id ${JSON.stringify(t)} exceeds ${e.maxLength} characters`);
	return t;
}
function requireOwnedMethod(e) {
	const t = e.registry.gatewayMethodDescriptors.find((t) => t.name === e.method);
	if (t?.owner.kind !== "plugin" || t.owner.pluginId !== e.pluginId) return fail(e.pluginId, `method ${JSON.stringify(e.method)} must be registered by the declaring plugin`);
	if (t.scope !== e.expectedScope) return fail(e.pluginId, `method ${JSON.stringify(e.method)} must use ${e.expectedScope}, got ${t.scope}`);
	const n = e.registry.gatewayHandlers[e.method];
	if (!n) return fail(e.pluginId, `method ${JSON.stringify(e.method)} is missing its registered handler`);
	return n;
}
/** Validates and publishes one plugin's manifest-declared dashboard capabilities atomically. */
function registerPluginDashboardCapabilities(e) {
	const t = e.record.dashboard;
	if (!t) return;
	const n = [];
	const r = [];
	const i = /* @__PURE__ */ new Set();
	const claimCapabilityId = (t) => {
		if (i.has(t) || e.registry.dashboardDataBindings.has(t) || e.registry.dashboardActionVerbs.has(t)) fail(e.record.id, `duplicate capability id ${JSON.stringify(t)}`);
		if (CORE_BOARD_HOST_CAPABILITY_IDS.includes(t) || t.startsWith("github.actions.runs:") || t.startsWith("cron.trigger:")) fail(e.record.id, `capability id ${JSON.stringify(t)} is reserved by core`);
		i.add(t);
	};
	for (const r of t.dataBindings ?? []) {
		const t = buildCapabilityId({
			pluginId: e.record.id,
			localId: r.id,
			maxLength: 64
		});
		claimCapabilityId(t);
		n.push({
			...r,
			pluginId: e.record.id,
			capabilityId: t,
			handler: requireOwnedMethod({
				pluginId: e.record.id,
				method: r.method,
				expectedScope: "operator.read",
				registry: e.registry
			})
		});
	}
	for (const n of t.actionVerbs ?? []) {
		const t = buildCapabilityId({
			pluginId: e.record.id,
			localId: n.id,
			maxLength: 269
		});
		claimCapabilityId(t);
		const i = requireOwnedMethod({
			pluginId: e.record.id,
			method: n.method,
			expectedScope: "operator.write",
			registry: e.registry
		});
		if (n.paramShape) try {
			validateJsonSchemaValue({
				schema: n.paramShape,
				cacheKey: `dashboard-action:${e.record.id}:${n.id}`,
				value: void 0
			});
		} catch (n) {
			fail(e.record.id, `action ${JSON.stringify(t)} has an invalid paramShape: ${String(n)}`);
		}
		r.push({
			...n,
			pluginId: e.record.id,
			capabilityId: t,
			handler: i
		});
	}
	for (const t of n) e.registry.dashboardDataBindings.set(t.capabilityId, t);
	for (const t of r) e.registry.dashboardActionVerbs.set(t.capabilityId, t);
}
/** Describe only validated, active registrations, with whole entries under one prompt budget. */
function describeDashboardCapabilities(e) {
	let t = `${GITHUB_ACTIONS_AUTHOR_GUIDANCE} Other core reads (grant the binding ID): ${CORE_BOARD_DATA_BINDING_IDS.join(", ")}.`;
	const n = [...[...e?.dashboardDataBindings.values() ?? []].map((e) => ({
		id: e.capabilityId,
		text: `read ${e.capabilityId}: ${e.description}`
	})), ...[...e?.dashboardActionVerbs.values() ?? []].map((e) => ({
		id: e.capabilityId,
		text: `action ${e.capabilityId}: ${e.description}${e.paramShape ? `; params ${JSON.stringify(e.paramShape)}` : ""}`
	}))].toSorted((e, t) => e.id < t.id ? -1 : e.id > t.id ? 1 : 0);
	let r = 0;
	for (const e of n) if (t.length + e.text.length + 2 > 950) r += 1;
	else t += `\n${e.text}`;
	if (r) t += `\n${r} plugin capabilities omitted; see the active plugins' dashboard documentation.`;
	return t;
}
//#endregion
//#region src/plugins/loader-channel-runtime.ts
/**
* Handles the setup-entry channel path.
* Returns true when the candidate is complete (loaded, disabled, or failed).
*/
function loadSetupRuntimeChannelCandidate(e) {
	const { manifestRecord: t, record: n, registrationPlan: r, runtimeCandidateEntry: i, registryBuilder: a } = e;
	if (!r.loadSetupEntry || !t.setupSource) return false;
	const recordSetupFailure = (t, r, i) => {
		a.rollbackPluginGlobalSideEffects(n.id, n);
		recordPluginError({
			logger: e.logger,
			registry: a.registry,
			record: n,
			seenIds: e.seenIds,
			phase: r,
			error: t,
			logPrefix: `[plugins] ${n.id} ${i} from ${n.source}: `,
			diagnosticMessagePrefix: `${i}: `,
			diagnosticCode: "channel-setup-failure"
		});
		return true;
	};
	const o = resolveSetupChannelRegistration(e.mod);
	if ("loadError" in o) return recordSetupFailure(o.loadError, "load", "failed to load setup entry");
	if (!o.plugin) return false;
	if (!channelPluginIdBelongsToManifest({
		channelId: o.plugin.id,
		pluginId: n.id,
		manifestChannels: t.channels
	})) {
		e.pushPluginLoadError(`plugin id mismatch (config uses "${n.id}", setup export uses "${o.plugin.id}")`);
		return true;
	}
	const s = a.createApi(n, {
		config: e.cfg,
		pluginConfig: {},
		hookPolicy: e.entry?.hooks,
		registrationMode: r.mode
	});
	const c = getPluginInstance(n);
	const applyChannelRuntime = (e) => {
		if (!e) return;
		if (!c) {
			e(s.runtime);
			return;
		}
		c.run(() => e(s.runtime));
	};
	let l = o.plugin;
	try {
		applyChannelRuntime(o.setChannelRuntime);
	} catch (e) {
		return recordSetupFailure(e, "load", "failed to apply setup channel runtime");
	}
	const u = r.loadSetupRuntimeEntry && o.usesBundledSetupContract ? resolvePluginRuntimeExecutionArtifact(i) : void 0;
	if (u && u.source !== e.safeSource) {
		const { source: t, rootDir: r } = u;
		const i = openPluginRootFileSync({
			filePath: t,
			rootPath: r,
			rejectHardlinks: e.rejectHardlinks
		});
		if (!i.ok) {
			e.pushPluginLoadError(describeRootFileOpenFailure({
				failure: i,
				subject: "plugin entry path",
				boundaryLabel: "plugin root",
				filePath: t
			}));
			return true;
		}
		const a = i.path;
		fs.closeSync(i.fd);
		let s;
		try {
			s = withProfile({
				pluginId: n.id,
				source: a
			}, "load-setup-runtime-entry", () => e.loadPluginModule(a));
		} catch (e) {
			return recordSetupFailure(e, "load", "failed to load setup-runtime entry");
		}
		const c = resolveBundledRuntimeChannelRegistration(s);
		if (c.id && c.id !== n.id) {
			e.pushPluginLoadError(`plugin id mismatch (config uses "${n.id}", runtime entry uses "${c.id}")`);
			return true;
		}
		if (c.setChannelRuntime) try {
			if (c.setChannelRuntime !== o.setChannelRuntime) applyChannelRuntime(c.setChannelRuntime);
		} catch (e) {
			return recordSetupFailure(e, "load", "failed to apply setup-runtime channel runtime");
		}
		const d = loadBundledRuntimeChannelPlugin({ registration: c });
		if ("loadError" in d) return recordSetupFailure(d.loadError, "load", "failed to load setup-runtime channel entry");
		if (d.plugin) {
			if (d.plugin.id && d.plugin.id !== n.id) {
				e.pushPluginLoadError(`plugin id mismatch (config uses "${n.id}", runtime export uses "${d.plugin.id}")`);
				return true;
			}
			l = mergeChannelPlugins(d.plugin, o.plugin, "merge");
		}
	}
	if (r.mode === "setup-runtime" && o.registerSetupRuntime) try {
		runPluginRegisterSyncInRegistry((e) => o.registerSetupRuntime?.(e), s, a.registry, n.id);
	} catch (e) {
		return recordSetupFailure(e, "register", "failed to register setup-runtime channel side effects");
	}
	try {
		s.registerChannel(l);
	} catch (e) {
		return recordSetupFailure(e, "load", "failed to register setup channel");
	}
	a.registry.plugins.push(n);
	e.seenIds.set(n.id, n.origin);
	return true;
}
//#endregion
//#region src/plugins/loader-registration-plan.ts
function createRegistrationPlan(e) {
	const t = e === "setup-only" || e === "setup-runtime";
	return {
		/** Public compatibility label passed to plugin register(api). */
		mode: e,
		/** Load a setup entry instead of the normal runtime entry. */
		loadSetupEntry: t,
		/** Setup flow also needs the runtime channel entry for runtime setters/plugin shape. */
		loadSetupRuntimeEntry: e === "setup-runtime",
		/** Apply runtime capability policy such as memory-slot selection. */
		runRuntimeCapabilityPolicy: !t,
		/** Register metadata that only belongs to live activation. */
		runFullActivationOnlyRegistrations: e === "full"
	};
}
/** Converts loader intent into explicit entrypoint and activation behavior. */
function resolvePluginRegistrationPlan(e) {
	if (e.cliMetadata) return e.enableStateEnabled ? createRegistrationPlan("cli-metadata") : null;
	if (e.canLoadScopedSetupOnlyChannelPlugin) return createRegistrationPlan("setup-only");
	if (!e.enableStateEnabled) return null;
	if (e.toolDiscovery) return createRegistrationPlan("tool-discovery");
	if (e.shouldLoadModules && !e.validateOnly && shouldLoadChannelPluginInSetupRuntime({
		manifestChannels: e.manifestRecord.channels,
		setupSource: e.manifestRecord.setupSource,
		cfg: e.cfg,
		env: e.env,
		channelPluginLoadIntent: e.channelPluginLoadIntent
	})) return createRegistrationPlan("setup-runtime");
	return createRegistrationPlan(e.runtimeSideEffects ? "full" : "discovery");
}
//#endregion
//#region src/plugins/loader-runtime-candidate.ts
function* loadRuntimePluginCandidate(e) {
	const { candidate: t, manifestRecord: n, context: r, state: i } = e;
	const a = e.options.mode === "cli-metadata";
	const { registry: o } = e.registryBuilder;
	const s = preparePluginLoadRecord({
		candidate: t,
		manifestRecord: n,
		context: r,
		onlyPluginIdSet: e.onlyPluginIdSet,
		dreamingSidecar: e.dreamingSidecar,
		registry: o,
		seenIds: i.seenIds
	});
	if (!s) return;
	const { pluginId: c, isDreamingSidecar: l, activationState: u, enableState: d, entry: f, record: p } = s;
	const finish = () => {
		o.plugins.push(p);
		i.seenIds.set(c, t.origin);
	};
	const disableMemoryPlugin = (e) => {
		p.enabled = false;
		markPluginActivationDisabled(p, e);
		finish();
	};
	const m = e.options.moduleRecoveries?.get(c);
	if (d.enabled && e.pendingStateMigration && !m) {
		yield;
		const t = recordPluginConfiguredUnavailable({
			registry: o,
			record: p,
			seenIds: i.seenIds,
			pendingStateMigration: e.pendingStateMigration,
			env: r.env
		});
		e.logger.warn(t);
		return;
	}
	const h = m ? t.rootDir : resolveRealpathOrAbsolute(t.rootDir);
	const g = findActiveDegradedPlugin(c);
	const _ = g && degradedPluginMatchesRoot(g, h) ? g : void 0;
	const v = d.enabled && Boolean(g) && !_;
	if (d.enabled && _) {
		yield;
		recordPluginConfiguredUnavailable({
			registry: o,
			record: p,
			seenIds: i.seenIds,
			degradedPlugin: _
		});
		return;
	}
	const y = resolveManifestOwnerBasePolicyBlock({
		plugin: { id: c },
		normalizedConfig: r.normalized
	}) === null && (hasExplicitManifestOwnerTrust({
		plugin: { id: c },
		normalizedConfig: r.normalized
	}) || t.origin === "workspace" && u.source === "auto");
	const b = !a && r.includeSetupOnlyChannelPlugins && !e.validateOnly && Boolean(e.onlyPluginIdSet) && n.channels.length > 0 && t.origin !== "bundled" && !y;
	const pushPluginLoadError = (t) => {
		e.registryBuilder.rollbackPluginGlobalSideEffects(p.id, p);
		recordPluginError({
			registry: o,
			seenIds: i.seenIds,
			record: p,
			phase: "validation",
			error: t
		});
	};
	const x = resolveExternalPluginRuntimeDependencyRepairHint({
		origin: t.origin,
		pluginId: c,
		packageName: t.packageName,
		packageBuild: t.packageManifest?.build
	});
	if (b) {
		yield;
		markPluginActivationDisabled(p, u.reason ?? d.reason ?? "local plugin requires explicit trust for setup");
		o.plugins.push(p);
		return;
	}
	const S = r.includeSetupOnlyChannelPlugins && !e.validateOnly && Boolean(e.onlyPluginIdSet) && n.channels.length > 0 && (!d.enabled || r.forceSetupOnlyChannelPlugins) && (t.origin !== "workspace" || d.enabled);
	const C = resolvePluginRegistrationPlan({
		canLoadScopedSetupOnlyChannelPlugin: S,
		enableStateEnabled: d.enabled,
		shouldLoadModules: r.shouldLoadModules,
		validateOnly: e.validateOnly,
		runtimeSideEffects: r.runtimeSideEffects,
		manifestRecord: n,
		cfg: r.cfg,
		env: r.env,
		channelPluginLoadIntent: r.channelPluginLoadIntent,
		toolDiscovery: e.options.toolDiscovery === true,
		cliMetadata: a
	});
	if (!C) {
		yield;
		markPluginActivationDisabled(p, d.reason);
		finish();
		return;
	}
	if (!d.enabled) markPluginActivationDisabled(p, d.reason);
	const w = resolveConfiguredRuntimePluginInstallCandidate(c);
	const T = resolveCompatibilityHostVersion(r.env);
	const E = w?.minimumCompatibleVersion;
	const D = n.packageVersion;
	if (d.enabled && t.origin !== "bundled" && w?.versionBoundToOpenClaw && E && n.packageName === w.npmSpec && D && (compareOpenClawReleaseVersions(D, E) ?? 0) < 0) {
		yield;
		p.activated = false;
		pushPluginLoadError(`Official runtime plugin ${c} ${D} is incompatible with OpenClaw ${T} (minimum compatible plugin version is ${E}); it is unavailable until repaired. Run \`openclaw update repair\` or \`openclaw plugins update ${c}\`, then restart the Gateway. For a linked plugin, update the linked source or remove its load-path override before retrying.`);
		return;
	}
	if (p.format === "bundle") {
		yield;
		if (a) o.plugins.push(p);
		else recordBundleDiagnostics({
			record: p,
			registry: o,
			inspectMcp: inspectBundleMcpRuntimeSupport
		});
		i.seenIds.set(c, t.origin);
		return;
	}
	const O = r.normalized.slots.memory;
	const memoryDecisionFor = (e) => resolveMemorySlotDecision({
		id: p.id,
		kind: e,
		slot: O,
		selectedId: i.selectedMemoryPluginId
	});
	if (C.runRuntimeCapabilityPolicy && t.origin === "bundled" && hasKind(n.kind, "memory") && !l) {
		yield;
		const e = memoryDecisionFor(n.kind);
		if (!e.enabled) {
			disableMemoryPlugin(e.reason);
			return;
		}
	}
	if (!n.configSchema) {
		yield;
		pushPluginLoadError("missing config schema");
		return;
	}
	if (!r.shouldLoadModules && C.runRuntimeCapabilityPolicy) {
		yield;
		const e = memoryDecisionFor(p.kind);
		if (!e.enabled && !l) {
			disableMemoryPlugin(e.reason);
			return;
		}
		if (e.selected && hasKind(p.kind, "memory")) {
			i.selectedMemoryPluginId = p.id;
			i.memorySlotMatched = true;
			p.memorySlotSelected = true;
		}
	}
	const k = performance.now();
	const A = prepareRuntimePluginConfig(e);
	const j = performance.now() - k;
	if (!A.ok) {
		yield;
		e.logger.error(`[plugins] ${p.id} invalid config: ${A.error.join(", ")}`);
		pushPluginLoadError(`invalid config: ${A.error.join(", ")}`);
		return;
	}
	if (!r.shouldLoadModules) {
		yield;
		finish();
		return;
	}
	const M = performance.now();
	const N = {
		pluginId: c,
		rootDir: h,
		origin: t.origin,
		preferBuiltPluginArtifacts: prefersBuiltPluginArtifacts(r.artifactPreference, t.origin),
		sourcePreferred: n.sourcePreferred,
		packageManifest: t.packageManifest,
		registry: o
	};
	const P = e.options.capabilityCatalog;
	if (P && n.capabilityCatalogSource !== void 0) {
		yield;
		try {
			if (!n.capabilityCatalogSource) throw new Error("entry must resolve inside the selected plugin root");
			const i = resolvePluginRuntimeArtifact({
				...N,
				entryKind: "capability-catalog",
				source: n.capabilityCatalogSource
			});
			const { source: a, modulePath: o } = preparePluginModule({
				modulePath: i.source,
				boundaryRoot: i.rootDir,
				boundaryLabel: "plugin root",
				rejectHardlinks: shouldRejectHardlinkedPluginFiles({
					origin: t.origin,
					rootDir: t.rootDir,
					env: r.env
				}),
				surfaceLabel: `${c} capabilityCatalogEntry`
			});
			if (a.capabilityCatalog?.context !== P.context) {
				const e = getPluginSetupModuleLoader(n, o, i.rootDir);
				a.capabilityCatalog = {
					context: P.context,
					value: e.initialize(() => resolvePluginCapabilityCatalog(e(o), P.context))
				};
			}
			const s = a.capabilityCatalog.value;
			if (Object.hasOwn(s, P.family)) {
				const t = s.speechProviders ?? [];
				for (const n of t.keys()) e.registryBuilder.registerSpeechProvider(p, t[n]);
				const n = s.realtimeTranscriptionProviders ?? [];
				for (const t of n.keys()) e.registryBuilder.registerRealtimeTranscriptionProvider(p, n[t]);
				const r = s.realtimeVoiceProviders ?? [];
				for (const t of r.keys()) e.registryBuilder.registerRealtimeVoiceProvider(p, r[t]);
				p.imported = false;
				p.capabilityCatalog = capabilityCatalogFamilies.filter((e) => Object.hasOwn(s, e));
				finish();
				return;
			}
		} catch (t) {
			e.registryBuilder.rollbackPluginGlobalSideEffects(p.id, p);
			throw new Error(`Plugin ${c} capabilityCatalogEntry failed: ${formatErrorMessage(t)}. Repair the declared entry in ${n.manifestPath}.`, { cause: t });
		}
	}
	const F = m?.runtimeEntry ?? (a ? {
		source: t.source,
		rootDir: h
	} : resolvePluginRuntimeArtifact({
		...N,
		entryKind: "runtime",
		source: t.source
	}));
	let I = C.loadSetupEntry && (m ? m.setupEntry : n.setupSource && resolvePluginRuntimeArtifact({
		...N,
		entryKind: "setup",
		source: n.setupSource
	})) || F;
	if (a) {
		const e = resolveCliMetadataEntrySource(t.rootDir, t.source);
		if (!e && t.origin === "bundled") {
			yield;
			finish();
			return;
		}
		I = {
			source: e ?? t.source,
			rootDir: h
		};
	}
	const L = m ? I : resolvePluginRuntimeExecutionArtifact(I);
	const R = bindPluginRuntimeArtifactSelection(p, {
		...N,
		source: t.source,
		runtimeEntry: m ? F : resolvePluginRuntimeExecutionArtifact(F),
		setupEntry: C.loadSetupEntry ? L : void 0
	});
	const z = L.source;
	const B = L.rootDir;
	const V = shouldRejectHardlinkedPluginFiles({
		origin: t.origin,
		rootDir: t.rootDir,
		env: r.env
	});
	let H = z;
	if (!m) {
		const e = openPluginRootFileSync({
			filePath: z,
			rootPath: B,
			rejectHardlinks: V
		});
		if (!e.ok) {
			yield;
			pushPluginLoadError(describeRootFileOpenFailure({
				failure: e,
				subject: "plugin entry path",
				boundaryLabel: "plugin root",
				filePath: z
			}));
			return;
		}
		H = e.path;
		fs.closeSync(e.fd);
	}
	let U = 0;
	let W = 0;
	let G;
	let K = false;
	const q = performance.now();
	const J = q - M;
	const traceRun = (t) => e.options.startupTrace?.run ? e.options.startupTrace.run(`plugins.gateway-load.plugin.${encodeStartupTraceSegment(p.id)}`, t) : t();
	try {
		const s = {
			record: p,
			rootDir: B,
			registry: o,
			standalone: n.manifestPath === t.source,
			immutableInstallIdentity: resolveImmutableInstallIdentity(t.origin, resolvePluginCandidateInstallOwner(t), r.installRecords)
		};
		try {
			if (!m) yield async () => {
				const t = performance.now();
				try {
					await traceRun(() => e.loadPluginModule.prepare(H, s));
				} finally {
					W = performance.now() - t;
				}
			};
		} finally {
			if (!a) recordImportedPluginId(p.id);
			i.pluginLoadAttemptCount++;
			e.logger.debug?.(`[plugins] loading ${p.id} from ${H}`);
		}
		const loadPluginModule = (t) => {
			if (m) {
				let e = getPluginInstance(p);
				if (!e) {
					e = new PluginInstance(p.id, {
						record: p,
						registry: o
					});
					m.module.bind(e);
				}
				return e.loadModule(t);
			}
			return e.loadPluginModule(t, s);
		};
		const u = withProfile({
			pluginId: p.id,
			source: H
		}, C.mode, () => traceRun(() => loadPluginModule(H)));
		U = performance.now() - q;
		const d = getPluginInstance(p);
		const loadSetupCandidate = () => loadSetupRuntimeChannelCandidate({
			mod: u,
			manifestRecord: n,
			record: p,
			registrationPlan: C,
			runtimeCandidateEntry: F,
			safeSource: H,
			rejectHardlinks: V,
			loadPluginModule,
			registryBuilder: e.registryBuilder,
			cfg: r.cfg,
			entry: f,
			seenIds: i.seenIds,
			logger: e.logger,
			pushPluginLoadError
		});
		if (d ? d.run(loadSetupCandidate) : loadSetupCandidate()) return;
		const { definition: h, register: g } = resolvePluginModuleExport(u);
		if (h?.id && h.id !== p.id) {
			pushPluginLoadError(`plugin id mismatch (config uses "${p.id}", export uses "${h.id}")`);
			return;
		}
		p.name = h?.name ?? p.name;
		p.description = h?.description ?? p.description;
		p.version = h?.version ?? p.version;
		const _ = p.kind;
		const y = h?.kind;
		if (_ && y && !kindsEqual(_, y)) o.diagnostics.push({
			level: "warn",
			pluginId: p.id,
			source: p.source,
			message: `plugin kind mismatch (manifest uses "${String(_)}", export uses "${String(y)}")`
		});
		p.kind = h?.kind ?? p.kind;
		if (hasKind(p.kind, "memory") && O === p.id) i.memorySlotMatched = true;
		if (C.runRuntimeCapabilityPolicy && !l) {
			const t = memoryDecisionFor(p.kind);
			if (!t.enabled) {
				e.registryBuilder.rollbackPluginGlobalSideEffects(p.id, p);
				disableMemoryPlugin(t.reason);
				return;
			}
			if (t.selected && hasKind(p.kind, "memory")) {
				i.selectedMemoryPluginId = p.id;
				p.memorySlotSelected = true;
			}
		}
		if (e.validateOnly) {
			finish();
			return;
		}
		if (typeof g !== "function") {
			const t = formatBundledChannelWrongLoaderError(p.kind);
			if (t) {
				e.logger.error(`[plugins] ${p.id} ${t}; check that plugin is loaded via bundled channel discovery, not legacy plugin loader`);
				pushPluginLoadError(t);
			} else {
				e.logger.error(`[plugins] ${p.id} missing register/activate export`);
				pushPluginLoadError(formatMissingPluginRegisterError(u, r.env));
			}
			return;
		}
		G = performance.now();
		const registerPlugin = () => {
			const t = d?.wrap(h) ?? h;
			if (!a) for (const n of t?.nodeHostCommands ?? []) e.registryBuilder.registerNodeHostCommand(p, n);
			if (C.runFullActivationOnlyRegistrations) {
				if (t?.reload) e.registryBuilder.registerReload(p, t.reload);
				for (const n of t?.securityAuditCollectors ?? []) e.registryBuilder.registerSecurityAuditCollector(p, n);
			}
			const n = e.registryBuilder.createApi(p, {
				config: r.cfg,
				pluginConfig: A.value,
				hookPolicy: f?.hooks,
				registrationMode: C.mode
			});
			return withProfile({
				pluginId: p.id,
				source: p.source
			}, `${C.mode}:register`, () => runPluginRegisterSyncInRegistry(g, n, o, p.id));
		};
		if (d) traceRun(() => d.run(registerPlugin));
		else traceRun(registerPlugin);
		if (!a && C.runRuntimeCapabilityPolicy) {
			registerPluginDashboardCapabilities({
				record: p,
				registry: o
			});
			R.runtimeRegistrationComplete = true;
		}
		finish();
		if (v) clearActiveDegradedPlugin(c);
	} catch (t) {
		const n = G === void 0 ? "load" : "register";
		let r = t;
		try {
			e.options.prepareRegistrationFailureCleanup?.(o, p);
		} catch (e) {
			r = new AggregateError([t, e], `${formatErrorMessage(t)}; registration cleanup preparation failed: ${formatErrorMessage(e)}`, { cause: t });
		}
		e.registryBuilder.rollbackPluginGlobalSideEffects(p.id, p);
		recordPluginError({
			logger: e.logger,
			registry: o,
			record: p,
			seenIds: i.seenIds,
			phase: n,
			error: r,
			logPrefix: `[plugins] ${p.id} failed during ${n} from ${p.source}: `,
			diagnosticMessagePrefix: `plugin failed during ${n}: `,
			missingDependencyHint: x,
			...t instanceof PluginDashboardDeclarationError ? { diagnosticCode: "dashboard-declaration-invalid" } : {}
		});
		K = true;
	} finally {
		const t = performance.now() - q;
		const n = G === void 0 ? void 0 : performance.now() - G;
		detailPluginStartupTrace(e.options.startupTrace, p.id, [
			["configValidationMs", j],
			["artifactPreparationMs", J],
			["loadMs", U || t],
			["modulePreparationMs", W],
			["loadFailedCount", K && G === void 0 ? 1 : 0],
			...n === void 0 ? [] : [
				["registerMs", n],
				["loadAndRegisterMs", t],
				["registerFailedCount", K ? 1 : 0]
			]
		]);
	}
}
function resolveCliMetadataEntrySource(e, t) {
	for (const n of /* @__PURE__ */ new Set([e, path.dirname(t)])) for (const e of [
		".ts",
		".js",
		".mjs",
		".cjs"
	]) {
		const t = path.join(n, `cli-metadata${e}`);
		if (fs.existsSync(t)) return t;
	}
	return null;
}
//#endregion
//#region src/plugins/loader-runtime-preparation.ts
function* finishPluginCandidate(e, t, n) {
	let r = t;
	while (!r.done) {
		const t = r.value;
		try {
			yield t && (() => n(t));
			r = n(() => e.next());
		} catch (t) {
			r = n(() => e.throw(t));
		}
	}
}
function* finishPluginPreparations(e, t) {
	if (!e.length) return;
	const n = e.splice(0);
	let r;
	yield async () => {
		r = await Promise.allSettled(n.map(({ prepare: e }) => Promise.resolve().then(() => t(e))));
	};
	let i = 0;
	try {
		if (getPluginCache().retirement) throw new PluginInventoryRetiredError();
		for (const { steps: e } of n) {
			const n = r?.[i];
			i++;
			yield* finishPluginCandidate(e, t(() => n?.status === "rejected" ? e.throw(n.reason) : e.next()), t);
			yield;
			if (getPluginCache().retirement) throw new PluginInventoryRetiredError();
		}
	} catch (e) {
		const t = [e];
		for (const { steps: e } of n.slice(i)) try {
			e.throw(new PluginInventoryRetiredError());
		} catch (e) {
			t.push(e);
		}
		if (t.length > 1) throw new AggregateError(t, "Plugin preparation and rollback failed", { cause: e });
		throw e;
	}
}
//#endregion
//#region src/plugins/loader-runtime-core.ts
const registryInputs = /* @__PURE__ */ new WeakMap();
/** Captured JSON inputs ignore object key order, but preserve array order and values. */
function samePluginLoadInput(e, t) {
	return e === t || e !== void 0 && t !== void 0 && isDeepStrictEqual(JSON.parse(e), JSON.parse(t));
}
/**
* Same-mode predecessors transfer to the candidate at publication. A live side-effect
* runtime lends active records to a non-activating load and keeps their custody.
*/
function resolvePluginRecordRetention({ previousRegistry: e, borrowRegistry: t }, n, r) {
	const i = e?.plugins.find((e) => e.id === n);
	const a = e && registryInputs.get(e)?.get(n);
	if (e && i && a && !isPluginRecordBorrowed(e, i) && r.signature !== void 0 && !r.replaced && samePluginLoadInput(a.signature, r.signature)) return {
		registry: e,
		record: i,
		input: a
	};
	const o = t?.plugins.find((e) => e.id === n);
	const s = t && registryInputs.get(t)?.get(n);
	return t && o && s?.borrowSignature !== void 0 && isPluginRecordActive(t, o) && samePluginLoadInput(s.borrowSignature, r.borrowSignature) ? {
		registry: t,
		record: o,
		input: s
	} : void 0;
}
function createCapabilityCatalogContextResolver(e) {
	return () => e;
}
/** The loader records actual registration inputs with their selected inventory. */
function bindRuntimeLoadContext(e, t, n, r, i, a) {
	setPluginRuntimeLoadContext(e, {
		rawConfig: t.config ?? {},
		config: n.cfg,
		activationSourceConfig: n.activationSourceConfig,
		autoEnabledReasons: n.autoEnabledReasons,
		workspaceDir: t.workspaceDir,
		env: n.env,
		logger: i,
		manifestRegistry: r,
		normalizePluginId: t.normalizePluginId,
		selectedContextEngine: a,
		metadataSnapshot: n.metadataSnapshot?.manifestRegistry === r ? n.metadataSnapshot : void 0,
		installRecords: n.installRecords,
		preferBuiltPluginArtifacts: t.preferBuiltPluginArtifacts,
		expectedSourceDigests: t.expectedSourceDigests
	}, n.registrationConfigKey);
}
function loadOpenClawPluginsCore(...e) {
	const t = loadOpenClawPluginsSteps(...e);
	let n = t.next();
	while (!n.done) n = t.next();
	return n.value;
}
/** One registration sequence, consumed synchronously by CLI/SDK callers or incrementally by hosts. */
function* loadOpenClawPluginsSteps(e, t, n, r, i) {
	if (getPluginCache().retirement) throw new PluginInventoryRetiredError();
	const a = normalizePluginIdScope(e.onlyPluginIds);
	const o = createPluginIdScopeSet(a);
	if (o && o.size === 0) {
		const t = createEmptyPluginRegistry();
		r?.attach(t);
		if (e.metadataSnapshot) bindRuntimeLoadContext(t, e, resolvePluginLoadCacheContext(e), e.manifestRegistry ?? e.metadataSnapshot.manifestRegistry, e.logger ?? createSubsystemLogger("plugins"));
		if (e.mode !== "cli-metadata" && e.activate !== false) {
			const n = resolveRuntimeSubagentMode(e.runtimeOptions);
			activatePluginRegistry(t, `empty-plugin-scope::${n}::${e.workspaceDir ?? ""}`, n, e.workspaceDir, void 0, i);
		}
		return t;
	}
	const s = resolvePluginLoadCacheContext(e);
	const c = e.logger ?? createSubsystemLogger("plugins");
	const l = e.mode === "validate";
	const u = createPluginIdScopeSet(s.onlyPluginIds);
	const d = isCachedPluginRegistryLoad(e);
	if (d) {
		const t = s.cacheState.get(s.cacheKey);
		if (t) {
			maybeThrowOnPluginLoadError(t, e.throwOnLoadError);
			if (s.shouldActivate) activatePluginRegistry(t, s.cacheKey, s.runtimeSubagentMode, e.workspaceDir, void 0, i);
			return t;
		}
	}
	s.cacheState.beginLoad(s.cacheKey);
	let f;
	try {
		let a = 1;
		let o;
		yield async () => {
			o = await readPluginStateMigrationReadinessAsync({ env: s.env });
			a = Math.min(4, availableParallelism());
		};
		o ??= readPluginStateMigrationReadiness({ env: s.env });
		const p = new Map(o.map((e) => [normalizePluginPolicyId(e.pluginId), e]));
		const m = createPluginModuleLoader({
			devSourceRoot: s.devSourceRoot,
			pluginSdkResolution: e.pluginSdkResolution,
			expectedSourceDigests: e.expectedSourceDigests,
			...n?.moduleLoader
		});
		const h = s.borrowedGatewayRuntime ? createDeferredGatewaySubagentRuntime(s.borrowedGatewayRuntime) : void 0;
		const g = s.borrowedGatewayRuntime ? createDeferredGatewayNodesRuntime(s.borrowedGatewayRuntime) : void 0;
		const _ = e.mode === "cli-metadata" ? createUnavailableRuntime("cli-metadata") : n?.runtime ? n.runtime : createLazyPluginRuntime({
			inspectionResources: r,
			devSourceRoot: s.devSourceRoot,
			pluginSdkResolution: e.pluginSdkResolution,
			runtimeOptions: {
				...e.runtimeOptions,
				modelAuth: e.runtimeOptions?.modelAuth ?? { ...t.modelAuth },
				modelConfig: e.runtimeOptions?.modelConfig ?? { ...t.modelConfig },
				subagent: e.runtimeOptions?.subagent ?? h,
				nodes: e.runtimeOptions?.nodes ?? g
			}
		});
		const v = e.capabilityCatalogContext ?? e.capabilityCatalog?.context ?? t.capabilityCatalogContext;
		f = createPluginRegistry({
			logger: c,
			runtime: _,
			resolveCapabilityCatalogContext: createCapabilityCatalogContextResolver(v),
			allowProcessHomeSessionCatalogs: e.allowProcessHomeSessionCatalogs ?? true,
			coreGatewayHandlers: e.coreGatewayHandlers,
			...e.coreGatewayMethodNames !== void 0 && { coreGatewayMethodNames: e.coreGatewayMethodNames },
			...e.hostServices !== void 0 && { hostServices: e.hostServices },
			activateGlobalSideEffects: s.runtimeSideEffects
		});
		const y = f;
		const { registry: b } = y;
		r?.attach(b);
		const x = e.manifestRegistry ?? (e.discovery === void 0 ? s.metadataSnapshot?.manifestRegistry : void 0);
		const S = x ? {
			candidates: createPluginCandidatesFromManifestRegistry(x),
			diagnostics: []
		} : e.discovery ?? discoverOpenClawPlugins({
			workspaceDir: e.workspaceDir,
			extraPaths: s.normalized.loadPaths,
			env: s.env,
			installRecords: s.installRecords
		});
		const C = x ?? loadPluginManifestRegistryCore({
			config: s.cfg,
			workspaceDir: e.workspaceDir,
			env: s.env,
			candidates: S.candidates,
			diagnostics: S.diagnostics,
			installRecords: Object.keys(s.installRecords).length > 0 ? s.installRecords : void 0
		});
		const w = s.selectContextEngineOwner(C.plugins);
		b.diagnostics.push(...C.diagnostics);
		warnWhenAllowlistIsOpen({
			emitWarning: s.shouldActivate,
			logger: c,
			pluginsEnabled: s.normalized.enabled,
			allow: s.normalized.allow,
			warningCacheKey: s.cacheKey,
			warningCache: s.cacheState,
			explicitlyEnabledPluginIds: new Set(Object.entries(s.normalized.entries).filter(([, e]) => e.enabled === true).map(([e]) => e)),
			discoverablePlugins: C.plugins.filter((e) => !u || u.has(e.id))
		});
		const T = buildProvenanceIndex({
			normalizedLoadPaths: s.normalized.loadPaths,
			env: s.env,
			installRecords: s.installRecords
		});
		const E = new Map(C.plugins.map((e) => [e.source, e]));
		const D = S.candidates.flatMap((e) => {
			const t = E.get(e.source);
			return t ? [{
				candidate: e,
				manifest: t
			}] : [];
		});
		const O = Object.freeze({
			requestKey: s.cacheKey,
			resolvedKey: s.resolveManifestCacheKey(C)
		});
		bindRuntimeLoadContext(b, e, s, C, c, w);
		const k = /* @__PURE__ */ new Set([...e.replacePluginIds ?? [], ...e.moduleRecoveries?.keys() ?? []]);
		const A = s.normalized.slots.memory;
		const j = resolveAuthorizedDreamingSidecar({
			cfg: s.cfg,
			normalized: s.normalized,
			activationSource: s.activationSource,
			manifestRegistry: C,
			memorySlot: A
		});
		const M = /* @__PURE__ */ new Map();
		const N = /* @__PURE__ */ new Map();
		for (const { candidate: t, manifest: n } of D) {
			if (M.has(n.id) || !matchesScopedPluginOrDreamingSidecar({
				onlyPluginIdSet: u,
				pluginId: n.id,
				sidecar: j
			})) continue;
			const r = resolveEffectivePluginActivationState({
				id: n.id,
				origin: t.origin,
				channelIds: n.channels,
				config: s.normalized,
				rootConfig: s.cfg,
				enabledByDefault: isPluginEnabledByDefaultForPlatform(n),
				activationSource: s.activationSource
			});
			const i = resolvePluginCandidateInstallOwner(t);
			const { config: a, ...o } = s.normalized.entries[normalizePluginPolicyId(n.id)] ?? {};
			const c = { input: JSON.stringify(a) };
			const d = findActiveDegradedPlugin(n.id);
			const { controlUi: f, schemaCacheKey: m, ...h } = n;
			const g = [
				t.source,
				t.origin,
				[i, i ? s.installRecords[i] : void 0],
				{
					...h,
					controlUi: f !== void 0
				},
				r,
				w,
				p.get(normalizePluginPolicyId(n.id)),
				o,
				d && degradedPluginMatchesRoot(d, t.rootDir) ? d : void 0,
				hasKind(n.kind, "memory") ? A : void 0,
				n.id === j?.engineId ? j : void 0,
				s.channelPluginLoadIntent,
				s.includeSetupOnlyChannelPlugins,
				s.forceSetupOnlyChannelPlugins,
				l
			];
			const _ = !l && e.mode !== "cli-metadata" && e.toolDiscovery !== true;
			const v = _ && s.runtimeSideEffects;
			const y = _ && !s.runtimeSideEffects && e.borrowRegistry !== void 0;
			let x;
			let S;
			try {
				x = JSON.stringify([
					...g,
					s.artifactPreference,
					s.runtimeSideEffects,
					e.toolDiscovery === true,
					e.mode
				]);
				S = v || y ? JSON.stringify(g) : void 0;
			} catch (e) {
				if (!(e instanceof RangeError) || t.origin === "bundled" || prepareRuntimePluginConfig({
					candidate: t,
					manifestRecord: n,
					context: s,
					preparedConfig: c
				}).ok) throw e;
			}
			M.set(n.id, {
				source: t.source,
				signature: x,
				...v ? { borrowSignature: S } : {},
				config: c
			});
			const C = resolvePluginRecordRetention(e, n.id, {
				signature: x,
				borrowSignature: y ? S : void 0,
				replaced: k.has(n.id)
			});
			if (C) {
				if (C.input.config.validation) prepareRuntimePluginConfig({
					candidate: t,
					manifestRecord: n,
					context: s,
					preparedConfig: c
				});
				if (samePluginLoadInput(C.input.config.input, c.input)) {
					N.set(n.id, C.record);
					if (C.registry === e.borrowRegistry) markPluginRecordBorrowed(b, C.record);
					projectPluginContributions(C.registry, C.record, b);
				}
			}
		}
		for (const t of [e.previousRegistry, e.borrowRegistry]) b.diagnostics.push(...t?.diagnostics.filter((e) => {
			const n = e.pluginId && N.get(e.pluginId);
			return n && t.plugins.includes(n);
		}) ?? []);
		const P = /* @__PURE__ */ new Map();
		for (const { manifest: e } of D) if (!P.has(e.id)) P.set(e.id, e);
		for (const t of P.values()) {
			if (N.has(t.id) || e.mode === "cli-metadata") continue;
			const n = resolveEffectivePluginActivationState({
				id: t.id,
				origin: t.origin,
				channelIds: t.channels,
				config: s.normalized,
				rootConfig: s.cfg,
				enabledByDefault: isPluginEnabledByDefaultForPlatform(t),
				activationSource: s.activationSource
			});
			const r = normalizeAgentToolResultMiddlewareRuntimeIds(t.contracts?.agentToolResultMiddleware);
			if (r.length > 0 && (t.origin === "bundled" || n.enabled && n.explicitlyEnabled)) b.agentToolResultMiddlewareOwners.push({
				pluginId: t.id,
				runtimes: r,
				manifest: t
			});
		}
		const F = {
			seenIds: /* @__PURE__ */ new Map(),
			selectedMemoryPluginId: null,
			memorySlotMatched: false,
			pluginLoadAttemptCount: 0
		};
		const I = performance.now();
		const runCandidate = (t) => e.previousRegistry ? withPluginRegistryPreparationScope(b, t) : t();
		const L = [];
		for (const { candidate: t, manifest: n } of D) {
			if (N.has(n.id) || t.origin === "bundled" || e.moduleRecoveries?.has(n.id) || F.seenIds.has(n.id) || L.some(({ id: e }) => e === n.id)) yield* finishPluginPreparations(L, runCandidate);
			const r = N.get(n.id);
			if (r && !F.seenIds.has(n.id)) {
				b.plugins.push(r);
				F.seenIds.set(r.id, r.origin);
				if (r.memorySlotSelected) {
					F.selectedMemoryPluginId = r.id;
					F.memorySlotMatched = true;
				}
				continue;
			}
			const i = F.pluginLoadAttemptCount;
			const o = M.get(n.id);
			const d = loadRuntimePluginCandidate({
				candidate: t,
				manifestRecord: n,
				context: s,
				options: e,
				onlyPluginIdSet: u,
				dreamingSidecar: j,
				validateOnly: l,
				registryBuilder: y,
				loadPluginModule: m,
				logger: c,
				state: F,
				preparedConfig: o?.source === t.source ? o.config : { input: void 0 },
				pendingStateMigration: p.get(normalizePluginPolicyId(n.id))
			});
			const f = runCandidate(() => d.next());
			if (!f.done && f.value) {
				L.push({
					id: n.id,
					steps: d,
					prepare: f.value
				});
				if (L.length === a) yield* finishPluginPreparations(L, runCandidate);
				continue;
			}
			yield* finishPluginPreparations(L, runCandidate);
			yield* finishPluginCandidate(d, f, runCandidate);
			if (F.pluginLoadAttemptCount !== i) {
				yield;
				if (getPluginCache().retirement) throw new PluginInventoryRetiredError();
			}
		}
		yield* finishPluginPreparations(L, runCandidate);
		const R = performance.now() - I;
		if (F.pluginLoadAttemptCount > 0) c.debug?.(`[plugins] loaded ${b.plugins.length} plugin(s) (${F.pluginLoadAttemptCount} attempted) in ${R.toFixed(1)}ms`);
		if (e.mode !== "cli-metadata" && !u && typeof A === "string" && !F.memorySlotMatched) b.diagnostics.push({
			level: "warn",
			message: `memory slot plugin not found or not marked as memory: ${A}`
		});
		if (e.mode !== "cli-metadata") warnAboutUntrackedLoadedPlugins({
			registry: b,
			provenance: T,
			allowlist: s.normalized.allow,
			emitWarning: s.shouldActivate,
			logger: c,
			env: s.env,
			installOwnerByPluginId: new Map(D.flatMap(({ candidate: e, manifest: t }) => {
				const n = resolvePluginCandidateInstallOwner(e);
				return t.id && n ? [[t.id, n]] : [];
			}))
		});
		maybeThrowOnPluginLoadError(b, e.throwOnLoadError, N, e.previousRegistry, k);
		if (s.shouldActivate && e.mode !== "validate") {
			const e = b.plugins.filter((e) => e.failedAt != null);
			if (e.length > 0) c.warn(`[plugins] ${e.length} plugin(s) failed to initialize (${formatPluginFailureSummary(e)}). Run 'openclaw plugins inspect <id> --runtime --json' for runtime diagnostics and 'openclaw plugins list' for registry state. After fixing plugin code or load paths, run 'openclaw plugins reload <id>' to retry.`);
		}
		getPluginRuntimeLoadContextState(b).loaderCacheIdentity = O;
		if (s.shouldActivate) activatePluginRegistry(b, s.cacheKey, s.runtimeSubagentMode, e.workspaceDir, void 0, i);
		if (d && !b.diagnostics.some((e) => e.code === "plugin-state-migration")) {
			s.cacheState.set(s.cacheKey, b);
			if (O.resolvedKey !== s.cacheKey) s.cacheState.set(O.resolvedKey, b);
		}
		registryInputs.set(b, M);
		return b;
	} catch (t) {
		if (f && !isPluginRegistryActivated(f.registry)) {
			for (const t of f.registry.plugins.toReversed()) if (!e.previousRegistry?.plugins.includes(t) && !e.borrowRegistry?.plugins.includes(t)) f.rollbackPluginGlobalSideEffects(t.id, t);
		}
		throw t;
	} finally {
		s.cacheState.finishLoad(s.cacheKey);
	}
}
//#endregion
//#region src/agents/auth-profiles/read-only-availability.ts
/** Pure, non-resolving credential availability checks shared by status and route selection. */
/** Store revisions do not advance when a token or failure window expires. */
function resolveAuthStoreReadOnlyValidUntil(e, t) {
	return Math.min(...[...Object.values(e.profiles).map((e) => e.type === "token" ? e.expires : void 0), ...Object.values(e.usageStats ?? {}).flatMap((e) => [
		e.blockedUntil,
		e.cooldownUntil,
		e.disabledUntil
	])].filter((e) => e !== void 0 && e > t));
}
function hasMalformedSecretInputSyntax(e) {
	if (typeof e !== "string") return false;
	const t = e.trim();
	return t.startsWith("secretref-env:") || t.startsWith("__env__:") || t.startsWith("$");
}
function resolveSecretRefReadOnlyAvailability(e, t, n) {
	if (!isSecretRef(e) || !isValidSecretRef(e)) return false;
	if (e.source === "env") {
		if (!canResolveEnvSecretRefInReadOnlyPath({
			cfg: t,
			provider: e.provider,
			id: e.id
		})) return false;
		return hasNonEmptyString(n[e.id]) ? true : void 0;
	}
	const r = t.secrets?.providers?.[e.provider];
	if (r?.source !== e.source && !isBuiltInDefaultSecretProviderRef(t, e)) return false;
	if (e.source === "file" && r?.source === "file" && r.mode === "singleValue" !== (e.id === "value")) return false;
}
function resolveSecretInputReadOnlyAvailability(e, t, n, r) {
	const i = parseSecretRef(t, n.secrets?.defaults) ?? parseSecretRef(e, n.secrets?.defaults);
	if (i) return resolveSecretRefReadOnlyAvailability(i, n, r);
	if (!hasNonEmptyString(e) || hasMalformedSecretInputSyntax(e)) return false;
	return isKnownEnvApiKeyMarker(e) ? hasNonEmptyString(r[e.trim()]) : isNonSecretApiKeyMarker(e) ? void 0 : true;
}
function resolveStoredCredentialReadOnlyAvailability(e) {
	const { credential: t, cfg: n, env: r } = e;
	const i = e.now ?? Date.now();
	if (t.type === "api_key") return resolveSecretInputReadOnlyAvailability(t.key, t.keyRef, n, r);
	if (t.type === "token") {
		const e = resolveTokenExpiryState(t.expires, i);
		if (e === "expired" || e === "invalid_expires") return false;
		return resolveSecretInputReadOnlyAvailability(t.token, t.tokenRef, n, r);
	}
	if (hasUsableOAuthCredential(t, { now: i })) return true;
	if (isOAuthRefreshFence(t)) return false;
	if (hasNonEmptyString(t.refresh)) return e.canRefreshOAuth ? true : void 0;
	return t.oauthRef && !hasNonEmptyString(t.access) ? void 0 : false;
}
//#endregion
//#region src/agents/model-auth-runtime-config.ts
/**
* Runtime-config-backed provider auth that does not require plugin activation.
*/
/** Reads a runtime-resolved credential for a SecretRef-backed provider entry. */
function resolveManagedSecretRefRuntimeProviderAuth(e) {
	const t = getRuntimeConfigSnapshot();
	const n = getRuntimeConfigSourceSnapshot();
	const r = n ?? void 0;
	if (!t || !hasSecretRefProviderApiKey(r, e.provider)) return;
	if (!(providerConfigMatchesRuntimeSnapshot({
		inputConfig: e.cfg,
		runtimeConfig: t,
		provider: e.provider
	}) || selectApplicableRuntimeConfig({
		inputConfig: e.cfg,
		runtimeConfig: t,
		runtimeSourceConfig: n
	}) === t)) return;
	const i = resolveRuntimeProviderConfigApiKeyAuth({
		cfg: t,
		sourceConfig: r,
		provider: e.provider
	});
	if (!i?.apiKey) return;
	return {
		...i,
		apiKey: e.secretSentinels ? mintSecretSentinel(i.apiKey, { label: `model-auth:${e.provider}` }) : i.apiKey
	};
}
function assertRuntimeProviderSecretOwnerAvailable(e) {
	const t = normalizeProviderId(e.provider);
	const n = findActiveDegradedSecretOwner("provider", t);
	if (!n) return;
	const r = getRuntimeConfigSnapshot();
	const i = getRuntimeConfigSourceSnapshot();
	if (!e.cfg || e.cfg === r || e.cfg === i || providerConfigMatchesRuntimeSnapshot({
		inputConfig: e.cfg,
		runtimeConfig: r,
		provider: t
	})) throw new SecretSurfaceUnavailableError(n);
}
//#endregion
//#region src/plugins/provider-auth-scope.ts
function pluginProviderAuthUnavailable(e, t) {
	return new ProviderAuthError("missing-provider-auth", e, `Plugin-owned auth for provider "${e}" is unavailable: ${t}.`);
}
/** Static ownership survives absent/disabled executables in the selected metadata generation. */
function resolveProviderAuthScope(e) {
	const t = e.pluginMetadataSnapshot ?? getCurrentPluginMetadataSnapshot({
		config: e.config,
		env: e.env,
		workspaceDir: e.workspaceDir,
		allowScopedSnapshot: true,
		allowWorkspaceScopedSnapshot: true
	});
	const n = getPluginRuntimeGenerationRegistry() ?? getPluginRuntimeGatewayRequestScope()?.pluginRegistry;
	const r = n ? getPluginRuntimeLoadContext(n) : void 0;
	const i = t?.manifestRegistry ?? r?.manifestRegistry;
	if (!i) return "agent";
	const a = getProviderOwnerIndex(i).authScopes.get(normalizeProviderId(e.provider));
	if (a === "conflict") throw pluginProviderAuthUnavailable(e.provider, "conflicting static credential owners");
	return a ?? "agent";
}
/** Plugin credentials are live instance-owned facts, never prepared/restored bearer cache entries. */
function resolvePluginOwnedProviderAuthWith(e, t) {
	if (resolveProviderAuthScope(e) !== "plugin") throw pluginProviderAuthUnavailable(e.provider, "static metadata does not grant plugin credential scope");
	if (e.profileId !== void 0 || e.preferredProfile !== void 0) throw pluginProviderAuthUnavailable(e.provider, "agent profile pins cannot select plugin credentials");
	const n = t({
		...e,
		applyAutoEnable: false
	});
	const r = n?.resolveSyntheticAuth;
	const i = r ? getPluginValueInstance(r) : void 0;
	const a = i?.owner;
	const o = a?.registry;
	const s = o?.providers.find((e) => e.pluginId === n?.pluginId && e.provider.id === n?.id && e.provider.resolveSyntheticAuth === r);
	if (!n || n.authScope !== "plugin" || !r || !i || !s) throw pluginProviderAuthUnavailable(e.provider, "selected live resolveSyntheticAuth owner is missing");
	const c = s.provider;
	const l = getActiveSecretsRuntimeSnapshotRevisionState();
	const assertCurrent = () => {
		if (!i.acceptingCalls || i.owner !== a || a?.revoked || i.lifecycle.signal.aborted || i.pluginId !== n.pluginId || !a?.record.enabled || a.record.status !== "loaded" || a.registry !== o || getActiveSecretsRuntimeSnapshotRevisionState() !== l || !o?.providers.includes(s) || s.provider !== c || c.authScope !== "plugin" || c.resolveSyntheticAuth !== r) throw pluginProviderAuthUnavailable(e.provider, "credential owner was retired or replaced");
	};
	assertCurrent();
	const u = i.run(() => {
		const t = r({
			config: e.config,
			provider: e.provider,
			providerConfig: void 0
		});
		if (!t) return;
		const { apiKey: n, source: i, mode: a, expiresAt: o, nativeAuth: s } = t;
		return {
			apiKey: n,
			source: i,
			mode: a,
			...o !== void 0 ? { expiresAt: o } : {},
			...s ? { nativeAuth: {
				runtime: s.runtime,
				mode: s.mode
			} } : {}
		};
	});
	assertCurrent();
	if (!u?.apiKey?.trim()) throw pluginProviderAuthUnavailable(e.provider, "live credential or no-auth evidence is missing");
	return attachProviderAuthAuthority(u, assertCurrent);
}
//#endregion
//#region src/plugins/provider-auth-availability-core.ts
function prepareProviderAuthProfileResolution(e) {
	return {
		agentDir: e.agentDir?.trim() || resolveDefaultAgentDir(e.cfg ?? {}),
		externalCli: e.includeExternalCliAuth ? externalCliDiscoveryForProviderAuth({
			cfg: e.cfg,
			provider: e.provider,
			allowKeychainPrompt: e.allowKeychainPrompt
		}) : void 0,
		select: (t) => ({
			store: t,
			profileIds: resolveAuthProfileOrder({
				cfg: e.cfg,
				store: t,
				provider: e.provider,
				includePendingOAuthRefresh: e.includePendingOAuthRefresh
			})
		})
	};
}
function createProviderAuthAvailability(e, t) {
	const { ensureAuthProfileStore: n, ensureAuthProfileStoreAsync: r, loadAuthProfileStoreWithoutExternalProfilesAsync: i, loadAuthProfileStoreForRuntimeAsync: a, findPersistedAuthProfileCredential: o, findPersistedAuthProfileCredentialAsync: s, loadAuthProfileStoreForSecretsRuntime: c, loadAuthProfileStoreWithoutExternalProfiles: l } = e;
	/**
	* Checks whether a provider has usable config/env auth or matching local auth profiles.
	*/
	function isProviderApiKeyConfiguredFromStore(e, r) {
		if (resolveProviderAuthScope({
			provider: e.provider,
			config: e.cfg
		}) === "plugin") try {
			if (!t) return false;
			const n = resolvePluginOwnedProviderAuthWith({
				provider: e.provider,
				config: e.cfg
			}, t);
			const r = n.mode === "api-key" ? "api_key" : n.mode;
			return !n.nativeAuth && (!e.profileTypes || e.profileTypes.includes(r)) && isAuthModeAllowedForModel({
				provider: e.provider,
				mode: n.mode,
				capability: e.capability
			}) && (!e.acceptsApiKey || e.acceptsApiKey(n.apiKey));
		} catch {
			return false;
		}
		const i = e.agentDir?.trim();
		if (e.acceptsApiKey) {
			const { acceptsApiKey: t, ...a } = e;
			if (!isProviderApiKeyConfiguredFromStore(a, r)) return false;
			const o = resolveMergedModelProviderConfig(e.cfg, e.provider);
			const s = o?.apiKey;
			const c = e.store ?? (i ? n(i, { allowKeychainPrompt: false }) : void 0);
			let l = r ?? (typeof s === "string" ? c?.profiles[s.trim()] : void 0);
			if (!l && c && o?.auth !== "api-key") {
				const [t] = e.store ? filterAuthProfileIds(c, resolveAuthProfileOrder({
					cfg: e.cfg,
					store: c,
					provider: e.provider
				}), e) : listUsableProviderAuthProfileIds(a).profileIds;
				l = t ? c.profiles[t] : void 0;
			}
			if (l) {
				const e = l.type === "oauth" ? l.access : l.type === "token" ? l.token ?? (l.tokenRef?.source === "env" ? process.env[l.tokenRef.id] : void 0) : l.key ?? (l.keyRef?.source === "env" ? process.env[l.keyRef.id] : void 0);
				return e === void 0 || t(e);
			}
			const u = {
				cfg: e.cfg,
				provider: e.provider
			};
			const d = resolveManagedSecretRefRuntimeProviderAuth(u)?.apiKey ?? resolveUsableCustomProviderApiKey(u)?.apiKey;
			const f = o?.auth === "api-key" && s !== void 0 ? d : resolveEnvApiKey(e.provider, process.env, { config: e.cfg })?.apiKey ?? d;
			return f === void 0 || t(f);
		}
		if (e.cfg) {
			const allowsCredentialMode = (t, n) => (!e.profileTypes?.length || e.profileTypes.some((e) => profileTypeToAuthMode(e) === t)) && (!e.capability || isAuthModeAllowedForModel({
				provider: e.provider,
				capability: e.capability,
				mode: t,
				authFlow: n
			}));
			const t = resolveMergedModelProviderConfig(e.cfg, e.provider)?.apiKey;
			const n = typeof t === "string" ? t.trim() : void 0;
			if (i && n) {
				const t = r !== void 0 ? r ?? void 0 : o({
					agentDir: i,
					profileId: n
				});
				if (t) {
					const r = resolveProviderEntryApiKeyProfileReference({
						cfg: e.cfg,
						provider: e.provider,
						store: {
							version: 1,
							profiles: { [n]: t }
						}
					});
					if (r.kind === "profile-incompatible") return false;
					if (r.kind === "profile") return allowsCredentialMode(r.mode, r.credential.type === "oauth" ? r.credential.authFlow : void 0) && resolveStoredCredentialReadOnlyAvailability({
						credential: r.credential,
						cfg: e.cfg,
						env: process.env
					}) === true;
				}
			}
			const a = resolveUsableCustomProviderApiKey({
				cfg: e.cfg,
				provider: e.provider
			});
			if (a?.apiKey && !isNonSecretApiKeyMarker(a.apiKey) && allowsCredentialMode(resolveDirectProviderCredentialMode({
				cfg: e.cfg,
				provider: e.provider,
				inferredMode: "api-key"
			}))) return true;
			const s = resolveManagedSecretRefRuntimeProviderAuth({
				cfg: e.cfg,
				provider: e.provider
			});
			if (s?.apiKey && allowsCredentialMode(s.mode)) return true;
		}
		if (resolveEnvApiKey(e.provider)?.apiKey && (!e.capability || isAuthModeAllowedForModel({
			provider: e.provider,
			capability: e.capability,
			mode: "api-key"
		}))) return true;
		if (!i) return false;
		const a = e.store ?? n(i, { allowKeychainPrompt: false });
		return filterAuthProfileIds(a, listProfilesForProvider(a, e.provider), e).length > 0;
	}
	/** @deprecated Use isProviderApiKeyConfiguredAsync. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
	function isProviderApiKeyConfigured(e) {
		warnPluginSdkDeprecation({
			family: "provider-auth",
			method: "isProviderApiKeyConfigured",
			replacement: "isProviderApiKeyConfiguredAsync"
		});
		return isProviderApiKeyConfiguredFromStore(e);
	}
	async function isProviderApiKeyConfiguredAsync(e) {
		if (resolveProviderAuthScope({
			provider: e.provider,
			config: e.cfg
		}) === "plugin") return isProviderApiKeyConfiguredFromStore(e);
		const t = e.agentDir?.trim();
		const n = resolveMergedModelProviderConfig(e.cfg, e.provider);
		const i = n?.apiKey;
		const a = typeof i === "string" ? i.trim() : void 0;
		const o = t && a ? await s({
			agentDir: t,
			profileId: a
		}) ?? null : null;
		let c = e.store;
		if (e.acceptsApiKey && !c && t && !o && n?.auth !== "api-key") c = await r(t, { allowKeychainPrompt: false });
		const l = isProviderApiKeyConfiguredFromStore({
			...e,
			store: c ?? {
				version: 1,
				profiles: {}
			}
		}, o);
		if (l || c || !t || o) return l;
		c = await r(t, { allowKeychainPrompt: false });
		return isProviderApiKeyConfiguredFromStore({
			...e,
			store: c
		}, o);
	}
	/** @deprecated Use listUsableProviderAuthProfileIdsAsync. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
	function listUsableProviderAuthProfileIds(e) {
		warnPluginSdkDeprecation({
			family: "auth-profile-sync-operations",
			method: "listUsableProviderAuthProfileIds",
			replacement: "await listUsableProviderAuthProfileIdsAsync()"
		});
		try {
			const { agentDir: t, profileIds: n, store: r } = resolveUsableProviderAuthProfiles(e);
			return {
				agentDir: t,
				profileIds: filterAuthProfileIds(r, n, e)
			};
		} catch {
			return {
				agentDir: "",
				profileIds: []
			};
		}
	}
	/** @deprecated Use isProviderAuthProfileConfiguredAsync. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
	function isProviderAuthProfileConfigured(e) {
		warnPluginSdkDeprecation({
			family: "auth-profile-sync-operations",
			method: "isProviderAuthProfileConfigured",
			replacement: "await isProviderAuthProfileConfiguredAsync()"
		});
		return listUsableProviderAuthProfileIds(e).profileIds.length > 0;
	}
	async function isProviderAuthProfileConfiguredAsync(e) {
		return (await listUsableProviderAuthProfileIdsAsync(e)).profileIds.length > 0;
	}
	async function listUsableProviderAuthProfileIdsAsync(e) {
		try {
			const { agentDir: t, profileIds: n, store: r } = await resolveUsableProviderAuthProfilesAsync(e);
			return {
				agentDir: t,
				profileIds: filterAuthProfileIds(r, n, e)
			};
		} catch {
			return {
				agentDir: "",
				profileIds: []
			};
		}
	}
	/**
	* Resolves the first usable auth-profile API key for a provider in configured profile order.
	*/
	async function resolveProviderAuthProfileApiKey(e) {
		const { resolveApiKeyForProfile: t } = await import("./oauth-I5nvh-hv.mjs");
		const { agentDir: n, profileIds: r, store: i } = await resolveUsableProviderAuthProfilesAsync({
			...e,
			includePendingOAuthRefresh: true
		});
		if (!n || r.length === 0) return;
		for (const a of filterAuthProfileIds(i, r, e)) {
			const r = await t({
				cfg: e.cfg,
				store: i,
				agentDir: n,
				profileId: a
			});
			const o = r?.credential ?? i.profiles[r?.profileId ?? a];
			if (r?.apiKey && (!e.capability || o && acceptsCredential(o, e))) return r.apiKey;
		}
	}
	function resolveUsableProviderAuthProfiles(e) {
		const { agentDir: t, externalCli: n, select: r } = prepareProviderAuthProfileResolution(e);
		const i = r(n ? c(t, { externalCli: n }) : c(t));
		if (i.profileIds.length > 0) return {
			agentDir: t,
			...i
		};
		return {
			agentDir: t,
			...r(l(t, { allowKeychainPrompt: e.allowKeychainPrompt ?? false }))
		};
	}
	async function resolveUsableProviderAuthProfilesAsync(e) {
		const { agentDir: t, externalCli: n, select: r } = prepareProviderAuthProfileResolution(e);
		const o = r(await a(t, {
			readOnly: true,
			allowKeychainPrompt: false,
			...n ? { externalCli: n } : {}
		}));
		if (o.profileIds.length > 0) return {
			agentDir: t,
			...o
		};
		return {
			agentDir: t,
			...r(await i(t, { allowKeychainPrompt: e.allowKeychainPrompt ?? false }))
		};
	}
	function acceptsCredential(e, t) {
		return (!t.profileTypes?.length || t.profileTypes.includes(e.type)) && (!t.capability || isAuthModeAllowedForModel({
			provider: t.provider,
			capability: t.capability,
			mode: profileTypeToAuthMode(e.type),
			authFlow: e.type === "oauth" ? e.authFlow : void 0
		}));
	}
	function filterAuthProfileIds(e, t, n) {
		return t.filter((t) => {
			const r = e.profiles[t];
			return r !== void 0 && acceptsCredential(r, n);
		});
	}
	return {
		isProviderApiKeyConfigured,
		isProviderApiKeyConfiguredAsync,
		listUsableProviderAuthProfileIds,
		listUsableProviderAuthProfileIdsAsync,
		isProviderAuthProfileConfigured,
		isProviderAuthProfileConfiguredAsync,
		resolveProviderAuthProfileApiKey
	};
}
//#endregion
//#region src/plugins/provider-external-auth-core.ts
function createProviderExternalAuthResolver(e) {
	const { resolveProviderPluginsForHooks: t } = e;
	const withPreparedExternalAuthProfiles = async (e, t) => {
		const n = getActivePluginRegistryWorkspaceDirFromStateCore();
		const r = e.env ?? process.env;
		const i = e.config ?? {};
		const a = await resolvePluginMetadataSnapshotAsync({
			config: i,
			workspaceDir: n,
			env: r
		});
		return withPluginMetadataSnapshotScope(a, t, {
			config: i,
			workspaceDir: n,
			env: r
		});
	};
	function resolveExternalAuthProfilesWithPlugins(e) {
		const n = e.workspaceDir ?? getActivePluginRegistryWorkspaceDirFromStateCore();
		const r = e.env ?? process.env;
		const i = e.config ?? {};
		const a = getCurrentPluginMetadataSnapshot({
			env: r,
			...e.config ? { config: i } : { requireDefaultDiscoveryContext: true },
			...n ? { workspaceDir: n } : { allowWorkspaceScopedSnapshot: true }
		});
		const { manifestRegistry: o } = a ?? resolvePluginMetadataSnapshot({
			config: i,
			workspaceDir: n,
			env: r
		});
		if (a && !o.plugins.some((e) => e.contracts?.externalAuthProviders?.length)) return [];
		const s = resolveExternalAuthProfileProviderPluginIds({
			config: e.config,
			workspaceDir: n,
			env: r,
			manifestRegistry: o
		});
		if (s.length === 0) return [];
		const c = [];
		for (const i of t({
			...e,
			workspaceDir: n,
			env: r,
			onlyPluginIds: s
		})) c.push(...i.resolveExternalAuthProfiles?.(e.context) ?? []);
		return c;
	}
	return {
		resolveExternalAuthProfilesWithPlugins,
		withPreparedExternalAuthProfiles
	};
}
//#endregion
//#region src/plugins/provider-registration-projection.ts
const projections = /* @__PURE__ */ new WeakMap();
/** Shared frozen `{ ...provider, pluginId }` for one registry entry; consumers must not mutate it. */
function projectRegisteredProvider(e, t) {
	let n = projections.get(e);
	if (n?.pluginId !== t) {
		n = Object.freeze(Object.assign({}, e, { pluginId: t }));
		projections.set(e, n);
	}
	return n;
}
//#endregion
//#region src/plugins/provider-hook-runtime-core.ts
const MODEL_PROVIDER_RUNTIME_PLUGIN_HANDLE_SYMBOL = Symbol.for("openclaw.modelProviderRuntimePluginHandle");
function createProviderHookRuntime(e) {
	const { resolvePluginProviderRegistryCore: t, resolvePluginProvidersCore: n } = e;
	/** Carries one attempt's prepared provider plugin through the model transport boundary. */
	function attachModelProviderRuntimePluginHandle(e, t) {
		return {
			...attachModelProviderLocalServiceReconciler(e, t.plugin?.reconcileLocalService),
			[MODEL_PROVIDER_RUNTIME_PLUGIN_HANDLE_SYMBOL]: t
		};
	}
	function getModelProviderRuntimePluginHandle(e) {
		return e ? e[MODEL_PROVIDER_RUNTIME_PLUGIN_HANDLE_SYMBOL] : void 0;
	}
	function resolveProviderRuntimeLookupModelId(e) {
		return normalizeOptionalString(e.modelId ?? e.context?.modelId);
	}
	function resolveLoadedProviderPluginsForHooks(e) {
		const n = t({
			...e,
			registryScope: "loaded"
		});
		if (!n) return;
		return n.registry.providers.filter(({ pluginId: t, provider: r }) => (!n.onlyPluginIds || n.onlyPluginIds.includes(t)) && (!e.providerRefs?.length || e.providerRefs.some((e) => matchesProviderPluginRef(r, e)))).map(({ pluginId: e, provider: t }) => Object.assign({}, t, { pluginId: e }));
	}
	function resolveProviderPluginsForHooks(e) {
		return n({
			...e,
			activate: false,
			applyAutoEnable: e.applyAutoEnable,
			skipIfLoadInFlight: true
		});
	}
	function resolveSelectedProvider(e, t, n) {
		const r = e && findProviderRuntimeRegistrationInRegistry({
			registry: e.registry,
			provider: t,
			ownerRefs: n,
			isOwnerEligible: (n) => e.isProviderOwnerEligible(n, t)
		});
		return r ? projectRegisteredProvider(r.provider, r.pluginId) : void 0;
	}
	function resolveProviderRuntimePluginLookup(e, n) {
		const r = resolveProviderConfigApiOwnerHint(e);
		const i = [...new Set([e.providerOwner, r].filter((e) => Boolean(e)))];
		const a = resolveProviderRuntimeLookupModelId(e);
		const o = t({
			...e,
			providerRefs: [e.provider, ...i],
			modelRefs: a ? resolveModelCatalogScope({
				cfg: e.config,
				provider: e.provider,
				model: a
			}) : void 0,
			registryScope: n,
			activate: false,
			skipIfLoadInFlight: true
		});
		const s = resolveSelectedProvider(o, e.provider, i);
		if (s && (s.authScope ?? "agent") !== resolveProviderAuthScope(e)) throw pluginProviderAuthUnavailable(e.provider, "runtime and static credential scope differ");
		return {
			...e,
			...o ? { workspaceDir: o.workspaceDir } : {},
			plugin: s
		};
	}
	function resolveProviderRuntimePlugin(e) {
		return resolveProviderRuntimePluginLookup(e).plugin;
	}
	function resolveLoadedProviderRuntimePlugin(e) {
		return resolveProviderRuntimePluginLookup(e, "loaded").plugin;
	}
	function resolveProviderHookPlugin(e) {
		const n = resolveProviderRuntimePlugin(e);
		if (n) return n;
		if (hasConfiguredModelProvider(e)) return;
		return resolveSelectedProvider(t({
			config: e.config,
			workspaceDir: e.workspaceDir,
			env: e.env,
			activate: false,
			skipIfLoadInFlight: true
		}), e.provider, []);
	}
	function ensureProviderRuntimePluginHandle(e) {
		const t = resolveProviderRuntimeLookupModelId(e);
		if (!e.runtimeHandle || t && !e.runtimeHandle.plugin && e.runtimeHandle.modelId !== t) return resolveProviderRuntimePluginLookup({
			provider: e.provider,
			modelId: t,
			config: e.config ?? e.runtimeHandle?.config,
			workspaceDir: e.workspaceDir ?? e.runtimeHandle?.workspaceDir,
			env: e.env ?? e.runtimeHandle?.env,
			applyAutoEnable: e.runtimeHandle?.applyAutoEnable,
			pluginMetadataSnapshot: e.pluginMetadataSnapshot ?? e.runtimeHandle?.pluginMetadataSnapshot
		});
		return e.runtimeHandle;
	}
	function resolveProviderAuthProfileId(e) {
		const t = ensureProviderRuntimePluginHandle(e).plugin?.resolveAuthProfileId?.(e.context);
		return normalizeOptionalString(t);
	}
	function resolveProviderFollowupFallbackRoute(e) {
		return ensureProviderRuntimePluginHandle(e).plugin?.followupFallbackRoute?.(e.context) ?? void 0;
	}
	function wrapProviderSimpleCompletionStreamFn(e) {
		return ensureProviderRuntimePluginHandle(e).plugin?.wrapSimpleCompletionStreamFn?.(e.context) ?? void 0;
	}
	return {
		attachModelProviderRuntimePluginHandle,
		getModelProviderRuntimePluginHandle,
		resolveLoadedProviderPluginsForHooks,
		resolveProviderPluginsForHooks,
		resolveProviderRuntimePlugin,
		resolveLoadedProviderRuntimePlugin,
		resolveProviderHookPlugin,
		resolveProviderRuntimePluginHandle: resolveProviderRuntimePluginLookup,
		ensureProviderRuntimePluginHandle,
		resolveProviderAuthProfileId,
		resolveProviderFollowupFallbackRoute,
		wrapProviderSimpleCompletionStreamFn
	};
}
//#endregion
//#region src/plugins/providers.runtime-core.ts
function createProviderRegistryResolver(e) {
	const { loadOpenClawPlugins: t, resolveRuntimePluginRegistry: n, isPluginRegistryLoadInFlight: r } = e;
	function prepareProviderSelection(e, t, n = buildDeclaredProviderOwnerIndex(t?.plugins ?? []), r = false) {
		let i;
		const a = t ? (e.providerRefs ?? []).map((a) => {
			const o = {
				provider: a,
				config: e.config,
				workspaceDir: e.workspaceDir,
				env: e.env
			};
			const s = resolveProviderConfigApiOwnerHint(o);
			const c = n.has(normalizeProviderId(a)) ? a : s ?? a;
			const l = n.get(normalizeProviderId(c));
			const u = l ? [...l] : resolveOwningPluginIdsForProviderRef({
				...o,
				provider: c,
				manifestRegistry: t
			}) ?? [];
			const d = r && u.length > 0 ? [] : sortUniqueStrings([a, ...s ? [s] : []].flatMap((n) => resolveManifestActivationPluginIds({
				...o,
				trigger: {
					kind: "provider",
					provider: n
				},
				manifestRecords: t.plugins,
				normalizedConfig: i ??= normalizePluginsConfig(e.config?.plugins)
			})));
			return {
				provider: a,
				ownerPluginIds: u,
				providerPluginIds: u.length > 0 ? u : d,
				runtimePluginIds: d
			};
		}) : [];
		const o = t && e.modelRefs?.length ? resolveOwningPluginIdsForModelRefs({
			models: e.modelRefs,
			config: e.config,
			workspaceDir: e.workspaceDir,
			env: e.env,
			manifestRegistry: t
		}) : [];
		const s = sortUniqueStrings([...a.flatMap((e) => [...e.ownerPluginIds, ...e.runtimePluginIds]), ...o]);
		return {
			pluginIds: !t ? e.onlyPluginIds : hasExplicitPluginIdScope(e.onlyPluginIds) || e.providerRefs?.length || e.modelRefs?.length ? sortUniqueStrings([...e.onlyPluginIds ?? [], ...s]) : void 0,
			workspaceDir: e.workspaceDir,
			manifestRegistry: t,
			onlyPluginIds: e.onlyPluginIds,
			providerRefs: e.providerRefs,
			projectedPluginIds: t && (e.providerRefs?.length || e.modelRefs?.length) ? sortUniqueStrings([...a.flatMap((e) => e.providerPluginIds), ...o]) : void 0,
			declaredProviderOwners: n,
			providerOwners: a,
			providerRegistrationPluginIds: void 0,
			runtimeRegistrationPluginIds: void 0,
			unownedProviderRefs: t ? a.filter((e) => e.ownerPluginIds.length === 0).map((e) => e.provider) : e.providerRefs ?? [],
			explicitOwnerPluginIds: s
		};
	}
	function prepareProviderLookup(e, t = false) {
		const n = e.env ?? process.env;
		const r = t ? {
			...e,
			pluginMetadataSnapshot: getCurrentPluginMetadataSnapshot({
				config: e.config,
				env: n
			})
		} : e;
		const i = resolveProviderRuntimeWorkspaceDir(r, t ? void 0 : getActivePluginRegistryWorkspaceDir());
		const a = r.pluginMetadataSnapshot ?? (t || e.registryScope === "loaded" ? getCurrentPluginMetadataSnapshot({
			config: e.config,
			env: n,
			workspaceDir: i,
			allowWorkspaceScopedSnapshot: true
		}) : resolvePluginMetadataSnapshot({
			config: e.config ?? {},
			env: n,
			workspaceDir: i
		}));
		const o = {
			...r,
			env: n,
			workspaceDir: i
		};
		const s = a ? prepareProviderSelection(o, a.manifestRegistry, a.declaredProviderOwners, t) : void 0;
		return {
			inputs: o,
			snapshot: a,
			selection: s,
			loadOptions: a && s && !t ? resolveProviderLoadOptions(o, s, a) : void 0
		};
	}
	function resolveProviderLoadOptions(e, t, n) {
		const r = resolvePluginActivationSourceConfig(e);
		const i = {
			config: e.config,
			workspaceDir: e.workspaceDir,
			env: e.env,
			includeUntrustedWorkspacePlugins: e.includeUntrustedWorkspacePlugins,
			registry: n.index,
			manifestRegistry: n.manifestRegistry,
			normalizePluginId: n.normalizePluginId
		};
		const a = e.mode === "setup";
		const o = (a ? resolveDiscoverableProviderOwnerPluginIds : resolveActivatableProviderOwnerPluginIds)({
			...i,
			pluginIds: t.explicitOwnerPluginIds
		});
		let s;
		if (a) {
			t.pluginIds = sortUniqueStrings([...resolveDiscoveredProviderPluginIds({
				...i,
				onlyPluginIds: t.pluginIds
			}), ...o]);
			if (t.pluginIds.length === 0) return;
			const n = withActivatedPluginIds({
				config: e.config,
				pluginIds: t.pluginIds
			});
			s = {
				config: n,
				activationSourceConfig: n,
				autoEnabledReasons: {}
			};
		} else {
			const r = t.pluginIds !== void 0 ? sortUniqueStrings([...e.onlyPluginIds ?? [], ...o]) : void 0;
			s = resolveBundledCompatActivationInputs({
				rawConfig: withActivatedPluginIds({
					config: e.config,
					pluginIds: o
				}),
				env: e.env,
				workspaceDir: e.workspaceDir,
				applyAutoEnable: e.applyAutoEnable ?? true,
				discovery: n.discovery,
				manifestRegistry: n.manifestRegistry,
				onlyPluginIds: r,
				resolveBundledPluginIds: resolveBundledProviderCompatPluginIds,
				activation: "defaults"
			});
			const a = sortUniqueStrings([...resolveEnabledProviderPluginIds({
				...i,
				config: s.config,
				onlyPluginIds: r
			}), ...o]);
			t.pluginIds = a;
			t.projectedPluginIds = t.projectedPluginIds?.filter((e) => a.includes(e));
		}
		if (e.config !== void 0 && r !== e.config) s.activationSourceConfig = withActivatedPluginIds({
			config: r,
			pluginIds: a ? t.pluginIds : o
		});
		return buildPluginRuntimeLoadOptions({
			...s,
			workspaceDir: e.workspaceDir,
			env: e.env,
			logger: pluginRuntimeLoaderLogger,
			manifestRegistry: n.manifestRegistry,
			installRecords: extractPluginInstallRecordsFromInstalledPluginIndex(n.index)
		}, {
			normalizePluginId: n.normalizePluginId,
			registrationConfigOrigin: !a && e.registryScope !== "exact" ? e.config : void 0,
			onlyPluginIds: t.pluginIds,
			pluginSdkResolution: e.pluginSdkResolution,
			cache: e.cache ?? !a,
			activate: e.activate ?? false
		});
	}
	function isPluginProvidersLoadInFlight(e) {
		const { loadOptions: t } = prepareProviderLookup({
			...e,
			registryScope: void 0
		});
		return t !== void 0 && r(t);
	}
	function captureProviderRegistrySelection(e, t, n) {
		return {
			registry: e,
			workspaceDir: t.workspaceDir,
			onlyPluginIds: n,
			isProviderOwnerEligible: (e, r) => (!n || n.includes(e)) && matchesDeclaredProviderOwner(t.declaredProviderOwners, r, e)
		};
	}
	function resolveProviderRegistryCandidate(e, t, n, r, i) {
		let a = t.pluginIds;
		let o = t.projectedPluginIds ?? a;
		if (t.unownedProviderRefs.length > 0) {
			a = sortUniqueStrings([...a ?? [], ...r]);
			o = sortUniqueStrings([...o ?? [], ...r]);
		}
		if (n) return captureProviderRegistrySelection(e, t, o);
		if (!registryContainsRuntimePluginIds(e, a)) return;
		if (i) {
			t.providerRegistrationPluginIds ??= new Set((t.manifestRegistry?.plugins ?? []).filter((e) => e.providers.length > 0 || (e.setup?.providers?.length ?? 0) > 0).map((e) => e.id));
			t.runtimeRegistrationPluginIds ??= new Set(t.providerOwners.flatMap((e) => e.runtimePluginIds));
			const n = new Set(e.providers.map((e) => e.pluginId));
			for (const e of a ?? []) {
				const r = i(e);
				if (!r || (t.providerRegistrationPluginIds.has(e) ? !n.has(e) : t.runtimeRegistrationPluginIds.has(e) && !hasCompletedPluginRuntimeRegistration(r))) return;
			}
			a ??= sortUniqueStrings(e.providers.map((e) => e.pluginId).filter(i));
		}
		return e.providers.some(({ pluginId: e, provider: n }) => (!a || a.includes(e)) && (!t.providerRefs?.length || t.providerRefs.some((e) => matchesProviderPluginRef(n, e)))) ? captureProviderRegistrySelection(e, t, o ?? a) : void 0;
	}
	function resolvePluginProviderRegistryCore(e) {
		if (e.mode === "setup" && e.registryScope === "loaded") return;
		const i = e.mode === "setup" ? void 0 : getPluginRuntimeGenerationRegistry();
		const a = prepareProviderLookup(e, Boolean(i));
		const { inputs: o, snapshot: s } = a;
		let { loadOptions: c } = a;
		const { env: l, workspaceDir: u } = o;
		const registrationKey = (t) => {
			if (i || e.config === void 0) return;
			const n = c ?? {
				config: e.config,
				activationSourceConfig: resolvePluginActivationSourceConfig(e)
			};
			const r = t ? (e) => normalizePluginsConfigWithResolverCore(e?.plugins, t) : (e) => normalizePluginsConfig(e?.plugins);
			return resolvePluginRegistrationConfigKey({
				runtimeEntries: r(n.config).entries,
				sourceEntries: r(n.activationSourceConfig).entries
			});
		};
		const d = s ? registrationKey(s.normalizePluginId) : void 0;
		if (e.skipIfLoadInFlight && c && r(c)) return;
		const prepareRegistry = (e, t) => {
			const n = !i && t.manifestRegistry ? createRuntimePluginManifestLookup(e, t.manifestRegistry.plugins) : void 0;
			const r = t.unownedProviderRefs.length > 0 ? e.providers.filter(({ pluginId: e, provider: r }) => (!t.onlyPluginIds || t.onlyPluginIds.includes(e)) && t.unownedProviderRefs.some((e) => matchesProviderPluginRef(r, e)) && (!n || Boolean(n(e)))).map((e) => e.pluginId) : [];
			return {
				lookup: n,
				aliasOwners: !i && s && r.length > 0 ? resolveActivatableProviderOwnerPluginIds({
					...o,
					pluginIds: r,
					registry: s.index,
					manifestRegistry: s.manifestRegistry,
					normalizePluginId: s.normalizePluginId
				}) : r
			};
		};
		if (i || e.mode !== "setup") {
			const t = getPluginRuntimeGatewayRequestScope()?.pluginRegistry;
			const n = getPluginRuntimeLoadContext(t);
			const f = i ? [i] : [n && n.workspaceDir === u ? t : void 0, getLoadedRuntimePluginRegistry({
				env: l,
				workspaceDir: u
			})];
			for (const t of f) {
				if (!t) continue;
				const n = getPluginRuntimeLoadContext(t);
				if (!s && !i && n && resolvePluginControlPlaneFingerprint({
					config: e.config ?? n.rawConfig,
					env: e.env ?? n.env,
					workspaceDir: u
				}) !== n.controlPlaneFingerprint) continue;
				const l = a.selection ?? prepareProviderSelection(o, n?.manifestRegistry, n?.declaredProviderOwners, Boolean(i));
				const { lookup: f, aliasOwners: p } = prepareRegistry(t, l);
				if (!i && s && p.some((e) => !l.explicitOwnerPluginIds.includes(e))) {
					l.explicitOwnerPluginIds = sortUniqueStrings([...l.explicitOwnerPluginIds, ...p]);
					c = resolveProviderLoadOptions(o, l, s);
					if (e.skipIfLoadInFlight && c && r(c)) return;
				}
				const m = s ? d : registrationKey(n?.normalizePluginId);
				if (!i && e.registryScope === "exact" || n && m !== void 0 && m !== n.registrationConfigKey) continue;
				const h = resolveProviderRegistryCandidate(t, l, Boolean(i), p, f);
				if (h) return h;
			}
		}
		if (i || e.registryScope === "loaded" || !c || !a.selection || c.onlyPluginIds?.length === 0) return;
		const f = e.mode === "setup" || e.registryScope === "exact" ? t(c) : n(c);
		if (!f) return;
		const p = a.selection.projectedPluginIds ?? c.onlyPluginIds;
		return captureProviderRegistrySelection(f, a.selection, e.mode !== "setup" && p ? sortUniqueStrings([...p, ...a.selection.unownedProviderRefs.length > 0 ? prepareRegistry(f, a.selection).aliasOwners : []]) : void 0);
	}
	function resolvePluginProvidersCore(e, t) {
		const n = resolvePluginProviderRegistryCore(e);
		if (!n) return [];
		const { registry: r, onlyPluginIds: i } = n;
		const a = t?.(r) ?? projectRegisteredProvider;
		return r.providers.filter((e) => !i || i.includes(e.pluginId)).map((e) => a(e.provider, e.pluginId));
	}
	return {
		isPluginProvidersLoadInFlight,
		resolvePluginProviderRegistryCore,
		resolvePluginProvidersCore
	};
}
//#endregion
//#region src/plugins/loader-runtime-load.ts
/** Native composition entry for ordinary, restricted, and cold provider-hook loading. */
const loadModelAuthRuntime = createLazyRuntimeModule(() => import("./runtime-model-auth.runtime.js"));
function resolveRuntimePluginRegistry(e) {
	const t = resolveCompatibleRuntimePluginRegistry(e);
	if (t) return t;
	return isPluginRegistryLoadInFlight(e) ? void 0 : loadOpenClawPlugins({
		...e,
		activate: false
	});
}
const providerRegistry = Object.freeze(createProviderRegistryResolver({
	loadOpenClawPlugins,
	resolveRuntimePluginRegistry,
	isPluginRegistryLoadInFlight
}));
const providerHooks = Object.freeze(createProviderHookRuntime(providerRegistry));
const externalProfiles = Object.freeze(createProviderExternalAuthResolver(providerHooks));
const externalAuth = Object.freeze(createExternalAuthRuntime(externalProfiles.resolveExternalAuthProfilesWithPlugins, externalProfiles.withPreparedExternalAuthProfiles));
const authStore = Object.freeze(createAuthProfileStoreRuntime(externalAuth));
const authAvailability = Object.freeze(createProviderAuthAvailability(authStore, providerHooks.resolveProviderRuntimePlugin));
let modelAuth;
let modelConfig;
let capabilityCatalogContext;
const loaderBindings = {
	get modelAuth() {
		if (!modelAuth) {
			const e = createLazyRuntimeMethod(loadModelAuthRuntime, (e) => e.getApiKeyForModel);
			const t = createLazyRuntimeMethod(loadModelAuthRuntime, (e) => e.getRuntimeAuthForModelCore);
			const n = createLazyRuntimeMethod(loadModelAuthRuntime, (e) => e.resolveProviderRuntimeApiKey);
			modelAuth = {
				resolveProviderIdForAuth,
				ensureAuthProfileStore: authStore.ensureAuthProfileStore,
				ensureAuthProfileStoreAsync: authStore.ensureAuthProfileStoreAsync,
				resolveAuthProfileOrder,
				listProfilesForProvider,
				isProviderApiKeyConfigured: authAvailability.isProviderApiKeyConfigured,
				isProviderApiKeyConfiguredAsync: authAvailability.isProviderApiKeyConfiguredAsync,
				getApiKeyForModel: (t) => e({
					model: t.model,
					cfg: t.cfg,
					workspaceDir: t.workspaceDir
				}),
				getRuntimeAuthForModel: (e) => t({
					model: e.model,
					cfg: e.cfg,
					workspaceDir: e.workspaceDir
				}),
				resolveApiKeyForProvider: (e) => n({
					provider: e.provider,
					cfg: e.cfg,
					workspaceDir: e.workspaceDir
				})
			};
		}
		return modelAuth;
	},
	get modelConfig() {
		return modelConfig ??= {
			resolveDefaultModelForAgent,
			resolveAllowedModelRef: resolveAllowedModelRefCore,
			resolveModelRuntimePolicy
		};
	},
	get capabilityCatalogContext() {
		return capabilityCatalogContext ??= Object.freeze({
			isProviderApiKeyConfigured: authAvailability.isProviderApiKeyConfigured,
			isProviderApiKeyConfiguredAsync: authAvailability.isProviderApiKeyConfiguredAsync,
			isProviderAuthProfileConfigured: authAvailability.isProviderAuthProfileConfigured,
			isProviderAuthProfileConfiguredAsync: authAvailability.isProviderAuthProfileConfiguredAsync,
			resolveAgentDir,
			createRealtimeTranscriptionWebSocketSession,
			resolveProviderRequestHeaders,
			resolveProviderAuthProfileApiKey: authAvailability.resolveProviderAuthProfileApiKey,
			resolveApiKeyForProvider: async (e) => (await import("./runtime-model-auth.runtime.js")).resolveProviderRuntimeApiKey(e),
			captureWsEvent,
			captureWsEventAsync,
			createDebugProxyWebSocketAgent,
			resolveDebugProxySettings,
			fetchWithSsrFGuard,
			createProviderHttpError,
			readProviderJsonResponse,
			readProviderTextResponse,
			formatErrorMessage,
			warn,
			redactSensitiveText
		});
	}
};
const nativePluginBindings = Object.freeze({
	providerRegistry,
	providerHooks,
	externalProfiles,
	externalAuth,
	authStore,
	authAvailability
});
function resolvePluginCapabilityCatalogContext() {
	return loaderBindings.capabilityCatalogContext;
}
function loadOpenClawPlugins(e = {}) {
	return loadOpenClawPluginsCore(e, loaderBindings);
}
const pendingCachedLoads = /* @__PURE__ */ new WeakMap();
/** Keep network callbacks responsive without publishing a partially registered generation. */
async function loadOpenClawPluginsAsync(e = {}) {
	const load = () => runPluginLoadStepsAsync(loadOpenClawPluginsSteps(e, loaderBindings));
	if (e.activate !== false || !isCachedPluginRegistryLoad(e)) return load();
	const { cacheState: t, cacheKey: n } = resolvePluginLoadCacheContext(e);
	let r = pendingCachedLoads.get(t);
	if (!r) {
		r = /* @__PURE__ */ new Map();
		pendingCachedLoads.set(t, r);
	}
	const i = e.throwOnLoadError === true;
	for (let t = r.get(n); t; t = r.get(n)) {
		if (!t.strict) {
			const n = await t.promise;
			maybeThrowOnPluginLoadError(n, e.throwOnLoadError);
			return n;
		}
		if (i) return t.promise;
		try {
			return await t.promise;
		} catch {
			if (r.get(n) === t) r.delete(n);
		}
	}
	const a = {
		promise: load(),
		strict: i
	};
	r.set(n, a);
	try {
		return await a.promise;
	} finally {
		if (r.get(n) === a) r.delete(n);
	}
}
async function runPluginLoadStepsAsync(e) {
	let t = e.next();
	while (!t.done) {
		await setImmediate();
		try {
			await t.value?.();
			t = e.next();
		} catch (n) {
			t = e.throw(n);
		}
	}
	return t.value;
}
/** Publishes synchronously, then joins every accepted health write before returning to its host. */
async function loadAndActivateRootPluginRegistry(e = {}) {
	const t = [];
	try {
		return await runPluginLoadStepsAsync(loadOpenClawPluginsSteps({
			...e,
			activate: true
		}, loaderBindings, void 0, void 0, (e) => t.push(e)));
	} finally {
		await Promise.allSettled(t);
	}
}
/** Acquires a fresh discovery registry; release waits for its registration resources. */
async function acquirePluginRegistryForInspection(e = {}) {
	return acquireRegistryResources((t) => runPluginLoadStepsAsync(loadOpenClawPluginsSteps({
		...e,
		activate: false,
		cache: false
	}, loaderBindings, void 0, t)));
}
async function acquireRegistryResources(e) {
	const t = createPluginCache();
	const n = new PluginRegistryInspectionResources(async (e, n) => {
		const r = new Set(t.instances);
		for (const t of e?.plugins ?? []) {
			const n = getPluginInstance(t);
			if (n && n.owner?.registry === e) r.add(n);
		}
		const i = (await Promise.allSettled([...r].filter((t) => {
			const n = getPluginInstanceOwner(t);
			return !n || n.registry === e;
		}).map(async (e) => {
			const t = await e.dispose(void 0, { waitForSettlement: true });
			return n.has(e) ? { errors: [] } : t;
		}))).flatMap((e) => e.status === "rejected" ? [new PluginRuntimeCloseRetainedError(e.reason)] : e.value.errors);
		for (const e of r) releasePluginCacheInstance(e, t);
		try {
			const e = await retirePluginCache(t, void 0, { waitForSettlement: true });
			i.push(...e.failures.map((e) => e.error));
		} catch (e) {
			i.push(new PluginRuntimeCloseRetainedError(e));
		}
		if (i.length) throw new AggregateError(i, "Plugin inspection instances failed to retire");
	});
	try {
		inheritPluginNativeAdmissions(getPluginCache(), t);
		return {
			registry: await withPluginCache(t, () => e(n)),
			release: n.release.bind(n)
		};
	} catch (e) {
		try {
			await n.release();
		} catch (t) {
			throw new AggregateError([e, t], "Plugin inspection failed and its resources could not be disposed", { cause: t });
		}
		throw e;
	}
}
function loadOpenClawPluginsWithInternalOverrides(e, t) {
	const n = loadRegistryWithInternalOverridesSteps(e, t);
	let r = n.next();
	while (!r.done) r = n.next();
	return r.value;
}
/** Owns the same narrow capability runtime without publishing or caching its registrations. */
function acquirePluginRegistryWithInternalOverrides(e, t) {
	return acquireRegistryResources((n) => runPluginLoadStepsAsync(loadRegistryWithInternalOverridesSteps(e, t, n)));
}
function loadRegistryWithInternalOverridesSteps(e, t, n) {
	const r = t.runtime.modelAuth ?? e.runtimeOptions?.modelAuth ?? { ...loaderBindings.modelAuth };
	const i = t.runtime.modelConfig ?? e.runtimeOptions?.modelConfig ?? { ...loaderBindings.modelConfig };
	const a = {
		config: t.runtime.config,
		get modelAuth() {
			return r;
		},
		get modelConfig() {
			return i;
		}
	};
	const o = Object.getOwnPropertyDescriptors(t.runtime);
	delete o.modelAuth;
	delete o.modelConfig;
	Object.defineProperties(a, o);
	return loadOpenClawPluginsSteps(e, loaderBindings, {
		...t,
		runtime: a
	}, n);
}
function resolveNativePluginModelAuth() {
	return { ...loaderBindings.modelAuth };
}
function resolveNativePluginModelConfig() {
	return { ...loaderBindings.modelConfig };
}
//#endregion
export { createRuntimeBase as C, resolvePluginRegistryLoadCacheKey as E, CORE_BOARD_DATA_BINDING_IDS as S, isPluginRegistryLoadInFlight as T, hasMalformedSecretInputSyntax as _, loadOpenClawPluginsAsync as a, resolveStoredCredentialReadOnlyAvailability as b, resolveNativePluginModelAuth as c, resolveRuntimePluginRegistry as d, pluginProviderAuthUnavailable as f, resolveManagedSecretRefRuntimeProviderAuth as g, assertRuntimeProviderSecretOwnerAvailable as h, loadOpenClawPlugins as i, resolveNativePluginModelConfig as l, resolveProviderAuthScope as m, acquirePluginRegistryWithInternalOverrides as n, loadOpenClawPluginsWithInternalOverrides as o, resolvePluginOwnedProviderAuthWith as p, loadAndActivateRootPluginRegistry as r, nativePluginBindings as s, acquirePluginRegistryForInspection as t, resolvePluginCapabilityCatalogContext as u, resolveAuthStoreReadOnlyValidUntil as v, clearPluginRegistryLoadCache as w, describeDashboardCapabilities as x, resolveSecretRefReadOnlyAvailability as y };