UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

11,545 lines • 373 kB
import { d as isRfc8215LocalUseNat64Ipv6Address, l as isLoopbackIpAddress, p as normalizeIpAddress, u as isPrivateOrLoopbackIpAddress$1 } from "./ip-CSwXvcih.mjs";
import { a as resolveIncludeRoots, b as toStringifiedError, g as extractErrorCodeOrErrno, i as resolveGatewayPort, t as resolveConfigPath } from "./paths-0xDagtub.mjs";
import { d as asOptionalRecord, f as asRecord, i as sanitizeTerminalText, l as asNullableRecord, p as isRecord } from "./utils-BclMknzT.mjs";
import { B as normalizeOptionalString, C as asPositiveInteger, L as normalizeLowercaseStringOrEmpty, U as resolveGlobalSet, W as resolveGlobalSingleton, a as resolveStateDir, x as asNonNegativeInteger } from "./path-guards-quCEQx1i.mjs";
import { C as copyConfigResolutionFactsExcept, D as resolveConfigSecretRef, E as hasUnresolvedConfigPath, O as setConfigResolutionFacts, S as cloneConfigWithResolutionFacts, T as getConfigResolutionFacts, _ as resolveClientCredentialStorePath, f as DeviceIdentityStorageError, g as storedDeviceIdentityToRow, h as normalizeIdentityKey, i as closedObject, j as safeParseJsonRecord, m as identityFromCredentialResult, p as generateStoredDeviceIdentity, r as stringLiteralUnion, w as getAuthoredConfigSecretRef, x as resolveConfigForRead } from "./openclaw-state-db-kPhNg45U.mjs";
import { a as resolveSleepDelayMs, i as raceWithTimeout, n as createAbortError, o as sleepWithAbort, r as racePromiseWithAbortSignal, t as RetrySupervisor } from "./src-DIZdnDBl.mjs";
import { a as resolvePreauthHandshakeTimeoutMs, i as resolveFiniteTimeoutDelayMs, n as clearGatewayConnectTimeout, o as resolveSafeTimeoutDelayMs, r as resolveConnectChallengeTimeoutMs, s as startGatewayConnectTimeout, t as DEFAULT_GATEWAY_REQUEST_TIMEOUT_MS } from "./timeouts-MDRkjIZh.mjs";
import { c as VERSION } from "./sqlite-user-version-D-rYjp-A.mjs";
import { A as normalizeRequiredSecretInput, D as containsEnvVarReference, G as parseJsonWithJson5Fallback, M as parseSecretRef, N as resolveSecretInputRef, Q as redactSensitiveUrlLikeString, h as resolveConfigIncludes, i as redactToolPayloadText, j as normalizeSecretInputString, k as hasConfiguredSecretInput, s as registerSecretValueForRedaction } from "./redact-BRF0hr6G.mjs";
import { i as normalizeOptionalTrimmedStringList, n as filterStringEntries, s as normalizeTrimmedStringList } from "./string-normalization-BMFMScZY.mjs";
import { h as AsyncContext, t as createSubsystemLogger } from "./subsystem-CeOCPr4l.mjs";
import { n as getPluginExecutionFrame, t as InvocationFrame } from "./plugin-instance-invocation-DLc0_aJ8.mjs";
import "./openclaw-root-l-fyeuXJ.mjs";
import { m as resolveDatabasePathKeyAsync } from "./sqlite-worker-identity-CiWdPbPl.mjs";
import { a as READ_SCOPE, c as WRITE_SCOPE, i as QUESTIONS_SCOPE, n as APPROVALS_SCOPE, o as SESSION_WRITE_SCOPE, r as PAIRING_SCOPE, s as TALK_SECRETS_SCOPE, t as ADMIN_SCOPE } from "./operator-scopes-By8_6ecO.mjs";
import "./env-C62NiKTo.mjs";
import { c as isVitestRuntimeEnv, o as isSecretResolutionError, s as captureRuntimeConfigWithSource } from "./resolve-CJA8GTEb.mjs";
import "./sqlite-database-admission-DMm34jqt.mjs";
import "./gateway-process-argv-DB5Y-Mad.mjs";
import "./openclaw-state-db-cache-D7C7Hg5y.mjs";
import { t as SUBAGENT_EXEC_ENV_VAR } from "./openclaw-exec-env-6zVPuy1n.mjs";
import { d as withDatabaseEngineSelection, u as getDatabaseEngineSelection } from "./worker-task-pool-DBu8jMlX.mjs";
import { a as resolveRuntimeProcessEntrypointUrl } from "./runtime-process-url-sztU0Vcb.mjs";
import { s as getOpenClawDatabaseMaintenanceScope } from "./openclaw-state-db-async-lifecycle-DLH47xBr.mjs";
import "./executable-path-BtaxFk1u.mjs";
import { a as signEd25519Payload, i as publicKeyRawBase64UrlFromEd25519Pem } from "./ed25519-signature-CQ3Kb-UR.mjs";
import { a as parseHostForAddressChecks, i as parseGatewayIpAddress, n as isGatewayClientStoppedError, o as requireTlsFingerprint, r as normalizeTlsFingerprint, t as formatGatewayClientErrorForLog } from "./client-address-utils-Dc3O8nVZ.mjs";
import { n as resolveCanonicalConfiguredSecretInputWithFallback, r as resolveDatabaseFamilyEngines } from "./resolve-configured-secret-input-string-DhCO8T_w.mjs";
import { n as logError, t as logDebug } from "./logger-DlJKXoGM.mjs";
import { c as resolveActiveManagedProxyTlsOptions, d as getActiveManagedProxyLoopbackMode, f as resolveEnvHttpProxyAgentOptions, i as loadUndiciGlobalDispatcherDeps, l as loadManagedProxyTlsOptionsSync, n as createHttp1EnvHttpProxyAgent, t as createHttp1Agent, u as resolveManagedProxyCaFileForUrl } from "./undici-runtime-CrE1-VGD.mjs";
import { t as getPluginRegistryState } from "./runtime-state-wvrNT8EC.mjs";
import { createRequire } from "node:module";
import { isDeepStrictEqual, types } from "node:util";
import fsSync from "node:fs";
import path from "node:path";
import crypto, { createHash, randomUUID } from "node:crypto";
import os from "node:os";
import { Buffer as Buffer$1 } from "node:buffer";
import net, { isIP } from "node:net";
import { Type } from "typebox";
import { TLSSocket, checkServerIdentity } from "node:tls";
import { isProxylineDispatcher } from "@openclaw/proxyline/dispatcher-brand";
import "typebox/guard";
import { Errors } from "typebox/schema";
//#region packages/gateway-client/src/event-loop-ready.ts
const DEFAULT_MAX_WAIT_MS = 1e4;
const DEFAULT_INTERVAL_MS = 1;
const DEFAULT_DRIFT_THRESHOLD_MS = 200;
const DEFAULT_CONSECUTIVE_READY_CHECKS = 2;
function resolvePositiveInteger(e, t) {
	return Number.isFinite(e) && e !== void 0 ? Math.max(1, Math.floor(e)) : t;
}
/** Waits until timer drift stays low for consecutive checks, or aborts/times out. */
async function waitForEventLoopReady(e = {}) {
	const t = resolveFiniteTimeoutDelayMs(e.maxWaitMs, DEFAULT_MAX_WAIT_MS, { minMs: 0 });
	const n = resolveFiniteTimeoutDelayMs(e.intervalMs, DEFAULT_INTERVAL_MS);
	const r = resolvePositiveInteger(e.driftThresholdMs, DEFAULT_DRIFT_THRESHOLD_MS);
	const i = resolvePositiveInteger(e.consecutiveReadyChecks, DEFAULT_CONSECUTIVE_READY_CHECKS);
	const a = e.signal;
	const o = Date.now();
	let s = 0;
	let c = 0;
	let l = 0;
	return await new Promise((e) => {
		let u = null;
		const finish = (t, n = false) => {
			if (u) {
				clearTimeout(u);
				u = null;
			}
			a?.removeEventListener("abort", onAbort);
			e({
				ready: t,
				elapsedMs: Math.max(0, Date.now() - o),
				maxDriftMs: l,
				checks: c,
				aborted: n
			});
		};
		const onAbort = () => {
			finish(false, true);
		};
		if (a?.aborted) {
			finish(false, true);
			return;
		}
		a?.addEventListener("abort", onAbort, { once: true });
		const scheduleNext = () => {
			const e = Math.max(0, Date.now() - o);
			const a = t - e;
			if (a <= 0) {
				finish(false);
				return;
			}
			const d = Math.min(n, a);
			const f = Date.now();
			u = setTimeout(() => {
				u = null;
				c += 1;
				const e = Math.max(0, Date.now() - f - d);
				l = Math.max(l, e);
				if (e > r) s = 0;
				else s += 1;
				if (s >= i) {
					finish(true);
					return;
				}
				scheduleNext();
			}, d);
		};
		scheduleNext();
	});
}
//#endregion
//#region packages/gateway-client/src/readiness.ts
/** Starts a gateway client only after the supplied readiness probe succeeds. */
async function startGatewayClientWithReadinessWait(e, t, n = {}) {
	let r;
	if (typeof n.timeoutMs === "number" && Number.isFinite(n.timeoutMs)) r = n.timeoutMs;
	else {
		const e = n.clientOptions ?? {};
		r = resolveConnectChallengeTimeoutMs(e.connectChallengeTimeoutMs, {
			env: e.env,
			configuredTimeoutMs: e.preauthHandshakeTimeoutMs
		});
	}
	const i = await e({
		maxWaitMs: r,
		signal: n.signal
	});
	if (i.ready && !i.aborted && n.signal?.aborted !== true) t.start();
	return i;
}
/** Starts a gateway client after the default event-loop readiness probe succeeds. */
async function startGatewayClientWhenEventLoopReady(e, t = {}) {
	return startGatewayClientWithReadinessWait(waitForEventLoopReady, e, t);
}
//#endregion
//#region packages/gateway-protocol/src/client-info.ts
/** Canonical client ids accepted in gateway hello/connect payloads. */
const GATEWAY_CLIENT_IDS = {
	WEBCHAT_UI: "webchat-ui",
	CONTROL_UI: "openclaw-control-ui",
	BROWSER_COPILOT: "openclaw-browser-copilot",
	TUI: "openclaw-tui",
	WEBCHAT: "webchat",
	CLI: "cli",
	GATEWAY_CLIENT: "gateway-client",
	MACOS_APP: "openclaw-macos",
	LINUX_APP: "openclaw-linux",
	IOS_APP: "openclaw-ios",
	WATCHOS_APP: "openclaw-watchos",
	ANDROID_APP: "openclaw-android",
	NODE_HOST: "node-host",
	WORKER: "openclaw-worker",
	TEST: "test",
	FINGERPRINT: "fingerprint",
	PROBE: "openclaw-probe"
};
const GATEWAY_CLIENT_NAMES = GATEWAY_CLIENT_IDS;
/** Coarse modes let policy group clients without matching every product id. */
const GATEWAY_CLIENT_MODES = {
	WEBCHAT: "webchat",
	CLI: "cli",
	UI: "ui",
	BACKEND: "backend",
	NODE: "node",
	WORKER: "worker",
	PROBE: "probe",
	TEST: "test"
};
const GATEWAY_CLIENT_ID_BY_VALUE = new Map(Object.values(GATEWAY_CLIENT_IDS).map((e) => [e, e]));
const GATEWAY_CLIENT_MODE_BY_VALUE = new Map(Object.values(GATEWAY_CLIENT_MODES).map((e) => [e, e]));
//#endregion
//#region packages/gateway-protocol/src/protocol-value-normalization.ts
/** Checks string presence without changing wire-significant whitespace. */
function isNonEmptyProtocolString(e) {
	return typeof e === "string" && e.length > 0;
}
//#endregion
//#region packages/gateway-protocol/src/connect-error-details.ts
/**
* Shared gateway connect-error detail helpers.
*
* These details cross client/server boundaries, so readers normalize untrusted
* payloads before using them in reconnect decisions or user-facing messages.
*/
/** Structured connect-error codes carried in gateway error `details.code`. */
const ConnectErrorDetailCodes = {
	AUTH_REQUIRED: "AUTH_REQUIRED",
	AUTH_UNAUTHORIZED: "AUTH_UNAUTHORIZED",
	AUTH_TOKEN_MISSING: "AUTH_TOKEN_MISSING",
	AUTH_TOKEN_MISMATCH: "AUTH_TOKEN_MISMATCH",
	AUTH_TOKEN_NOT_CONFIGURED: "AUTH_TOKEN_NOT_CONFIGURED",
	AUTH_PASSWORD_MISSING: "AUTH_PASSWORD_MISSING",
	AUTH_PASSWORD_MISMATCH: "AUTH_PASSWORD_MISMATCH",
	AUTH_PASSWORD_NOT_CONFIGURED: "AUTH_PASSWORD_NOT_CONFIGURED",
	AUTH_BOOTSTRAP_TOKEN_INVALID: "AUTH_BOOTSTRAP_TOKEN_INVALID",
	AUTH_DEVICE_TOKEN_MISMATCH: "AUTH_DEVICE_TOKEN_MISMATCH",
	AUTH_SCOPE_MISMATCH: "AUTH_SCOPE_MISMATCH",
	AUTH_RATE_LIMITED: "AUTH_RATE_LIMITED",
	AUTH_TAILSCALE_IDENTITY_MISSING: "AUTH_TAILSCALE_IDENTITY_MISSING",
	AUTH_TAILSCALE_PROXY_MISSING: "AUTH_TAILSCALE_PROXY_MISSING",
	AUTH_TAILSCALE_WHOIS_FAILED: "AUTH_TAILSCALE_WHOIS_FAILED",
	AUTH_TAILSCALE_IDENTITY_MISMATCH: "AUTH_TAILSCALE_IDENTITY_MISMATCH",
	AUTH_IDENTITY_HEADER_REQUIRED: "AUTH_IDENTITY_HEADER_REQUIRED",
	AUTH_VERIFIED_USER_REQUIRED: "AUTH_VERIFIED_USER_REQUIRED",
	AUTHENTICATED_PROFILE_UNAVAILABLE: "AUTHENTICATED_PROFILE_UNAVAILABLE",
	OPERATOR_ACCESS_DENIED: "OPERATOR_ACCESS_DENIED",
	CONTROL_UI_BUILD_MISMATCH: "CONTROL_UI_BUILD_MISMATCH",
	CONTROL_UI_ORIGIN_NOT_ALLOWED: "CONTROL_UI_ORIGIN_NOT_ALLOWED",
	PROTOCOL_MISMATCH: "PROTOCOL_MISMATCH",
	CONTROL_UI_DEVICE_IDENTITY_REQUIRED: "CONTROL_UI_DEVICE_IDENTITY_REQUIRED",
	DEVICE_IDENTITY_REQUIRED: "DEVICE_IDENTITY_REQUIRED",
	DEVICE_AUTH_INVALID: "DEVICE_AUTH_INVALID",
	DEVICE_AUTH_DEVICE_ID_MISMATCH: "DEVICE_AUTH_DEVICE_ID_MISMATCH",
	DEVICE_AUTH_SIGNATURE_EXPIRED: "DEVICE_AUTH_SIGNATURE_EXPIRED",
	DEVICE_AUTH_NONCE_REQUIRED: "DEVICE_AUTH_NONCE_REQUIRED",
	DEVICE_AUTH_NONCE_MISMATCH: "DEVICE_AUTH_NONCE_MISMATCH",
	DEVICE_AUTH_SIGNATURE_INVALID: "DEVICE_AUTH_SIGNATURE_INVALID",
	DEVICE_AUTH_PUBLIC_KEY_INVALID: "DEVICE_AUTH_PUBLIC_KEY_INVALID",
	PAIRING_REQUIRED: "PAIRING_REQUIRED",
	PAIRING_REJECTED: "PAIRING_REJECTED",
	PAIRING_EXPIRED: "PAIRING_EXPIRED",
	CLIENT_VERSION_MISMATCH: "CLIENT_VERSION_MISMATCH"
};
/** Suggested client-side recovery action for structured connect errors. */
const CONNECT_RECOVERY_NEXT_STEP_VALUES = [
	"retry_with_device_token",
	"update_auth_configuration",
	"update_auth_credentials",
	"wait_then_retry",
	"review_auth_configuration"
];
const PAIRING_CONNECT_REQUEST_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const PAIRING_CONNECT_REASON_METADATA = {
	"not-paired": {
		message: "device pairing required",
		requirement: "device is not approved yet",
		remediationHint: "Approve this device from the pending pairing requests.",
		recoveryTitle: "Gateway pairing approval required."
	},
	"role-upgrade": {
		message: "role upgrade pending approval",
		requirement: "device is asking for a higher role than currently approved",
		remediationHint: "Review the requested role upgrade, then approve the pending request.",
		recoveryTitle: "Gateway role upgrade approval required."
	},
	"scope-upgrade": {
		message: "scope upgrade pending approval",
		requirement: "device is asking for more scopes than currently approved",
		remediationHint: "Review the requested scopes, then approve the pending upgrade.",
		recoveryTitle: "Gateway scope upgrade approval required."
	},
	"metadata-upgrade": {
		message: "device metadata change pending approval",
		requirement: "device identity changed and must be re-approved",
		remediationHint: "Review the refreshed device details, then approve the pending request.",
		recoveryTitle: "Gateway device refresh approval required."
	}
};
const AUTH_CONNECT_ERROR_CODES = /* @__PURE__ */ new Map([
	["token_missing", ConnectErrorDetailCodes.AUTH_TOKEN_MISSING],
	["token_mismatch", ConnectErrorDetailCodes.AUTH_TOKEN_MISMATCH],
	["token_missing_config", ConnectErrorDetailCodes.AUTH_TOKEN_NOT_CONFIGURED],
	["password_missing", ConnectErrorDetailCodes.AUTH_PASSWORD_MISSING],
	["password_mismatch", ConnectErrorDetailCodes.AUTH_PASSWORD_MISMATCH],
	["password_missing_config", ConnectErrorDetailCodes.AUTH_PASSWORD_NOT_CONFIGURED],
	["bootstrap_token_invalid", ConnectErrorDetailCodes.AUTH_BOOTSTRAP_TOKEN_INVALID],
	["tailscale_user_missing", ConnectErrorDetailCodes.AUTH_TAILSCALE_IDENTITY_MISSING],
	["tailscale_proxy_missing", ConnectErrorDetailCodes.AUTH_TAILSCALE_PROXY_MISSING],
	["tailscale_whois_failed", ConnectErrorDetailCodes.AUTH_TAILSCALE_WHOIS_FAILED],
	["tailscale_user_mismatch", ConnectErrorDetailCodes.AUTH_TAILSCALE_IDENTITY_MISMATCH],
	["rate_limited", ConnectErrorDetailCodes.AUTH_RATE_LIMITED],
	["device_token_mismatch", ConnectErrorDetailCodes.AUTH_DEVICE_TOKEN_MISMATCH],
	["scope_mismatch", ConnectErrorDetailCodes.AUTH_SCOPE_MISMATCH],
	[void 0, ConnectErrorDetailCodes.AUTH_REQUIRED]
]);
const DEVICE_AUTH_CONNECT_ERROR_CODES = /* @__PURE__ */ new Map([
	["device-id-mismatch", ConnectErrorDetailCodes.DEVICE_AUTH_DEVICE_ID_MISMATCH],
	["device-signature-stale", ConnectErrorDetailCodes.DEVICE_AUTH_SIGNATURE_EXPIRED],
	["device-nonce-missing", ConnectErrorDetailCodes.DEVICE_AUTH_NONCE_REQUIRED],
	["device-nonce-mismatch", ConnectErrorDetailCodes.DEVICE_AUTH_NONCE_MISMATCH],
	["device-signature", ConnectErrorDetailCodes.DEVICE_AUTH_SIGNATURE_INVALID],
	["device-public-key", ConnectErrorDetailCodes.DEVICE_AUTH_PUBLIC_KEY_INVALID]
]);
/** Reads a non-empty detail code from an untrusted error details payload. */
function readConnectErrorDetailCode(e) {
	if (!isRecord(e)) return null;
	return normalizeOptionalString(e.code) ?? null;
}
/** Extracts normalized retry advice from untrusted connect-error details. */
function readConnectErrorRecoveryAdvice(e) {
	if (!isRecord(e)) return {};
	return {
		canRetryWithDeviceToken: typeof e.canRetryWithDeviceToken === "boolean" ? e.canRetryWithDeviceToken : void 0,
		recommendedNextStep: normalizeConnectRecoveryNextStep(e.recommendedNextStep)
	};
}
function normalizeConnectRecoveryNextStep(e) {
	const t = normalizeOptionalString(e) ?? "";
	return CONNECT_RECOVERY_NEXT_STEP_VALUES.find((e) => e === t);
}
function normalizePairingConnectReason(e) {
	const t = normalizeOptionalString(e) ?? "";
	return Object.hasOwn(PAIRING_CONNECT_REASON_METADATA, t) ? t : void 0;
}
/** Normalizes pairing request ids before echoing them in close reasons or UI text. */
function normalizePairingConnectRequestId(e) {
	const t = normalizeOptionalString(e);
	return t && PAIRING_CONNECT_REQUEST_ID_PATTERN.test(t) ? t : void 0;
}
function createPairingConnectErrorDetails(e) {
	return {
		code: ConnectErrorDetailCodes.PAIRING_REQUIRED,
		...e.reason ? { reason: e.reason } : {},
		...e.requestId ? { requestId: e.requestId } : {},
		...e.remediationHint ? { remediationHint: e.remediationHint } : {},
		...e.recommendedNextStep ? { recommendedNextStep: e.recommendedNextStep } : {},
		...e.retryable !== void 0 ? { retryable: e.retryable } : {},
		...e.pauseReconnect !== void 0 ? { pauseReconnect: e.pauseReconnect } : {},
		...e.waitForResolution !== void 0 ? { waitForResolution: e.waitForResolution } : {},
		...e.deviceId ? { deviceId: e.deviceId } : {},
		...e.requestedRole ? { requestedRole: e.requestedRole } : {},
		...e.requestedScopes ? { requestedScopes: e.requestedScopes } : {},
		...e.approvedRoles ? { approvedRoles: e.approvedRoles } : {},
		...e.approvedScopes ? { approvedScopes: e.approvedScopes } : {}
	};
}
function normalizePairingConnectMetadata(e, t) {
	return {
		requestId: normalizePairingConnectRequestId(e.requestId),
		remediationHint: normalizeOptionalString(e.remediationHint) ?? (t ? PAIRING_CONNECT_REASON_METADATA[t].remediationHint : "Approve the pending device request before retrying."),
		deviceId: normalizeOptionalString(e.deviceId),
		requestedRole: normalizeOptionalString(e.requestedRole),
		requestedScopes: normalizeOptionalTrimmedStringList(e.requestedScopes),
		approvedRoles: normalizeOptionalTrimmedStringList(e.approvedRoles),
		approvedScopes: normalizeOptionalTrimmedStringList(e.approvedScopes)
	};
}
/** Reads and backfills pairing-required details from an untrusted details object. */
function readPairingConnectErrorDetails(e) {
	if (readConnectErrorDetailCode(e) !== ConnectErrorDetailCodes.PAIRING_REQUIRED) return null;
	if (!isRecord(e)) return null;
	const t = normalizePairingConnectReason(e.reason);
	return createPairingConnectErrorDetails({
		...normalizePairingConnectMetadata(e, t),
		reason: t,
		recommendedNextStep: normalizeConnectRecoveryNextStep(e.recommendedNextStep),
		retryable: typeof e.retryable === "boolean" ? e.retryable : void 0,
		pauseReconnect: typeof e.pauseReconnect === "boolean" ? e.pauseReconnect : void 0,
		waitForResolution: typeof e.waitForResolution === "boolean" ? e.waitForResolution : void 0
	});
}
/** Formats pairing-required details into the canonical user-facing message. */
function formatConnectPairingRequiredMessage(e) {
	const t = readPairingConnectErrorDetails(e);
	const n = PAIRING_CONNECT_REASON_METADATA[t?.reason ?? "not-paired"].message;
	return t?.requestId ? `${n} (requestId: ${t.requestId})` : n;
}
/** Formats connect errors using structured details before falling back to raw messages. */
function formatConnectErrorMessage(e) {
	const t = readConnectErrorDetailCode(e.details);
	if (t === ConnectErrorDetailCodes.PAIRING_REQUIRED) return formatConnectPairingRequiredMessage(e.details);
	if (t === ConnectErrorDetailCodes.PROTOCOL_MISMATCH) return formatProtocolMismatchMessage(e.message, e.details);
	return normalizeOptionalString(e.message) ?? "gateway request failed";
}
function formatProtocolMismatchMessage(e, t) {
	const n = t;
	const r = asPositiveInteger(n.clientMinProtocol);
	const i = asPositiveInteger(n.clientMaxProtocol);
	const a = asPositiveInteger(n.expectedProtocol);
	const o = asPositiveInteger(n.minimumProbeProtocol);
	const s = [];
	if (r !== void 0 && i !== void 0) s.push(r === i ? `Control UI v${r}` : `Control UI v${r}-v${i}`);
	if (a !== void 0) s.push(`Gateway v${a}`);
	if (o !== void 0) s.push(`connection check min v${o}`);
	const c = normalizeOptionalString(e) ?? "protocol mismatch";
	return s.length > 0 ? `${c}: ${s.join(", ")}` : c;
}
//#endregion
//#region packages/gateway-protocol/src/gateway-error-details.ts
/** Stable discriminants for structured method-level failures. */
const GatewayErrorDetailCodes = {
	CRON_JOB_NOT_FOUND: "CRON_JOB_NOT_FOUND",
	MISSING_SCOPE: "MISSING_SCOPE",
	MCP_APP_VIEW_EXPIRED: "MCP_APP_VIEW_EXPIRED",
	OUTBOUND_DELIVERY_QUEUED: "OUTBOUND_DELIVERY_QUEUED",
	USER_PREFS_LIMIT_EXCEEDED: "USER_PREFS_LIMIT_EXCEEDED",
	SESSION_COMPANION_BUSY: "SESSION_COMPANION_BUSY",
	PROJECT_CLONE_FAILED: "PROJECT_CLONE_FAILED",
	UNKNOWN_AGENT_ID: "UNKNOWN_AGENT_ID",
	WIZARD_NOT_FOUND: "WIZARD_NOT_FOUND",
	SETUP_ADMISSION_BUSY: "SETUP_ADMISSION_BUSY",
	GITHUB_PUBLICATION_SELECTION_REJECTED: "GITHUB_PUBLICATION_SELECTION_REJECTED",
	SESSION_WORKSPACE_RECOVERY_REQUIRED: "SESSION_WORKSPACE_RECOVERY_REQUIRED",
	TASK_WORKTREE_SOURCE_REQUIRED: "TASK_WORKTREE_SOURCE_REQUIRED",
	TASK_HISTORY_PREVIEW_CAPACITY: "TASK_HISTORY_PREVIEW_CAPACITY",
	CLAWHUB_RISK_ACKNOWLEDGEMENT_REQUIRED: "CLAWHUB_RISK_ACKNOWLEDGEMENT_REQUIRED",
	TEMPLATE_REVIEW_REQUIRED: "TEMPLATE_REVIEW_REQUIRED",
	PENDING_INPUT_NOT_RETIRED: "PENDING_INPUT_NOT_RETIRED",
	OPENCLAW_CONFIG_READONLY: "OPENCLAW_CONFIG_READONLY"
};
/** Reads validated missing-scope details from an untrusted protocol payload. */
function readMissingScopeErrorDetails(e) {
	const t = asNullableRecord(e);
	if (t?.code !== GatewayErrorDetailCodes.MISSING_SCOPE) return null;
	const n = typeof t.missingScope === "string" ? t.missingScope.trim() : "";
	const r = Array.isArray(t.requiredScopes) ? t.requiredScopes.map((e) => typeof e === "string" ? e.trim() : "") : [];
	if (!n || r.length === 0 || r.some((e) => !e)) return null;
	return {
		code: GatewayErrorDetailCodes.MISSING_SCOPE,
		missingScope: n,
		requiredScopes: r
	};
}
//#endregion
//#region src/config/gateway-dispatch-config.ts
const GATEWAY_DISPATCH_SHELL_ENV_EXPECTED_KEYS = ["OPENCLAW_GATEWAY_TOKEN", "OPENCLAW_GATEWAY_PASSWORD"];
const GATEWAY_DISPATCH_TOP_LEVEL_KEYS = [
	"agents",
	"database",
	"env",
	"gateway",
	"plugins",
	"secrets",
	"session"
];
function resolveGatewayDispatchConfig(e, t) {
	if (!isRecord(e)) return {};
	const n = {};
	for (const t of GATEWAY_DISPATCH_TOP_LEVEL_KEYS) if (Object.hasOwn(e, t)) n[t] = e[t];
	const { resolvedConfigRaw: r, resolutionFacts: i } = resolveConfigForRead(n, t);
	const a = r;
	if (a.session?.mainKey !== void 0) a.session.mainKey = "main";
	setConfigResolutionFacts(a, i);
	return a;
}
function readRawGatewayDispatchConfig(e = {}) {
	const t = e.env ?? process.env;
	const n = e.configPath ?? resolveConfigPath(t);
	if (!fsSync.existsSync(n)) return {
		config: {},
		configPath: n
	};
	const r = fsSync.readFileSync(n, "utf-8");
	const i = parseJsonWithJson5Fallback(r);
	return {
		config: resolveGatewayDispatchConfig(resolveConfigIncludes(i, n, void 0, { allowedRoots: resolveIncludeRoots(t) }), t),
		configPath: n
	};
}
function readGatewayDispatchConfig(e = {}) {
	return readRawGatewayDispatchConfig(e).config;
}
async function readGatewayDispatchConfigWithShellEnvFallback(e = {}) {
	const t = e.env ?? process.env;
	const n = readRawGatewayDispatchConfig(e);
	const { loadShellEnvFallback: r, resolveShellEnvFallbackTimeoutMs: i, shouldDeferShellEnvFallback: a, shouldEnableShellEnvFallback: o } = await import("./shell-env-C-Fm1H-y.mjs");
	if ((o(t) || n.config.env?.shellEnv?.enabled === true) && !a(t)) {
		if (r({
			env: t,
			expectedKeys: [...GATEWAY_DISPATCH_SHELL_ENV_EXPECTED_KEYS],
			timeoutMs: n.config.env?.shellEnv?.timeoutMs ?? i(t)
		}).length > 0) return readGatewayDispatchConfig({
			...e,
			configPath: path.resolve(n.configPath)
		});
	}
	return n.config;
}
//#endregion
//#region src/sessions/session-row-changes.ts
const listeners = resolveGlobalSet(Symbol.for("openclaw.sessionRowChanges"), "close-and-restart");
const factListeners = resolveGlobalSet(Symbol.for("openclaw.sessionRowFactChanges"), "close-and-restart");
const projectionListeners = resolveGlobalSet(Symbol.for("openclaw.sessionRowProjectionChanges"), "close-and-restart");
const invalidationSources = resolveGlobalSingleton(Symbol.for("openclaw.sessionRowInvalidationSources"), () => /* @__PURE__ */ new WeakMap());
const privateFacts = resolveGlobalSingleton(Symbol.for("openclaw.sessionRowPrivateFacts"), () => /* @__PURE__ */ new WeakMap());
const captures = resolveGlobalSingleton(Symbol.for("openclaw.sessionRowChangeCaptures"), () => /* @__PURE__ */ new WeakMap());
const rowRevision = resolveGlobalSingleton(Symbol.for("openclaw.sessionRowChangeRevision"), () => ({ value: 0 }));
//#endregion
//#region src/config/runtime-snapshot.ts
let runtimeConfigSnapshot = null;
let runtimeConfigCapturedSnapshot = null;
let runtimeConfigSourceSnapshot = null;
function getRuntimeConfigSnapshot(e) {
	if (e?.capture && runtimeConfigSnapshot) return runtimeConfigCapturedSnapshot ??= captureRuntimeConfigWithSource(runtimeConfigSnapshot, runtimeConfigSourceSnapshot ?? runtimeConfigSnapshot);
	return runtimeConfigSnapshot;
}
//#endregion
//#region src/shared/operator-scope-compat.ts
const OPERATOR_ROLE = "operator";
const OPERATOR_ADMIN_SCOPE = "operator.admin";
const OPERATOR_READ_SCOPE = "operator.read";
const OPERATOR_TALK_SCOPE = "operator.talk";
const OPERATOR_WRITE_SCOPE = "operator.write";
const OPERATOR_SESSION_READ_SCOPE = "operator.sessions.read";
const OPERATOR_SESSION_WRITE_SCOPE = "operator.sessions.write";
const OPERATOR_SCOPE_PREFIX = "operator.";
function operatorScopeSatisfied(e, t) {
	if (!e.startsWith(OPERATOR_SCOPE_PREFIX)) return false;
	return t.includes(e) || t.includes(OPERATOR_ADMIN_SCOPE) || (e === OPERATOR_READ_SCOPE || e === OPERATOR_TALK_SCOPE || e === OPERATOR_SESSION_READ_SCOPE || e === OPERATOR_SESSION_WRITE_SCOPE) && t.includes(OPERATOR_WRITE_SCOPE) || e === OPERATOR_SESSION_READ_SCOPE && (t.includes(OPERATOR_READ_SCOPE) || t.includes(OPERATOR_SESSION_WRITE_SCOPE));
}
/** Grants must be canonical; requests retain blank skipping and original error strings. */
function resolveMissingOperatorScope(e, t) {
	for (const n of e) {
		const e = n.trim();
		if (e && !operatorScopeSatisfied(e, t)) return n;
	}
	return null;
}
/** Returns true when a role grant satisfies requested scopes, including operator implications. */
function roleScopesAllow(e) {
	return resolveMissingRequestedScope(e) === null;
}
/** Returns the original first requested scope not covered by the role's allowed scopes. */
function resolveMissingRequestedScope(e) {
	const t = e.role.trim();
	const n = e.allowedScopes.map((e) => e.trim());
	if (t === OPERATOR_ROLE) return resolveMissingOperatorScope(e.requestedScopes, n);
	const r = `${t}.`;
	for (const t of e.requestedScopes) {
		const e = t.trim();
		if (!e) continue;
		if (!e.startsWith(r) || !n.includes(e)) return t;
	}
	return null;
}
//#endregion
//#region src/shared/device-auth.ts
/** Normalize a device-auth role id without changing its case or namespace. */
function normalizeDeviceAuthRole(e) {
	return e.trim();
}
/** Normalize device-auth scopes, dedupe/sort them, and include implied operator scopes. */
function normalizeDeviceAuthScopes(e) {
	const t = new Set(normalizeTrimmedStringList(e));
	if (t.has("operator.admin")) {
		t.add("operator.read");
		t.add("operator.write");
	} else if (t.has("operator.write")) t.add("operator.read");
	return [...t].toSorted();
}
//#endregion
//#region src/plugin-sdk/keyed-async-queue.ts
function enqueueKeyedTask(e) {
	e.hooks?.onEnqueue?.();
	const t = "keys" in e ? e.keys : [e.key];
	const n = "keys" in e ? Promise.allSettled(t.map((t) => e.tails.get(t) ?? Promise.resolve())) : (e.tails.get(e.key) ?? Promise.resolve()).catch(() => void 0);
	const r = e.signal ? racePromiseWithAbortSignal(n, e.signal) : n;
	const i = n.then(() => {
		e.signal?.throwIfAborted();
		return e.task();
	}).finally(() => {
		e.hooks?.onSettle?.();
	});
	const a = i.then(() => void 0, () => void 0);
	for (const n of t) e.tails.set(n, a);
	const cleanup = () => {
		for (const n of t) if (e.tails.get(n) === a) e.tails.delete(n);
	};
	a.then(cleanup, cleanup);
	return e.signal ? r.then(() => i) : i;
}
//#endregion
//#region src/infra/client-credential-async.ts
const queues = resolveGlobalSingleton(Symbol.for("openclaw.clientCredentialOperations"), () => /* @__PURE__ */ new Map());
const runtime = resolveGlobalSingleton(Symbol.for("openclaw.clientCredentialWorker"), () => ({ resources: /* @__PURE__ */ new Map() }), () => closeClientCredentialWorker());
function closeClientCredentialWorker() {
	runtime.closing ??= (async () => {
		await Promise.all(queues.values());
		await runtime.pool?.close();
		runtime.pool = void 0;
		for (const e of runtime.resources.values()) e.unregister();
		runtime.resources.clear();
	})().finally(() => {
		runtime.closing = void 0;
	});
	return runtime.closing;
}
/** Run one bounded off-thread operation, routing to the app when it owns this root. */
async function runClientCredentialOperationAsync(e, t, n = {}) {
	return runClientCredentialTaskAsync(e, t, n);
}
async function runClientCredentialTaskAsync(e, t, n = {}) {
	n.signal?.throwIfAborted();
	n.assertCurrent?.();
	const r = await enqueueKeyedTask({
		tails: queues,
		key: "\0credential-root-resolution",
		task: () => resolveDatabasePathKeyAsync(path.resolve(resolveStateDir(e)))
	});
	n.signal?.throwIfAborted();
	n.assertCurrent?.();
	const i = {
		HOME: e.HOME,
		USERPROFILE: e.USERPROFILE,
		OPENCLAW_PROFILE: e.OPENCLAW_PROFILE,
		OPENCLAW_STATE_DIR: r
	};
	const a = resolveClientCredentialStorePath({ OPENCLAW_STATE_DIR: r });
	const assertCurrent = () => {
		n.signal?.throwIfAborted();
		n.assertCurrent?.();
	};
	assertCurrent();
	return enqueueKeyedTask({
		tails: queues,
		key: r,
		task: async () => {
			const offline = async () => {
				const [{ registerOpenClawAgentDatabaseReadCandidateResource: e }, { hydrateOpenClawStateWorkerError: i, retainOpenClawStateWorkerErrorPayload: o }, { acquireStateDatabaseSchemaLease: s, captureStateDatabaseAccess: c }, { retainSqliteWriteAdmissionService: l }, { createSqliteWorkerOperationAdmission: u }, { WorkerTaskPool: d }] = await Promise.all([
					import("./openclaw-agent-db-resources-BGNiyF8F.mjs"),
					import("./openclaw-state-worker-error-BR8va0Jq.mjs"),
					import("./gateway-state-owner-B8AG222r.mjs"),
					import("./sqlite-transaction-CAW-A99g.mjs"),
					import("./sqlite-worker-operation-admission-fA7iCyWm.mjs"),
					import("./worker-task-pool-CxRJp59U.mjs")
				]);
				assertCurrent();
				if (runtime.closing) throw new Error("Client credential worker is closing.");
				let f = runtime.resources.get(a);
				if (!f) {
					const t = await c(a);
					assertCurrent();
					if (runtime.closing) throw new Error("Client credential worker is closing.");
					f = {
						access: t,
						unregister: e({
							path: a,
							revoke() {
								closeClientCredentialWorker().catch(() => {});
							},
							close: closeClientCredentialWorker
						})
					};
					runtime.resources.set(a, f);
				}
				const p = getOpenClawDatabaseMaintenanceScope();
				const m = await f.access.prepareAccess({ maintenanceScope: p });
				assertCurrent();
				let h;
				const assertAccess = () => {
					assertCurrent();
					p?.assertAdmission();
					m({
						maintenanceScope: p,
						schemaLease: h
					});
				};
				const g = u((e, t) => {
					assertAccess();
					if (!t()) throw new Error("Client credential operation authority expired.");
				});
				g.bindDatabaseAuthority({
					databasePath: a,
					assertRequest: assertCurrent,
					assertAccess,
					acquireSchema() {
						assertAccess();
						const acquire = () => s(a);
						const e = p ? p.run(acquire) : acquire();
						h = e;
						p?.own(e, "shared-resources", () => e.release());
						return e;
					}
				});
				const _ = l([a], () => g.service());
				try {
					runtime.pool ??= new d({
						workerUrl: resolveRuntimeProcessEntrypointUrl("clientCredentials"),
						workerClass: "singleton"
					});
					const e = await runtime.pool.run({
						root: r,
						operation: t,
						admission: g.port
					}, {
						signal: n.signal,
						transferList: (e) => [e.admission]
					});
					assertAccess();
					if (e.kind === "error") {
						const t = /* @__PURE__ */ new Error("Client credential operation failed");
						o(t, e.error);
						throw i(t, { includeOrdinary: true });
					}
					return e;
				} catch (e) {
					throw g.failure ?? e;
				} finally {
					_();
					g.finish();
				}
			};
			const e = getOpenClawDatabaseMaintenanceScope();
			if (e?.ownsSchemaMaintenance) e.assertAdmission();
			else {
				const { requestClientCredentialsFromApp: e } = await import("./client-credential-ipc-CL2BSDKt.mjs");
				assertCurrent();
				const r = await e(i, t.kind === "startup.prepare" ? {
					kind: "identity.read",
					identity_key: "primary"
				} : t, n.signal, assertCurrent);
				assertCurrent();
				if (r) return t.kind === "startup.prepare" ? {
					kind: "preparation",
					state: "ready"
				} : r;
			}
			const o = await offline();
			if (o.kind === "result") return o.result;
			throw new Error("Client credentials are busy; retry after the current owner finishes.");
		}
	});
}
//#endregion
//#region src/infra/device-auth-store.kernel.ts
function deviceAuthEntryFromRow(e) {
	try {
		const t = JSON.parse(e.scopes_json);
		if (!Array.isArray(t)) return null;
		return {
			token: e.token,
			role: e.role,
			scopes: normalizeDeviceAuthScopes(t),
			updatedAtMs: e.updated_at_ms
		};
	} catch {
		return null;
	}
}
function createDeviceAuthEntry(e) {
	return {
		token: e.token,
		role: normalizeDeviceAuthRole(e.role),
		scopes: normalizeDeviceAuthScopes(e.scopes),
		updatedAtMs: e.updatedAtMs ?? Date.now()
	};
}
//#endregion
//#region src/infra/device-auth-store.ts
function captureDeviceAuthOperation(e) {
	const t = { ...e.env ?? process.env };
	const { signal: n, assertCurrent: r } = e;
	const assertActive = () => {
		n?.throwIfAborted();
		r?.();
	};
	assertActive();
	return {
		env: t,
		signal: n,
		assertCurrent: assertActive
	};
}
function tokenKey(e, t) {
	return {
		device_id: e.deviceId,
		role: normalizeDeviceAuthRole(e.role),
		...t === void 0 ? {} : { gateway_scope: t }
	};
}
async function readDeviceAuth(e, t) {
	const n = captureDeviceAuthOperation(e);
	const r = await runClientCredentialOperationAsync(n.env, {
		kind: "token.read",
		key: tokenKey(e, t)
	}, n);
	if (r.kind !== "token") throw new Error("Client credential owner returned an unexpected token result.");
	n.assertCurrent();
	const i = {
		entry: r.token ? deviceAuthEntryFromRow(r.token) : null,
		expectedToken: r.token?.token ?? null
	};
	e.onSnapshot?.(i);
	return i.entry;
}
function loadDeviceAuthToken(e) {
	return readDeviceAuth(e);
}
const loadDeviceAuthTokenReadOnly = loadDeviceAuthToken;
async function storeToken(e, t) {
	const n = captureDeviceAuthOperation(e);
	const r = createDeviceAuthEntry(e);
	const i = await runClientCredentialOperationAsync(n.env, {
		kind: "token.replace",
		key: tokenKey(e, t),
		expectedToken: e.expectedToken,
		token: {
			device_id: e.deviceId,
			role: r.role,
			token: r.token,
			scopes_json: JSON.stringify(r.scopes),
			updated_at_ms: r.updatedAtMs
		}
	}, n);
	if (i.kind !== "changed") throw new Error("Client credential owner returned an unexpected token write result.");
	return i.changed ? r : null;
}
async function clearToken(e, t) {
	const n = captureDeviceAuthOperation(e);
	const r = await runClientCredentialOperationAsync(n.env, {
		kind: "token.remove",
		key: tokenKey(e, t),
		expectedToken: e.expectedToken,
		observedToken: e.observedToken
	}, n);
	if (r.kind !== "changed") throw new Error("Client credential owner returned an unexpected token removal result.");
	return r.changed;
}
function storeDeviceAuthToken(e) {
	return storeToken(e);
}
function clearDeviceAuthToken(e) {
	return clearToken(e);
}
function loadOriginDeviceToken(e) {
	return readDeviceAuth(e, e.gatewayScope);
}
const loadOriginDeviceTokenReadOnly = loadOriginDeviceToken;
function storeOriginDeviceToken(e) {
	return storeToken(e, e.gatewayScope);
}
function clearOriginDeviceToken(e) {
	return clearToken(e, e.gatewayScope);
}
//#endregion
//#region src/infra/device-identity-store-options.ts
/** Resolve once before awaiting work so another caller's environment cannot change the root. */
function resolveDeviceIdentityStore(e = {}) {
	const t = path.resolve(e.path ?? resolveClientCredentialStorePath(e.env ?? process.env));
	if (path.basename(t) !== "credentials.sqlite" || path.basename(path.dirname(t)) !== "client") throw new DeviceIdentityStorageError("Device identity path must be <client-root>/client/credentials.sqlite; pass env.OPENCLAW_STATE_DIR to select the client root.");
	return {
		databasePath: t,
		identityKey: normalizeIdentityKey(e.identityKey)
	};
}
function resolveDeviceIdentityEnvironment(e) {
	const { databasePath: t } = resolveDeviceIdentityStore(e);
	return {
		...e.env ?? process.env,
		OPENCLAW_STATE_DIR: path.dirname(path.dirname(t))
	};
}
//#endregion
//#region src/infra/device-identity-async.ts
const log = createSubsystemLogger("gateway/chat");
/** Resolve private signing material without opening the selected Gateway database. */
async function loadOrCreateDeviceIdentityAsync(e = {}) {
	const { identityKey: t } = resolveDeviceIdentityStore(e);
	const n = resolveDeviceIdentityEnvironment(e);
	const r = identityFromCredentialResult(await runClientCredentialOperationAsync(n, {
		kind: "identity.create",
		identity: storedDeviceIdentityToRow(t, generateStoredDeviceIdentity())
	}));
	if (!r) throw new Error(`Client credential owner did not persist identity "${t}".`);
	return {
		deviceId: r.deviceId,
		publicKeyPem: r.publicKeyPem,
		privateKeyPem: r.privateKeyPem
	};
}
/** Existing-only reads never create a local store or a signing identity. */
async function loadDeviceIdentityIfPresentAsync(e = {}) {
	const { identityKey: t } = resolveDeviceIdentityStore(e);
	const n = identityFromCredentialResult(await runClientCredentialOperationAsync(resolveDeviceIdentityEnvironment(e), {
		kind: "identity.read",
		identity_key: t
	}));
	return n ? {
		deviceId: n.deviceId,
		publicKeyPem: n.publicKeyPem,
		privateKeyPem: n.privateKeyPem
	} : null;
}
//#endregion
//#region src/gateway/websocket-protocol.ts
/** Map the HTTP aliases accepted by WebSocket clients onto their canonical schemes. */
function normalizeWebSocketProtocol(e) {
	return e === "https:" ? "wss:" : e === "http:" ? "ws:" : e;
}
//#endregion
//#region src/gateway/net.ts
function isLoopbackAddress(e) {
	return isLoopbackIpAddress(e);
}
/**
* Returns true if the IP belongs to a private or loopback network range.
* Private ranges: RFC1918, link-local, ULA IPv6, and CGNAT (100.64/10), plus loopback.
* Excludes RFC8215 local-use NAT64: SSRF policy blocks that allocation, but
* Gateway trust decisions cannot infer a private mapped destination from it.
*/
function isPrivateOrLoopbackAddress(e) {
	return isPrivateOrLoopbackIpAddress$1(e) && !isRfc8215LocalUseNat64Ipv6Address(e);
}
/**
* Check if a hostname or IP refers to the local machine.
* Handles: localhost, 127.x.x.x, ::1, [::1], ::ffff:127.x.x.x
* Note: 0.0.0.0 and :: are NOT loopback - they bind to all interfaces.
*/
function isLoopbackHost(e) {
	const t = typeof e === "string" ? parseHostForAddressChecks(e) : null;
	if (!t) return false;
	if (t.isLocalhost) return true;
	return isLoopbackAddress(t.unbracketedHost);
}
function isLoopbackGatewayUrl(e) {
	try {
		const t = new URL(e).hostname.toLowerCase();
		const n = t.startsWith("[") && t.endsWith("]") ? t.slice(1, -1) : t;
		return n === "localhost" || isLoopbackIpAddress(n);
	} catch {
		return false;
	}
}
/**
* Check if a hostname or IP refers to a private or loopback address.
* Handles the same hostname formats as isLoopbackHost, but also accepts
* RFC 1918, link-local, CGNAT, and IPv6 ULA/link-local addresses.
*/
function isPrivateOrLoopbackHost$1(e) {
	const t = typeof e === "string" ? parseHostForAddressChecks(e) : null;
	if (!t) return false;
	if (t.isLocalhost) return true;
	const n = normalizeIpAddress(t.unbracketedHost);
	if (!n || !isPrivateOrLoopbackAddress(n)) return false;
	if (net.isIP(n) === 6) {
		if (n.startsWith("ff")) return false;
		if (n === "::") return false;
	}
	return true;
}
/**
* Security check for WebSocket URLs (CWE-319: Cleartext Transmission of Sensitive Information).
*
* Returns true if the URL is secure for transmitting data:
* - wss:// (TLS) is always secure
* - ws:// is secure for loopback, private IP literals, .local, and Tailnet hosts
* - optional break-glass: other private-DNS ws:// hostnames can be enabled for trusted networks
*
* All other ws:// URLs are considered insecure because both credentials
* AND chat/conversation data would be exposed to network interception.
*/
function isSecureWebSocketUrl$1(e, t) {
	let n;
	try {
		n = new URL(e);
	} catch {
		return false;
	}
	const r = normalizeWebSocketProtocol(n.protocol);
	if (r === "wss:") return true;
	if (r !== "ws:") return false;
	if (isLoopbackHost(n.hostname)) return true;
	if (isTrustedPlaintextWebSocketHost$1(n.hostname)) return true;
	if (t?.allowPrivateWs) {
		const e = n.hostname.startsWith("[") && n.hostname.endsWith("]") ? n.hostname.slice(1, -1) : n.hostname;
		return net.isIP(e) === 0;
	}
	return false;
}
function isTrustedPlaintextWebSocketHost$1(e) {
	if (isPrivateOrLoopbackHost$1(e)) return true;
	const t = normalizeLowercaseStringOrEmpty(e).replace(/\.+$/, "");
	return t.endsWith(".local") || t.endsWith(".ts.net");
}
//#endregion
//#region src/gateway/call-device-auth.ts
var GatewayCredentialsRequiredError = class extends Error {
	constructor(e) {
		super([
			`gateway ${e.method} requires credentials before opening a websocket`,
			"Fix: configure gateway.auth token/password, pair this device, or pass --token/--password.",
			`Config: ${e.configPath}`
		].join("\n"));
		this.name = "GatewayCredentialsRequiredError";
		this.method = e.method;
		this.configPath = e.configPath;
	}
};
var GatewayStoredDeviceAuthUnavailableError = class extends Error {
	constructor(e) {
		super(e);
		this.name = "GatewayStoredDeviceAuthUnavailableError";
	}
};
var GatewayLocalBackendSharedAuthUnavailableError = class extends Error {
	constructor(e) {
		super(e);
		this.name = "GatewayLocalBackendSharedAuthUnavailableError";
	}
};
async function resolveDeviceIdentityForGatewayCall(e) {
	try {
		return e === "read-only" ? await loadDeviceIdentityIfPresentAsync() : await loadOrCreateDeviceIdentityAsync();
	} catch (e) {
		throw new Error("Cannot load device identity. Check access to your OpenClaw state directory and run \"openclaw doctor --fix\", then retry.", { cause: e });
	}
}
async function resolveGatewayCallDeviceAuth(e) {
	const { opts: t } = e;
	const n = isLoopbackGatewayUrl(e.url);
	const r = {
		clientName: t.clientName,
		mode: t.mode,
		requireLocalBackendSharedAuth: t.requireLocalBackendSharedAuth
	};
	if (t.allowLocalBackendAuthNone && e.authMode === "none" && e.isImplicitLocalTarget && n && t.clientName === GATEWAY_CLIENT_NAMES.CLI && t.mode === GATEWAY_CLIENT_MODES.CLI && t.deviceIdentity === void 0 && !t.useStoredDeviceAuth && !t.preparedDeviceAuth && !t.approvalRuntimeToken && !t.agentRuntimeIdentityToken) {
		r.clientName = GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT;
		r.mode = GATEWAY_CLIENT_MODES.BACKEND;
		r.requireLocalBackendSharedAuth = true;
	}
	const i = r.mode ?? GATEWAY_CLIENT_MODES.CLI;
	const a = r.clientName ?? GATEWAY_CLIENT_NAMES.CLI;
	const o = r.requireLocalBackendSharedAuth === true && e.authMode === "none";
	const s = e.authMode === "token" && Boolean(e.token) || e.authMode === "password" && Boolean(e.password);
	const c = i === GATEWAY_CLIENT_MODES.BACKEND && a === GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT && (s || o) && n;
	const l = i === GATEWAY_CLIENT_MODES.CLI && a === GATEWAY_CLIENT_NAMES.CLI && s && n;
	const u = c || l;
	if (r.requireLocalBackendSharedAuth && !u) throw new GatewayLocalBackendSharedAuthUnavailableError("local backend shared auth requires a loopback gateway with token/password credentials or auth mode none");
	if (t.deviceIdentity === void 0 && !u) await t.beforeDeviceIdentityLoad?.();
	return {
		clientOptions: r,
		omitDeviceIdentity: u,
		deviceIdentity: t.deviceIdentity === void 0 ? u ? null : await resolveDeviceIdentityForGatewayCall(t.sharedStateMode) : t.deviceIdentity
	};
}
async function loadStoredOperatorDeviceAuthToken(e, t, n, r = process.env) {
	if (!e) return null;
	try {
		if (t) return await (n === "read-only" ? loadOriginDeviceTokenReadOnly : loadOriginDeviceToken)({
			gatewayScope: t,
			deviceId: e.deviceId,
			role: "operator",
			env: r
		});
		return await (n === "read-only" ? loadDeviceAuthTokenReadOnly : loadDeviceAuthToken)({
			deviceId: e.deviceId,
			role: "operator",
			env: r
		});
	} catch {
		return null;
	}
}
//#endregion
//#region src/gateway/call-required-features.ts
function ensureGatewaySupportsRequiredFeatures(e) {
	const t = (e.required ?? []).map((e) => e.trim()).filter(Boolean);
	if (t.length === 0) return;
	const n = new Set((e.supported ?? []).map((e) => e.trim()).filter(Boolean));
	for (const r of t) if (!n.has(r)) throw new Error(`active gateway does not support required ${e.kind} "${r}" for "${e.attemptedMethod}". Update or restart the active gateway and try again.`);
}
//#endregion
//#region src/config/gateway-public-origin.ts
function resolveGatewayPublicOrigin(e) {
	const t = e?.gateway?.publicOrigin?.trim();
	if (!t) return;
	try {
		const e = new URL(t);
		return e.pathname === "/" && !e.search && !e.hash ? e.origin : void 0;
	} catch {
		return;
	}
}
//#endregion
//#region src/gateway/credential-planner.ts
const trimToUndefined = normalizeOptionalString;
/**
* Like trimToUndefined but also rejects unresolved env var placeholders (e.g. `${VAR}`).
* This prevents literal placeholder strings like `${OPENCLAW_GATEWAY_TOKEN}` from being
* accepted as valid credentials when the referenced env var is missing.
* Note: legitimate credential values containing literal `${UPPER_CASE}` patterns will
* also be rejected, but this is an extremely unlikely edge case.
*/
function trimCredentialToUndefined(e) {
	const t = trimToUndefined(e);
	if (t && containsEnvVarReference(t)) return;
	return t;
}
function createGatewayCredentialPlan(e) {
	const t = e.env ?? process.env;
	const n = e.config.gateway;
	const r = n?.remote;
	const i = e.defaults ?? e.config.secrets?.defaults;
	const a = n?.auth?.mode;
	const o = trimToUndefined(t.OPENCLAW_GATEWAY_TOKEN);
	const s = trimToUndefined(t.OPENCLAW_GATEWAY_PASSWORD);
	function resolveInput(t, n) {
		const r = getConfigResolutionFacts(e.config);
		if (hasUnresolvedConfigPath(e.config, t) || getAuthoredConfigSecretRef(e.config, t)) return {
			path: t,
			configured: true,
			refPath: t,
			hasSecretRef: false
		};
		if (r !== null && typeof n === "string") return {
			path: t,
			configured: Boolean(trimToUndefined(n)),
			value: trimToUndefined(n),
			hasSecretRef: false
		};
		const a = resolveSecretInputRef({
			value: n,
			defaults: i
		}).ref;
		return {
			path: t,
			configured: hasConfiguredSecretInput(n, i),
			value: a ? void 0 : trimToUndefined(n),
			refPath: a ? t : void 0,
			hasSecretRef: a !== null
		};
	}
	const c = resolveInput("gateway.auth.token", n?.auth?.token);
	const l = resolveInput("gateway.auth.password", n?.auth?.password);
	const u = resolveInput("gateway.remote.token", r?.token);
	const d = resolveInput("gateway.remote.password", r?.password);
	const f = a !== "password" && a !== "none" && a !== "trusted-proxy";
	const p = a === "password" || a === "trusted-proxy" || a !== "token" && a !== "none" && !(o || c.configured);
	const m = Boolean(o || c.configured || u.configured);
	const h = a === "password" || a === "trusted-proxy" || a !== "token" && a !== "none" && !m;
	const g = f && (a === "token" || a === void 0 && !(s || l.configured));
	const _ = n?.mode === "remote";
	const v = Boolean(trimToUndefined(r?.url));
	const y = n?.tailscale?.mode === "serve" || n?.tailscale?.mode === "funnel";
	const b = _ || v || y;
	const x = f && !o && !c.configured;
	const S = a !== "trusted-proxy" && !s && !l.configured && h;
	return {
		configuredMode: n?.mode === "remote" ? "remote" : "local",
		authMode: a,
		envToken: o,
		envPassword: s,
		localToken: c,
		localPassword: l,
		remoteToken: u,
		remotePassword: d,
		localTokenCanWin: f,
		localPasswordCanWin: p,
		localTokenSurfaceActive: g,
		tokenCanWin: m,
		passwordCanWin: h,
		remoteMode: _,
		remoteUrlConfigured: v,
		tailscaleRemoteExposure: y,
		remoteConfiguredSurface: b,
		remoteTokenFallbackActive: x,
		remoteTokenActive: b || x,
		remotePasswordFallbackActive: S,
		remotePasswordActive: b || S
	};
}
//#endregion
//#region src/gateway/credentials.ts
/** Trim caller-supplied Gateway credentials without consulting config or environment. */
function resolveExplicitGatewayAuth(e) {
	return {
		token: trimToUndefined(e?.token),
		password: trimToUndefined(e?.password)
	};
}
const GATEWAY_SECRET_REF_UNAVAILABLE_ERROR_CODE = "GATEWAY_SECRET_REF_UNAVAILABLE";
/** Raised when a command path needs Gateway credentials before secret refs were resolved. */
var GatewaySecretRefUnavailableError = class extends Error {
	constructor(e) {
		super([
			`${e} is configured as a secret reference but is unavailable in this command path.`,
			"Fix: set OPENCLAW_GATEWAY_TOKEN/OPENCLAW_GATEWAY_PASSWORD, pass explicit --token/--password,",
			"or run a gateway command path that resolves secret references before credential selection."
		].join("\n"));
		this.code = GATEWAY_SECRET_REF_UNAVAILABLE_ERROR_CODE;
		this.name = "GatewaySecretRefUnavailableError";
		this.path = e;
	}
};
function resolveGatewayCredentialsFromValues(e) {
	const t = e.env ?? process.env;
	const n = trimToUndefined(t.OPENCLAW_GATEWAY_TOKEN);
	const r = trimToUndefined(t.OPENCLAW_GATEWAY_PASSWORD);
	const i = trimCredentialToUndefined(e.configToken);
	const a = trimCredentialToUndefined(e.configPassword);
	const o = e.tokenPrecedence ?? "env-first";
	const s = e.passwordPrecedence ?? "env-first";
	return {
		token: o === "config-first" ? i || n : n || i,
		password: s === "config-first" ? a || r : r || a
	};
}
function resolveLocalGatewayCredentials(e) {
	const { plan: t, localPrecedence: n } = e;
	const resolveCredential = (e, t, r) => {
		const i = e.configured ? e.value : r;
		return n === "config-first" ? e.value || t || (e.configured ? void 0 : r) : t || i;
	};
	const r = resolveCredential(t.localToken, t.envToken, t.remoteToken.value);
	const i = resolveCredential(t.localPassword, t.envPassword, t.authMode === "trusted-proxy" ? void 0 : t.remotePassword.value);
	const a = {
		token: r,
		password: i
	};
	const o = e.plan.authMode === "password" || e.plan.authMode === "trusted-proxy" || e.plan.authMode !== "token" && e.plan.authMode !== "none" && !a.token;
	const s = e.plan.authMode === "token" || e.plan.authMode !== "password" && e.plan.authMode !== "none" && e.plan.authMode !== "trusted-proxy" && !a.password;
	const c = [{
		credential: t.localToken,
		env: t.envToken,
		value: r,
		canWin: s
	}, {
		credential: t.localPassword,
		env: t.envPassword,
		value: i,
		canWin: o
	}].filter(({ credential: e, canWin: t }) => e.refPath && t);
	const l = (n === "config-first" ? c.find(({ credential: e, env: t }) => !e.value && Boolean(t)) : void 0) ?? c.find(({ value: e, env: t }) => !e && !t);
	if (l?.credential.refPath) throw new GatewaySecretRefUnavailableError(l.credential.refPath);
	return a;
}
function resolveGatewayCredentialsFromConfig(e) {
	const t = e.env ?? process.env;
	const n = resolveExplicitGatewayAuth(e.explicitAuth);
	if (n.token || n.password) return n;
	if (trimToUndefined(e.urlOverride)) return e.urlOverrideSource === "env" ? resolveGatewayCredentialsFromValues({ env: t }) : {};
	const r = createGatewayCredentialPlan({
		config: e.cfg,
		env: t
	});
	if ((e.modeOverride ?? r.configuredMode) === "local") return resolveLocalGatewayCredentials({
		plan: r,
		localPrecedence: e.localPrecedence ?? "config-first"
	});
	const i = e.remoteTokenFallback ?? "remote-env-local";
	const a = e.remotePasswordFallback ?? "remote-env-local";
	const o = e.remoteTokenPrecedence ?? "remote-first";
	const s = e.remotePasswordPrecedence ?? "env-first";
	const resolveCredential = (e) => {
		const t = r[`remote${e}`].value;
		if ((e === "Token" ? i : a) === "remote-only") return t;
		const n = r[`env${e}`];
		const c = r[`local${e}`].value;
		return (e === "Token" ? o : s) === "env-first" ? n || t || c : t || n || c;
	};
	const c = resolveCredential("Token");
	const l = resolveCredential("Password");
	const u = i !== "remote-only";
	const d = i === "remote-only" ? void 0 : r.localToken.value;
	const f = a === "remote-only" ? void 0 : r.localPassword.value;
	if (r.remoteToken.refPath && !c && !r.envToken && !d && !l) throw new GatewaySecretRefUnavailableError(r.remoteToken.refPath);
	if (r.remotePassword.refPath && !l && !r.envPassword && !f && !c) throw new GatewaySecretRefUnavailableError(r.remotePassword.refPath);
	if (r.localToken.refPath && u && !c && !l && !r.envToken && !r.remoteToken.value && r.localTokenCanWin) throw new GatewaySecretRefUnavailableError(r.localToken.refPath);
	return {
		token: c,
		password: l
	};
}
//#endregion
//#region packages/session-url-contract/src/session-key.ts
const INCOGNITO_SESSION_RE = /^agent:[^:]+:(?:dashboard|subagent|internal-session-effects):incognito-[^:]+$/u;
/** Classifies process-only agent session keys without consulting runtime registry state. */
function isIncognitoSessionKey(e) {
	const t = e?.trim().toLowerCase();
	return Boolean(t && INCOGNITO_SESSION_RE.test(t));
}
//#endregion
//#region src/gateway/secret-input-paths.ts
/** Canonical Gateway config paths whose values may be plaintext or secret refs. */
const GATEWAY_AUTH_SURFACE_PATHS = [
	"gateway.auth.token",
	"gateway.auth.password",
	"gateway.remote.token",
	"gateway.remote.password"
];
/** Stable scan order for Gateway secret-ref credential selection. */
const ALL_GATEWAY_SECRET_INPUT_PATHS = [...GATEWAY_AUTH_SURFACE_PATHS];
/** Narrow an arbitrary error/config path to one of the supported Gateway secret inputs. */
function isSupportedGatewaySecretInputPath(e) {
	return ALL_GATEWAY_SECRET_INPUT_PATHS.includes(e);
}
/** Read a Gateway secret input without assuming whether it is plaintext, a ref, or absent. */
function readGatewaySecretInputValue(e, t) {
	if (t === "gateway.auth.token") return e.gateway?.auth?.token;
	if (t === "gateway.auth.password") return e.gateway?.auth?.password;
	if (t === "gateway.remote.token") return e.gateway?.remote?.token;
	return e.gateway?.remote?.password;
}
/** Replace one Gateway secret input and consume its pending authored provenance atomically. */
function assignResolvedGatewaySecretInput(e) {
	const { config: t, path: n, value: r } = e;
	const i = n === "gateway.auth.token" || n === "gateway.auth.password" ? t.gateway?.auth : t.gateway?.remote;
	if (i) {
		i[isTokenGatewaySecretInputPath(n) ? "token" : "password"] = r;
		copyConfigResolutionFactsExcept(t, t, [n]);
	}
}
/** Distinguish token paths from password paths for auth-mode precedence checks. */
function isTokenGatewaySecretInputPath(e) {
	return e === "gateway.auth.token" || e === "gateway.remote.token";
}
//#endregion
//#region src/gateway/auth-surface-resolution.ts
function createGatewayCredentialResolver(e) {
	return async (t) => {
		const n = await resolveCanonicalConfiguredSecretInputWithFallback({
			config: e.config,
			env: e.env,
			value: readGatewaySecretInputValue(e.config, t),
			path: t,
			unresolvedReasonStyle: "detailed"
		});
		if (n.unresolvedRefReason) e.diagnostics.push({
			message: n.unresolvedRefReason,
			code: n.unresolvedRefCode
		});
		return n;
	};
}
function withDiagnostics(e, t) {
	return e.length > 0 ? {
		...t,
		diagnostics: e.map(({ message: e }) => e),
		...e.some(({ code: e }) => e === "SECRET_REF_REDACTED_VALUE") ? { warningCode: "SECRET_REF_REDACTED_VALUE" } : {}
	} : t;
}
/** Resolves best-effort credentials for non-mutating local/remote gateway probes. */
async function resolveGatewayProbeSurfaceAuth(e) {
	const t = e.env ?? process.env;
	const n = [];
	const r = createGatewayCredentialResolver({
		config: e.config,
		env: t,
		diagnostics: n
	});
	const i = e.config.gateway?.auth?.mode;
	if (e.surface === "remote") {
		const e = await r("gateway.remote.token");
		const i = e.value ? {
			value: void 0,
			secretRefConfigured: false
		} : await r("gateway.remote.password");
		const a = trimToUndefined(t.OPENCLAW_GATEWAY_TOKEN);
		const o = trimToUndefined(t.OPENCLAW_GATEWAY_PASSWORD);
		const s = Boolean(e.value || i.value);
		const c = !s && n.length === 0;
		return withDiagnostics(n, {
			token: e.value ?? (c ? a : void 0),
			password: i.value ?? (c ? o : void 0),
			...s ? { source: "config" } : c && (a || o) && { source: "env" }
		});
	}
	if (i === "none" || i === "trusted-proxy") return {};
	const a = trimToUndefined(t.OPENCLAW_GATEWAY_TOKEN);
	const o = trimToUndefined(t.OPENCLAW_GATEWAY_PASSWORD);
	if (i === "token" || i === "password") {
		const e = await r(`gateway.auth.${i}`);
		if (e.value) return withDiagnostics(n, {
			[i]: e.value,
			source: "config"
		});
		const t = i === "token" ? a : o;
		return !e.secretRefConfigured && t ? {
			[i]: t,
			source: "env"
		} : withDiagnostics(n, {});
	}
	const s = await r("gateway.auth.token");
	if (s.value) return withDiagnostics(n, {
		token: s.value,
		source: "config"
	});
	if (s.secretRefConfigured) return withDiagnostics(n, {});
	const c = await r("gateway.auth.password");
	if (c.secretRefConfigured) return withDiagnostics(n, c.value ? {
		password: c.value,
		source: "config"
	} : {});
	if (a) return {
		token: a,
		source: "env"
	};
	if (o) return withDiagnostics(n, {
		password: o,
		source: "env"
	});
	return withDiagnostics(n, {
		token: s.value,
		password: c.value,
		...c.value && { source: "config" }
	});
}
/** Resolves credentials for client paths that must either authenticate or explain the failure. */
async function resolveGatewayInteractiveSurfaceAuth(e) {
	const t = e.env ?? process.env;
	const n = createGatewayCredentialResolver({
		config: e.config,
		env: t,
		diagnostics: []
	});
	const r = trimToUndefined(e.explicitAuth?.token);
	const i = trimToUndefined(e.explicitAuth?.password);
	const a = createGatewayCredentialPlan({
		config: e.config,
		env: t
	});
	const o = e.config.gateway?.auth?.mode;
	const s = e.surface === "remote" ? a.remoteToken.hasSecretRef || a.remotePassword.hasSecretRef : a.localTokenCanWin && a.localToken.hasSecretRef || (o === "password" || o === void 0) && a.localPassword.hasSecretRef;
	if ((r || i) && s) return {
		token: r,
		password: i
	};
	const c = e.suppressEnvAuthFallback ? void 0 : trimToUndefined(t.OPENCLAW_GATEWAY_TOKEN);
	const l = e.suppressEnvAuthFallback ? void 0 : trimToUndefined(t.OPENCLAW_GATEWAY_PASSWORD);
	if (e.surface === "remote") {
		const e = r ? {
			value: r,
			secretRefConfigured: false
		} : await n("gateway.remote.token");
		if (e.value && (e.secretRefConfigured || a.remotePassword.hasSecretRef)) return {
			token: e.value,
			password: void 0
		};
		const t = i ? {
			value: i,
			secretRefConfigured: false
		} : await n("gateway.remote.password");
		const o = e.secretRefConfigured || t.secretRefConfigured;
		const s = e.value ?? (o ? void 0 : c);
		const u = i ?? (o ? t.value : l ?? t.value);
		return s || u ? {
			token: s,
			password: u
		} : { failureReason: e.unresolvedRefReason ?? t.unresolvedRefReason ?? "Missing gateway auth credentials." };
	}
	if (o === "none" || o === "trusted-proxy") return {
		token: r ?? c,
		password: i ?? l
	};
	const u = o === "password" || o !== "token" && (Boolean(i ?? l) && !a.localToken.hasSecretRef || a.localPassword.configured && !a.localToken.configured);
	const d = u ? "password" : "token";
	const f = u ? i : r;
	const p = u ? l : c;
	const m = f ? {
		value: f,
		secretRefConfigured: false
	} : await n(`gateway.auth.${d}`);
	const h = m.value ?? (m.secretRefConfigured ? void 0 : p);
	return {
		token: u ? m.secretRefConfigured ? void 0 : r ?? c : h,
		password: u ? h : m.secretRefConfigured ? void 0 : i ?? l,
		failureReason: h ? void 0 : m.unresolvedRefReason ?? `Missing gateway auth ${d}.`
	};
}
//#endregion
//#region packages/gateway-client/src/gateway-origin-scope.ts
function normalizeGatewayScope(e, t) {
	const n = e.trim();
	if (!n) return "default";
	const r = globalThis.location;
	const i = r ? `${r.protocol}//${r.host}${r.pathname || "/"}` : void 0;
	const a = URL.parse(n, i);
	if (!a) return n;
	const o = a.pathname === "/" ? "" : a.pathname.replace(/\/+$/, "") || a.pathname;
	return `${a.protocol}//${a.host}${o}${t ? a.search : ""}`;
}
/** Normalizes the gateway URL scope used for origin-bound device tokens. */
function gatewayOriginScope(e) {
	return normalizeGatewayScope(e, false);
}
//#endregion
//#region src/gateway/connection-details.ts
/** Resolve the forwarded Gateway port independently of the local tunnel port. */
function resolveGatewaySshRemotePort(e, t = e.gateway?.remote?.url) {
	if (e.gateway?.remote?.remotePort !== void 0) return e.gateway.remote.remotePort;
	const n = t?.trim();
	if (n && URL.canParse(n)) {
		const e = new URL(n.replace(/^wss?:/iu, "openclaw-ssh:")).port;
		if (e) return Number(e);
	}
	return resolveGatewayPort(e);
}
/** Select credential ownership independently of an SSH tunnel's reusable local port. */
function resolveGatewayDeviceAuthRoute(e) {
	if (!e.remote) return { bound: false };
	const t = e.url.trim();
	const n = gatewayOriginScope(t);
	if (!URL.canParse(t)) return {
		deviceAuthScope: n,
		bound: false
	};
	const r = new URL(t);
	if (!isLoopbackHost(r.hostname)) return {
		deviceAuthScope: n,
		bound: true
	};
	const i = e.config.gateway?.remote;
	const a = normalizeOptionalString(i?.sshTarget);
	const o = normalizeOptionalString(i?.sshIdentity);
	const s = e.configuredRemote && a && i?.transport !== "direct" && i?.url?.trim() === t ? {
		target: a,
		remotePort: resolveGatewaySshRemotePort(e.config, t),
		...o ? { identity: o } : {},
		...i.sshHostKeyPolicy ? { hostKeyPolicy: i.sshHostKeyPolicy } : {}
	} : void 0;
	const c = e.sshRoute ?? s;
	if (c) {
		const e = {
			...c,
			target: c.target.trim()
		};
		const t = `${e.target}:gateway-port:${e.remotePort}`;
		return {
			deviceAuthScope: `remote:ssh:${createHash("sha256").update(t).digest("hex")}`,
			sshTunnel: e,
			bound: true
		};
	}
	const l = normalizeTlsFingerprint(e.tlsFingerprint);
	if (r.protocol === "wss:" && l) return {
		deviceAuthScope: `remote:tls:${createHash("sha256").update(`${n}:tls-sha256:${l}`).digest("hex")}`,
		bound: true
	};
	return {
		deviceAuthScope: n,
		bound: false
	};
}
/** Redact one Gateway URL before it crosses an operator-visible diagnostic boundary. */
function projectGatewayUrlForDiagnostics(e) {
	return redactSensitiveUrlLikeString(e);
}
/** Build gateway target details and reject unsafe remote plaintext websocket URLs. */
function buildGatewayConnectionDetailsWithResolvers(e = {}, t = {}) {
	const n = e.config ?? t.getRuntimeConfig?.() ?? {};
	const r = e.configPath ?? t.resolveConfigPath?.(process.env) ?? resolveConfigPath(process.env);
	const i = e.localPortOverride === void 0 && n.gateway?.mode === "remote";
	const a = i ? n.gateway?.remote : void 0;
	const o = n.gateway?.tls?.enabled === true;
	const s = e.localPortOverride ?? t.resolveGatewayPort?.(n, process.env) ?? resolveGatewayPort(n);
	const c = n.gateway?.bind ?? "loopback";
	const l = `${o ? "wss" : "ws"}://127.0.0.1:${s}`;
	const u = normalizeOptionalString(e.url);
	const d = normalizeOptionalString(e.serviceTargetUrl);
	const f = u || d || e.ignoreEnvUrlOverride || e.localPortOverride !== void 0 ? void 0 : normalizeOptionalString(process.env.OPENCLAW_GATEWAY_URL);
	const p = u ?? f;
	const m = normalizeOptionalString(a?.url);
	const h = i && !p && !d && !m;
	const g = e.urlSource ?? (u ? "cli" : f ? "env" : void 0);
	const _ = p || d || m || l;
	const v = redactSensitiveUrlLikeString(_);
	const y = p ? g === "env" ? "env OPENCLAW_GATEWAY_URL" : "cli --url" : d ? "service target" : m ? "config gateway.remote.url" : h ? "missing gateway.remote.url (fallback local)" : "local loopback";
	const b = !p && (d || !m) ? `Bind: ${c}` : void 0;
	const x = h ? "Warn: gateway.mode=remote but gateway.remote.url is missing; set gateway.remote.url or switch gateway.mode=local." : void 0;
	const S = process.env.OPENCLAW_ALLOW_INSECURE_PRIVATE_WS === "1";
	if (!isSecureWebSocketUrl$1(_, { allowPrivateWs: S })) throw new Error([
		`SECURITY ERROR: Gateway URL "${v}" uses plaintext ws:// to a non-loopback address.`,
		"Both credentials and chat data would be exposed to network interception.",
		`Source: ${y}`,
		`Config: ${r}`,
		"Fix: Use wss:// for remote gateway URLs.",
		"Safe remote access defaults:",
		"- keep gateway.bind=loopback and use an SSH tunnel (ssh -N -L 18789:127.0.0.1:18789 user@gateway-host)",
		"- or use Tailscale Serve/Funnel for HTTPS remote access",
		S ? void 0 : "Break-glass (trusted private networks only): set OPENCLAW_ALLOW_INSECURE_PRIVATE_WS=1",
		"Doctor: openclaw doctor --fix",
		"Docs: https://docs.openclaw.ai/gateway/remote"
	].join("\n"));
	return {
		url: _,
		urlSource: y,
		bindDetail: b,
		remoteFallbackNote: x,
		message: [
			`Gateway target: ${v}`,
			`Source: ${y}`,
			`Config: ${r}`,
			b,
			x
		].filter(Boolean).join("\n")
	};
}
//#endregion
//#region src/gateway/control-ui-shared.ts
/** Normalizes a Control UI base path to either "" or a leading-slash path without trailing slash. */
function normalizeControlUiBasePath(e) {
	const t = e?.trim() ?? "";
	if (!t || t === "/") return "";
	const n = t.startsWith("/") ? t : `/${t}`;
	return n.endsWith("/") ? n.slice(0, -1) : n;
}
//#endregion
//#region src/secrets/resolve-secret-input-string.ts
/**
* Resolves a config value that may be either an inline string or a SecretRef object.
*
* Gateway and storage callers can override normalization and convert SecretRef resolution errors
* into surface-specific failures without duplicating provider lookup behavior.
*/
async function materializeSecretInput(e) {
	const t = e.normalize ?? normalizeSecretInputString;
	const n = parseSecretRef(e.value, e.config.secrets?.defaults);
	if (!n) return t(e.value);
	let r;
	try {
		const { resolveSecretRefString: t } = await import("./resolve-DU_9nxfS.mjs");
		r = await t(n, {
			config: e.config,
			env: e.env
		});
	} catch (t) {
		if (e.onResolveRefError) return e.onResolveRefError(t, n);
		throw t;
	}
	return t(r);
}
//#endregion
//#region src/gateway/credentials-secret-inputs.ts
async function resolveConfiguredGatewaySecretInput(e) {
	const t = readGatewaySecretInputValue(e.config, e.path);
	const n = resolveConfigSecretRef({
		config: e.config,
		path: e.path,
		value: t,
		defaults: e.config.secrets?.defaults
	});
	const materialize = () => materializeSecretInput({
		config: e.config,
		value: n ?? t,
		env: e.env,
		normalize: trimToUndefined,
		onResolveRefError: (t) => {
			if (isSecretResolutionError(t) && t.code === "SECRET_REF_REDACTED_VALUE") throw t;
			throw new GatewaySecretRefUnavailableError(e.path);
		}
	});
	const r = n?.source === "store" && !getDatabaseEngineSelection() && resolveDatabaseFamilyEngines(e.config).state === "postgres" ? await withDatabaseEngineSelection(await resolveConfiguredDatabaseEngineSelection(e), materialize) : await materialize();
	if (!r) throw new Error(`${e.path} resolved to an empty or non-string value.`);
	return r;
}
async function resolveConfiguredDatabaseEngineSelection(e) {
	const { resolveDatabaseEngineSelection: t } = await import("./config-Wnlt5Ng1.mjs");
	try {
		return await t(e.config, e.env);
	} catch {
		throw new GatewaySecretRefUnavailableError(e.path);
	}
}
function hasConfiguredGatewaySecretRef(e, t) {
	return Boolean(resolveConfigSecretRef({
		config: e,
		path: t,
		value: readGatewaySecretInputValue(e, t),
		defaults: e.secrets?.defaults
	}));
}
function localAuthModeAllowsGatewaySecretInputPath(e) {
	const { authMode: t, path: n } = e;
	if (t === "none") return false;
	if (t === "trusted-proxy") return !isTokenGatewaySecretInputPath(n);
	if (t === "token") return isTokenGatewaySecretInputPath(n);
	if (t === "password") return !isTokenGatewaySecretInputPath(n);
	return true;
}
function canGatewaySecretInputPathWin(e) {
	if (!hasConfiguredGatewaySecretRef(e.config, e.path)) return false;
	const t = e.options.modeOverride ?? (e.config.gateway?.mode === "remote" ? "remote" : "local");
	if (t === "local" && !localAuthModeAllowsGatewaySecretInputPath({
		authMode: e.config.gateway?.auth?.mode,
		path: e.path
	})) return false;
	const n = `__OPENCLAW_GATEWAY_SECRET_REF_PROBE_${e.path.replaceAll(".", "_")}__`;
	const r = cloneConfigWithResolutionFacts(e.config);
	for (const e of ALL_GATEWAY_SECRET_INPUT_PATHS) {
		if (!hasConfiguredGatewaySecretRef(r, e)) continue;
		assignResolvedGatewaySecretInput({
			config: r,
			path: e,
			value: void 0
		});
	}
	assignResolvedGatewaySecretInput({
		config: r,
		path: e.path,
		value: n
	});
	try {
		const i = resolveGatewayCredentialsFromConfig({
			...e.options,
			cfg: r,
			env: e.env
		});
		const a = e.config.gateway?.auth?.mode;
		const o = i.token === n && (t === "local" && a === "token" || !i.password);
		const s = i.password === n && (t === "local" && (a === "password" || a === "trusted-proxy") || !i.token);
		return o || s;
	} catch {
		return false;
	}
}
/** Resolve only secret refs that can win, then select Gateway credentials. */
async function resolveGatewayCredentialsWithSecretInputs(e) {
	const t = resolveExplicitGatewayAuth(e.explicitAuth);
	if (t.token || t.password) return t;
	const n = {
		...e,
		explicitAuth: t
	};
	const r = n.env ?? process.env;
	const i = n.config;
	let a = i;
	const resolvePath = async (e) => {
		const t = await resolveConfiguredGatewaySecretInput({
			config: a,
			path: e,
			env: r
		});
		assignResolvedGatewaySecretInput({
			config: a,
			path: e,
			value: t
		});
	};
	for (const e of ALL_GATEWAY_SECRET_INPUT_PATHS) {
		if (!canGatewaySecretInputPathWin({
			options: n,
			env: r,
			config: a,
			path: e
		})) continue;
		if (a === i) a = cloneConfigWithResolutionFacts(i);
		try {
			await resolvePath(e);
		} catch (e) {
			if (isSecretResolutionError(e) && e.code === "SECRET_REF_REDACTED_VALUE") throw e;
		}
	}
	const o = /* @__PURE__ */ new Set();
	for (;;) try {
		return resolveGatewayCredentialsFromConfig({
			...n,
			cfg: a,
			env: r
		});
	} catch (e) {
		if (!(e instanceof GatewaySecretRefUnavailableError)) throw e;
		const t = e.path;
		if (!isSupportedGatewaySecretInputPath(t) || o.has(t)) throw e;
		if (a === i) a = cloneConfigWithResolutionFacts(i);
		await resolvePath(t);
		o.add(t);
	}
}
//#endregion
//#region packages/net-policy/src/url-protocol.ts
function parseUrl(e) {
	return e instanceof URL ? e : URL.parse(e);
}
function isHttpUrl(e) {
	const t = parseUrl(e);
	return t?.protocol === "http:" || t?.protocol === "https:";
}
function isWebSocketUrl(e) {
	const t = parseUrl(e);
	return t?.protocol === "ws:" || t?.protocol === "wss:";
}
function isWssUrl(e) {
	return parseUrl(e)?.protocol === "wss:";
}
//#endregion
//#region src/gateway/tls-fingerprint.ts
/** Resolve the certificate pin for one already-selected Gateway target. */
async function resolveGatewayConnectionTlsFingerprint(e) {
	const t = e.explicitTlsFingerprint ? requireTlsFingerprint(e.explicitTlsFingerprint) : void 0;
	if (t) return t;
	const n = e.config.gateway?.mode === "remote" && (e.urlSource === "config gateway.remote.url" || e.urlSource === "env OPENCLAW_GATEWAY_URL") ? e.config.gateway.remote?.tlsFingerprint ? requireTlsFingerprint(e.config.gateway.remote.tlsFingerprint) : void 0 : void 0;
	if (n) return n;
	if (!isWssUrl(e.url)) return;
	if (!(e.urlSource === "local loopback" || e.urlSource === "missing gateway.remote.url (fallback local)") || e.config.gateway?.tls?.enabled !== true) return;
	const { inspectGatewayTlsCertificate: r } = await import("./gateway-BjxstsxN.mjs");
	const i = await r(e.config.gateway.tls);
	return i.ok ? i.value.fingerprintSha256 : void 0;
}
//#endregion
//#region src/gateway/client-bootstrap.ts
var GatewayExplicitAuthRequiredError = class extends Error {
	constructor(e) {
		super(e);
		this.name = "GatewayExplicitAuthRequiredError";
	}
};
async function ensureExplicitGatewayAuth(e) {
	if (!e.urlOverride || !e.urlOverrideSource) return;
	if (e.explicitAuth?.token || e.explicitAuth?.password) return;
	if (e.urlOverrideSource === "env" && (e.resolvedAuth?.token || e.resolvedAuth?.password)) return;
	if (e.deviceAuthScope && await e.allowStoredOriginAuth?.(e.deviceAuthScope) === true) return;
	const t = e.urlOverrideSource === "env" ? "Set OPENCLAW_GATEWAY_TOKEN or OPENCLAW_GATEWAY_PASSWORD alongside OPENCLAW_GATEWAY_URL; config credentials are intentionally not reused." : "For the default local or SSH-tunneled Gateway, remove --url to use the configured target.";
	throw new GatewayExplicitAuthRequiredError([
		"gateway url override requires explicit credentials",
		e.errorHint,
		t,
		e.configPath ? `Config: ${e.configPath}` : void 0
	].filter(Boolean).join("\n"));
}
/** Resolve the only URL overrides allowed to displace configured Gateway targets. */
function resolveGatewayUrlOverride(e) {
	const t = trimToUndefined(e.gatewayUrl);
	if (t) return {
		url: t,
		source: "cli"
	};
	if (e.ignoreEnvUrlOverride || e.localPortOverride !== void 0) return {};
	const n = trimToUndefined((e.env ?? process.env).OPENCLAW_GATEWAY_URL);
	return n ? {
		url: n,
		source: "env"
	} : {};
}
/**
* Resolves the URL, auth material, and handshake tuning needed to start a GatewayClient.
*/
async function resolveGatewayClientBootstrap(e) {
	const t = e.env ?? process.env;
	const n = resolveExplicitGatewayAuth(e.explicitAuth);
	const r = resolveGatewayUrlOverride({
		gatewayUrl: e.gatewayUrl,
		env: t,
		ignoreEnvUrlOverride: e.ignoreEnvUrlOverride,
		localPortOverride: e.localPortOverride
	});
	const i = e.buildConnectionDetails ?? buildGatewayConnectionDetailsWithResolvers;
	const a = i({
		config: e.config,
		url: r.url,
		...e.configPath ? { configPath: e.configPath } : {},
		...r.source ? { urlSource: r.source } : {},
		ignoreEnvUrlOverride: true,
		...e.localPortOverride !== void 0 ? { localPortOverride: e.localPortOverride } : {},
		...e.serviceTargetUrl ? { serviceTargetUrl: e.serviceTargetUrl } : {}
	});
	const o = a.urlSource === "cli --url" ? "cli" : a.urlSource === "env OPENCLAW_GATEWAY_URL" ? "env" : void 0;
	const s = r.source ?? o;
	let c;
	if (e.allowConfiguredAuthForExactTarget && s === "cli") {
		if (e.config.gateway?.mode === "remote") {
			const t = trimToUndefined(e.config.gateway.remote?.url);
			if (t && t === a.url) c = {
				authSurface: "remote",
				tlsSource: "config gateway.remote.url"
			};
		} else {
			const t = {
				...e.config.gateway,
				mode: "local"
			};
			delete t.remote;
			const n = i({
				config: {
					...e.config,
					gateway: t
				},
				ignoreEnvUrlOverride: true,
				...e.localPortOverride !== void 0 ? { localPortOverride: e.localPortOverride } : {}
			}).url;
			const r = normalizeControlUiBasePath(e.config.gateway?.controlUi?.basePath ?? "");
			if (`${n}${r}` === a.url) c = {
				authSurface: "local",
				tlsSource: "local loopback"
			};
			else {
				const t = resolveGatewayPublicOrigin(e.config);
				if (t && `${t.replace(/^https:/u, "wss:").replace(/^http:/u, "ws:")}${r}` === a.url) c = { authSurface: "local" };
			}
		}
	}
	const l = c?.tlsSource ?? a.urlSource;
	const u = await resolveGatewayConnectionTlsFingerprint({
		config: e.config,
		url: a.url,
		urlSource: l,
		explicitTlsFingerprint: e.explicitTlsFingerprint
	});
	const d = c?.authSurface ?? e.modeOverride ?? (e.localPortOverride !== void 0 ? "local" : e.config.gateway?.mode === "remote" ? "remote" : "local");
	let f;
	if (e.skipImplicitAuth) f = n;
	else if (s && !c) f = e.suppressEnvAuthFallback ? n : await resolveGatewayCredentialsWithSecretInputs({
		config: e.config,
		explicitAuth: n,
		env: t,
		urlOverride: a.url,
		urlOverrideSource: s,
		modeOverride: e.modeOverride
	});
	else if (e.authPolicy === "probe") f = await resolveGatewayProbeSurfaceAuth({
		config: e.config,
		env: t,
		surface: d
	});
	else if (e.authPolicy === "interactive") f = await resolveGatewayInteractiveSurfaceAuth({
		config: e.config,
		env: t,
		explicitAuth: n,
		suppressEnvAuthFallback: e.suppressEnvAuthFallback,
		surface: d
	});
	else f = await resolveGatewayCredentialsWithSecretInputs({
		config: e.config,
		explicitAuth: n,
		env: t,
		urlOverride: s ? a.url : void 0,
		urlOverrideSource: s,
		modeOverride: d
	});
	const { deviceAuthScope: p, sshTunnel: m } = resolveGatewayDeviceAuthRoute({
		config: e.config,
		url: a.url,
		remote: Boolean(s || a.urlSource === "config gateway.remote.url"),
		configuredRemote: !s && a.urlSource === "config gateway.remote.url" || c?.authSurface === "remote",
		tlsFingerprint: u
	});
	if (e.overrideAuthErrorHint && !c) await ensureExplicitGatewayAuth({
		urlOverride: s ? a.url : void 0,
		urlOverrideSource: s,
		explicitAuth: n,
		resolvedAuth: f,
		deviceAuthScope: p,
		allowStoredOriginAuth: e.allowStoredOriginAuth,
		errorHint: e.overrideAuthErrorHint,
		configPath: e.configPath
	});
	return {
		url: a.url,
		urlSource: a.urlSource,
		connectionDetails: a,
		...s ? { urlOverrideSource: s } : {},
		...p ? { deviceAuthScope: p } : {},
		...m ? { sshTunnel: m } : {},
		...f.failureReason ? { authFailureReason: f.failureReason } : {},
		...u ? { tlsFingerprint: u } : {},
		auth: {
			token: f.token,
			password: f.password
		}
	};
}
//#endregion
//#region packages/gateway-protocol/src/startup-unavailable.ts
/** Structured error reason used while gateway startup sidecars are still initializing. */
const GATEWAY_STARTUP_UNAVAILABLE_REASON = "startup-sidecars";
/** Default retry-after hint sent with startup-unavailable handshake errors. */
const GATEWAY_STARTUP_RETRY_AFTER_MS = 500;
const GATEWAY_STARTUP_RETRY_MIN_MS = 100;
const GATEWAY_STARTUP_RETRY_MAX_MS = 2e3;
function isGatewayStartupUnavailableDetails(e) {
	return typeof e === "object" && e !== null && e.reason === "startup-sidecars";
}
/** Detects the structured retryable error emitted while startup sidecars are pending. */
function isRetryableGatewayStartupUnavailableError(e) {
	if (!e || typeof e !== "object") return false;
	const t = e;
	return (t.gatewayCode ?? t.code) === "UNAVAILABLE" && t.retryable === true && isGatewayStartupUnavailableDetails(t.details);
}
/** Resolves a bounded retry-after delay from a startup-unavailable error. */
function resolveGatewayStartupRetryAfterMs(e) {
	if (!isRetryableGatewayStartupUnavailableError(e)) return null;
	const t = e.retryAfterMs;
	return Math.min(Math.max(Math.floor(typeof t === "number" && Number.isFinite(t) ? t : 500), GATEWAY_STARTUP_RETRY_MIN_MS), GATEWAY_STARTUP_RETRY_MAX_MS);
}
//#endregion
//#region packages/gateway-client/src/client-device-auth.ts
/** Owns pending host storage work for one client across connection generations. */
var GatewayClientDeviceAuth = class {
	constructor(e) {
		this.storage = e;
		this.operations = /* @__PURE__ */ new Set();
	}
	load(e) {
		const load = () => {
			e.signal?.throwIfAborted();
			e.assertCurrent?.();
			return this.track(this.storage.loadDeviceAuthToken(e));
		};
		return this.operations.size > 0 ? this.settle().then(load) : load();
	}
	store(e, t, n) {
		const failed = (e) => {
			const t = toStringifiedError(e);
			let r = false;
			try {
				r = n(t);
			} catch {}
			if (!r) this.unreportedPersistenceFailure ??= t;
			throw t;
		};
		e.signal?.throwIfAborted();
		e.assertCurrent?.();
		const r = this.storage.storeDeviceAuthToken(e);
		return r instanceof Promise ? this.track(r.then(t).catch(failed)) : t();
	}
	clear(e, t, n) {
		const clear = () => {
			if (!n()) return;
			const r = [t.token, t.receiptToken].filter((e) => typeof e === "string");
			const i = [...new Set(r)];
			if (t.token === void 0 && i.length === 0) i.push(void 0);
			const clearToken = (t) => {
				e.signal?.throwIfAborted();
				e.assertCurrent?.();
				const n = this.storage.clearDeviceAuthToken({
					...e,
					...t === void 0 ? {} : { expectedToken: t }
				});
				return n instanceof Promise ? n.then(() => {}) : void 0;
			};
			let a;
			for (const e of i) a = a ? a.then(() => clearToken(e)) : clearToken(e);
			return a;
		};
		return this.track(t.persistence ? t.persistence.then(clear, clear) : clear());
	}
	async settle() {
		await Promise.allSettled(this.operations);
	}
	async drain() {
		await this.settle();
		const e = this.unreportedPersistenceFailure;
		this.unreportedPersistenceFailure = void 0;
		if (e) throw e;
	}
	track(e) {
		if (!(e instanceof Promise)) return e;
		this.operations.add(e);
		e.then(() => this.operations.delete(e), () => this.operations.delete(e));
		return e;
	}
};
//#endregion
//#region packages/gateway-client/src/client-upgrade-error.ts
const MAX_UPGRADE_ERROR_BODY_BYTES = 2048;
const UPGRADE_ERROR_BODY_TIMEOUT_MS = 1e3;
async function readUpgradeErrorBody(e) {
	return await new Promise((t) => {
		const n = [];
		let r = 0;
		let i = false;
		const finish = () => {
			if (i) return;
			i = true;
			clearTimeout(a);
			e.off("data", onData);
			e.off("end", finish);
			e.off("error", finish);
			e.off("aborted", finish);
			t(Buffer.concat(n, r).toString("utf8").replace(/\s+/gu, " ").trim());
		};
		const stop = () => {
			finish();
			e.destroy();
		};
		const onData = (e) => {
			const t = Buffer.isBuffer(e) ? e : Buffer.from(e);
			const i = MAX_UPGRADE_ERROR_BODY_BYTES - r;
			if (i > 0) {
				const e = t.subarray(0, i);
				n.push(e);
				r += e.byteLength;
			}
			if (t.byteLength >= i) stop();
		};
		const a = setTimeout(stop, UPGRADE_ERROR_BODY_TIMEOUT_MS);
		a.unref?.();
		e.on("data", onData);
		e.once("end", finish);
		e.once("error", finish);
		e.once("aborted", finish);
	});
}
//#endregion
//#region packages/gateway-client/src/connect-auth.ts
function selectGatewayConnectAuth(e) {
	const t = normalizeOptionalString(e.token);
	const n = normalizeOptionalString(e.bootstrapToken);
	const r = normalizeOptionalString(e.deviceToken);
	const i = normalizeOptionalString(e.password);
	const a = normalizeOptionalString(e.storedToken);
	const o = {
		storedToken: a,
		storedScopes: e.storedScopes
	};
	if (e.preferBootstrapToken && n) return {
		authBootstrapToken: n,
		signatureToken: n,
		...o
	};
	const s = e.pendingDeviceTokenRetry === true && !r && Boolean(t && a && e.trustedDeviceTokenRetry);
	const c = r ?? (s || !(t || i) && (!n || a) ? a : void 0);
	const l = Boolean(c && !r && a) && c === a;
	const u = t ?? c;
	const d = !t && !c && !i ? n : void 0;
	return {
		authToken: t,
		authBootstrapToken: d,
		authDeviceToken: s ? a : void 0,
		authPassword: i,
		authApprovalRuntimeToken: normalizeOptionalString(e.approvalRuntimeToken),
		authAgentRuntimeIdentityToken: normalizeOptionalString(e.agentRuntimeIdentityToken),
		signatureToken: u ?? d,
		resolvedDeviceToken: c,
		usingStoredDeviceToken: l,
		...o
	};
}
function buildGatewayConnectAuth(e) {
	const t = {
		token: e.authToken,
		bootstrapToken: e.authBootstrapToken,
		deviceToken: e.authDeviceToken ?? e.resolvedDeviceToken,
		password: e.authPassword,
		approvalRuntimeToken: e.authApprovalRuntimeToken,
		agentRuntimeIdentityToken: e.authAgentRuntimeIdentityToken
	};
	return Object.values(t).some(Boolean) ? t : void 0;
}
function resolveGatewayConnectScopes(e) {
	return e.requestedScopes ?? (e.usingStoredDeviceToken && e.storedScopes?.length ? e.storedScopes : [...e.defaultScopes]);
}
function shouldRetryGatewayWithDeviceToken(e) {
	if (e.retryBudgetUsed || e.currentDeviceToken || !e.explicitToken || !e.storedToken || !e.trustedEndpoint) return false;
	const t = readConnectErrorRecoveryAdvice(e.errorDetails);
	return e.canRetryWithDeviceTokenHint === true || t.canRetryWithDeviceToken === true || t.recommendedNextStep === "retry_with_device_token" || readConnectErrorDetailCode(e.errorDetails) === ConnectErrorDetailCodes.AUTH_TOKEN_MISMATCH;
}
//#endregion
//#region packages/gateway-client/src/device-auth.ts
function normalizeDeviceMetadataForAuth(e) {
	if (typeof e !== "string") return "";
	return e.trim().replace(/[A-Z]/g, (e) => String.fromCharCode(e.charCodeAt(0) + 32));
}
function buildDeviceAuthPayloadV3(e) {
	const t = e.scopes.join(",");
	const n = e.token ?? "";
	const r = normalizeDeviceMetadataForAuth(e.platform);
	const i = normalizeDeviceMetadataForAuth(e.deviceFamily);
	return [
		"v3",
		e.deviceId,
		e.clientId,
		e.clientMode,
		e.role,
		t,
		String(e.signedAtMs),
		n,
		e.nonce,
		r,
		i
	].join("|");
}
//#endregion
//#region packages/gateway-client/src/model-catalog-connect.ts
const MODEL_CATALOG_SNAPSHOT = "model-catalog-snapshot";
/** A requested snapshot opts in only after the server advertises its connect field. */
function resolveModelCatalogConnect(e) {
	const t = e.serverCapabilities.includes(MODEL_CATALOG_SNAPSHOT) ? e.modelCatalog : void 0;
	const n = e.caps?.filter((e) => e !== MODEL_CATALOG_SNAPSHOT);
	if (t === void 0) return { caps: n };
	return {
		modelCatalog: t,
		caps: [...n ?? [], MODEL_CATALOG_SNAPSHOT]
	};
}
//#endregion
//#region packages/gateway-client/src/node-protocol.ts
/** Match the shipped v3 node envelope before signing its metadata. */
function resolveNodeProtocolClientMetadata(e, t, n) {
	const r = e.platform ?? t;
	if (!n) return {
		platform: r,
		deviceFamily: e.deviceFamily,
		modelIdentifier: e.modelIdentifier
	};
	return { platform: r === "macos" ? "darwin" : r === "windows" ? "win32" : r };
}
function shouldNegotiateLegacyNodeProtocol(e) {
	if (e.role !== "node" || e.mode !== GATEWAY_CLIENT_MODES.NODE || e.clientName !== GATEWAY_CLIENT_NAMES.NODE_HOST) return false;
	return (e.minProtocol ?? 3) === 3 && (e.maxProtocol ?? 4) === 4;
}
//#endregion
//#region packages/gateway-protocol/src/frame-guards.ts
function isGatewayErrorShape(e) {
	if (!isRecord(e)) return false;
	if (!isNonEmptyProtocolString(e.code) || !isNonEmptyProtocolString(e.message)) return false;
	if (e.retryable !== void 0 && typeof e.retryable !== "boolean") return false;
	return e.retryAfterMs === void 0 || asNonNegativeInteger(e.retryAfterMs) !== void 0;
}
function isGatewayEventFrame(e) {
	if (!isRecord(e) || e.type !== "event" || !isNonEmptyProtocolString(e.event)) return false;
	return e.seq === void 0 || asNonNegativeInteger(e.seq) !== void 0;
}
function isGatewayResponseFrame(e) {
	if (!isRecord(e) || e.type !== "res" || !isNonEmptyProtocolString(e.id) || typeof e.ok !== "boolean") return false;
	return e.error === void 0 || isGatewayErrorShape(e.error);
}
//#endregion
//#region packages/gateway-client/src/event-listeners.ts
/** Subscription identity prevents old frames and disposers from reviving callbacks. */
var GatewayEventListeners = class {
	constructor() {
		this.listeners = /* @__PURE__ */ new Map();
	}
	add(e) {
		const t = this.listeners.get(e) ?? {};
		this.listeners.set(e, t);
		return () => {
			if (this.listeners.get(e) === t) this.listeners.delete(e);
		};
	}
	snapshot() {
		return [...this.listeners];
	}
	isCurrent(e, t) {
		return this.listeners.get(e) === t;
	}
};
//#endregion
//#region packages/gateway-protocol/src/restart-unavailable.ts
/** Structured error reason used while the gateway drains for a restart. */
const GATEWAY_RESTART_UNAVAILABLE_REASON = "gateway-restarting";
/** Structured error reason used while the gateway drains for a suspension. */
const GATEWAY_SUSPEND_UNAVAILABLE_REASON = "gateway-suspending";
/** Identity reads wait for resume, with a bounded probe if that event is missed. */
const GATEWAY_SUSPEND_IDENTITY_RETRY_AFTER_MS = 6e4;
/** Detects the structured retryable error emitted while a restart drain refuses work. */
function isGatewayRestartUnavailableError(e) {
	return hasUnavailableReason(e, GATEWAY_RESTART_UNAVAILABLE_REASON);
}
/** Detects the structured retryable error emitted while suspension refuses work. */
function isGatewaySuspendUnavailableError(e) {
	return hasUnavailableReason(e, GATEWAY_SUSPEND_UNAVAILABLE_REASON);
}
function hasUnavailableReason(e, t) {
	if (!e || typeof e !== "object" || !("details" in e)) return false;
	const n = e.details;
	return typeof n === "object" && n !== null && "reason" in n && n.reason === t;
}
//#endregion
//#region packages/gateway-client/src/protocol-request.ts
const gatewayResponseErrors = /* @__PURE__ */ new WeakSet();
var GatewayProtocolRequestError = class extends Error {
	constructor(e) {
		super(e.message ?? "request failed");
		this.name = "GatewayProtocolRequestError";
		this.code = e.code ?? "UNAVAILABLE";
		this.gatewayCode = this.code;
		this.details = e.details;
		this.retryable = e.retryable === true;
		this.retryAfterMs = e.retryAfterMs;
	}
};
/** Preserve response metadata after custom factories without adding it to error JSON. */
function retainGatewayResponsePayload(e, t) {
	gatewayResponseErrors.add(e);
	Object.defineProperty(e, "responsePayload", {
		value: t,
		enumerable: false,
		configurable: true
	});
}
/** A local transport deadline, distinct from a Gateway's authoritative rejection. */
var GatewayProtocolRequestTimeoutError = class extends Error {
	constructor(e, t = `gateway request timed out after ${e.timeoutMs}ms: ${e.method}`) {
		super(t);
		this.code = "CLIENT_TIMEOUT";
		this.name = "GatewayProtocolRequestTimeoutError";
		this.method = e.method;
		this.timeoutMs = e.timeoutMs;
		this.requestSent = e.requestSent;
	}
};
//#endregion
//#region packages/gateway-client/src/pending-request.ts
/** Owns request deadlines, correlation, settlement, and generation-scoped IDs. */
var GatewayPendingRequests = class {
	constructor(e) {
		this.opts = e;
		this.pending = /* @__PURE__ */ new Map();
		this.requestSequence = 0;
	}
	setSuspensionPhase(e) {
		if (e === "accepting") this.resumeBootstrapRequests();
		else if (e === "preparing" || e === "draining" || e === "prepared") this.pauseBootstrapRequests(void 0, true);
	}
	pauseBootstrapRequests(e = GATEWAY_SUSPEND_IDENTITY_RETRY_AFTER_MS, t = false) {
		const n = this.opts.nowMs();
		const r = resolveSafeTimeoutDelayMs(Number.isFinite(e) && e > 0 ? e : GATEWAY_SUSPEND_IDENTITY_RETRY_AFTER_MS);
		const i = this.bootstrapPause ??= {
			retryAtMs: n,
			revision: 0,
			announced: t
		};
		i.announced ||= t;
		i.revision += 1;
		i.retryAtMs = Math.max(i.retryAtMs, n + r);
		clearTimeout(i.timer);
		i.timer = void 0;
		if (i.announced) return;
		i.timer = setTimeout(() => {
			i.timer = void 0;
			this.drainBootstrapRequests();
		}, resolveSafeTimeoutDelayMs(i.retryAtMs - n));
		i.timer.unref?.();
	}
	resumeBootstrapRequests() {
		clearTimeout(this.bootstrapPause?.timer);
		this.bootstrapPause = void 0;
		this.drainBootstrapRequests();
	}
	drainBootstrapRequests() {
		for (const e of this.pending.values()) if (e.waitingForResume) e.resend?.();
	}
	get hasPending() {
		return this.pending.size > 0;
	}
	get hasUnboundedPending() {
		for (const e of this.pending.values()) if (e.unbounded) return true;
		return false;
	}
	releaseHeldRequests(e) {
		for (const t of this.pending.values()) {
			if (!e()) return;
			const n = t.afterHello;
			t.afterHello = void 0;
			n?.();
		}
	}
	request(e, t, n, r, i = false) {
		let a;
		try {
			this.requestSequence += 1;
			a = `${this.requestSequence}:${this.opts.createRequestId()}`;
		} catch (e) {
			return Promise.reject(toStringifiedError(e));
		}
		const o = r?.timeoutMs === null ? void 0 : r?.timeoutMs ?? this.opts.requestTimeoutMs;
		const s = typeof o === "number" && Number.isFinite(o) ? resolveSafeTimeoutDelayMs(o, { minMs: 0 }) : void 0;
		return new Promise((o, c) => {
			let l;
			let u;
			let d = false;
			let f = false;
			const p = {
				resolve: (e) => o(e),
				reject: c,
				expectFinal: r?.expectFinal === true,
				acceptedNotified: false,
				onAccepted: r?.onAccepted,
				unbounded: s === void 0,
				method: t,
				startedAtMs: this.opts.nowMs(),
				prepareRetry: () => {
					f = false;
					d = false;
					if (r?.signal?.aborted) {
						onAbort();
						return false;
					}
					return true;
				}
			};
			const cleanup = () => {
				clearTimeout(u);
				if (l !== void 0) clearTimeout(l);
				r?.signal?.removeEventListener("abort", onAbort);
				if (this.bootstrapPause?.probe?.pending === p) {
					this.bootstrapPause.probe = void 0;
					this.drainBootstrapRequests();
				}
			};
			const retire = (e) => {
				if (this.pending.get(a) !== p) return false;
				this.pending.delete(a);
				cleanup();
				this.finishTiming(a, p, false, e);
				return true;
			};
			const onAbort = () => {
				if (r?.retainSentResultOnAbort && f) return;
				if (!retire("CLIENT_ABORTED")) return;
				c(this.opts.createRequestAbortError?.(t) ?? /* @__PURE__ */ new Error(`gateway request aborted for ${t}`));
			};
			if (r?.signal?.aborted) {
				c(this.opts.createRequestAbortError?.(t) ?? /* @__PURE__ */ new Error(`gateway request aborted for ${t}`));
				return;
			}
			p.cleanup = cleanup;
			if (s !== void 0) {
				l = setTimeout(() => {
					if (!retire("CLIENT_TIMEOUT")) return;
					c(this.opts.createRequestTimeoutError?.(t, s, d) ?? new GatewayProtocolRequestTimeoutError({
						method: t,
						timeoutMs: s,
						requestSent: d
					}));
				}, s);
				l.unref?.();
			}
			r?.signal?.addEventListener("abort", onAbort, { once: true });
			this.pending.set(a, p);
			try {
				const o = JSON.stringify({
					type: "req",
					id: a,
					method: t,
					params: n
				});
				const send = () => {
					if (this.pending.get(a) !== p || r?.signal?.aborted || s !== void 0 && this.opts.nowMs() - p.startedAtMs >= s) return;
					const t = p.resend ? this.bootstrapPause : void 0;
					if (t && !t.announced && !t.timer && !t.probe) t.probe = {
						pending: p,
						revision: t.revision
					};
					p.waitingForResume = Boolean(t && (t.announced || t.probe?.pending !== p));
					if (p.waitingForResume) return;
					try {
						f = true;
						e.send(o);
						if (this.pending.get(a) !== p) return;
						d = f;
						this.invoke("sent", () => r?.onSent?.(a));
					} catch (e) {
						if (retire("CLIENT_SEND_ERROR")) c(toStringifiedError(e));
					}
				};
				p.retryStartup = (e) => {
					p.resend = send;
					clearTimeout(u);
					u = setTimeout(send, resolveFiniteTimeoutDelayMs(e, GATEWAY_SUSPEND_IDENTITY_RETRY_AFTER_MS));
					u.unref?.();
				};
				if (t === "agent.identity.get" || t === "sessions.subscribe" || t === "sessions.groups.list" || t === "question.list" || t === "sessions.list") p.resend = send;
				if (i) p.afterHello = send;
				else send();
			} catch (e) {
				if (retire("CLIENT_SEND_ERROR")) c(toStringifiedError(e));
			}
		});
	}
	handleResponse(e) {
		const t = this.pending.get(e.id);
		if (!t) return;
		const n = e.payload?.status;
		if (e.ok && t.expectFinal && n === "accepted") {
			if (!t.acceptedNotified) {
				t.acceptedNotified = true;
				this.invoke("accepted", () => t.onAccepted?.(e.payload));
			}
			return;
		}
		const r = e.error?.details;
		if (!e.ok && isRetryableGatewayStartupUnavailableError(e.error) && r !== null && typeof r === "object" && "method" in r && r.method === t.method && !t.acceptedNotified) {
			if (t.prepareRetry()) {
				t.retryStartup?.(e.error?.retryAfterMs);
				if (this.bootstrapPause?.probe?.pending === t && this.bootstrapPause.probe.revision === this.bootstrapPause.revision) this.resumeBootstrapRequests();
			}
			return;
		}
		if (!e.ok && t.resend && !t.acceptedNotified && e.error?.code === "UNAVAILABLE" && e.error.retryable === true && (isGatewaySuspendUnavailableError(e.error) || isGatewayRestartUnavailableError(e.error))) {
			if (!t.prepareRetry()) return;
			if (this.bootstrapPause?.probe?.pending === t) this.bootstrapPause.probe = void 0;
			this.pauseBootstrapRequests(isGatewayRestartUnavailableError(e.error) ? Math.ceil(Math.max(GATEWAY_SUSPEND_IDENTITY_RETRY_AFTER_MS, e.error.retryAfterMs ?? 0) * (1 + Math.random() * .2)) : e.error.retryAfterMs);
			t.waitingForResume = true;
			return;
		}
		this.pending.delete(e.id);
		if (e.ok && this.bootstrapPause?.probe?.pending === t && this.bootstrapPause.probe.revision === this.bootstrapPause.revision) this.resumeBootstrapRequests();
		t.cleanup?.();
		if (e.ok) {
			this.finishTiming(e.id, t, true);
			t.resolve(e.payload);
			return;
		}
		this.finishTiming(e.id, t, false, e.error?.code);
		const i = this.opts.createRequestError?.(e.error ?? {}) ?? new GatewayProtocolRequestError(e.error ?? {});
		retainGatewayResponsePayload(i, e.payload);
		t.reject(i);
	}
	flush(e) {
		clearTimeout(this.bootstrapPause?.timer);
		this.bootstrapPause = void 0;
		const t = this.pending;
		this.pending = /* @__PURE__ */ new Map();
		this.requestSequence = 0;
		for (const [n, r] of t) {
			r.cleanup?.();
			this.finishTiming(n, r, false, "CLIENT_CLOSED");
			r.reject(e);
		}
	}
	finishTiming(e, t, n, r) {
		const i = this.opts.nowMs();
		this.invoke("request timing", () => this.opts.onTiming?.({
			id: e,
			method: t.method,
			ok: n,
			durationMs: Math.max(0, i - t.startedAtMs),
			startedAtMs: t.startedAtMs,
			endedAtMs: i,
			errorCode: r
		}));
	}
	invoke(e, t) {
		try {
			t();
		} catch (t) {
			this.opts.onCallbackError?.(e, t);
		}
	}
};
//#endregion
//#region packages/gateway-client/src/protocol-client.ts
const DEFAULT_CONNECT_FAILURE = Object.freeze({
	closeCode: 1008,
	closeReason: "connect failed"
});
/**
* Browser-safe gateway wire client. Environment adapters own transport and auth
* policy; this class owns the single socket/handshake/reconnect/frame state machine.
*/
var GatewayProtocolClient = class {
	constructor(e) {
		this.opts = e;
		this.socket = null;
		this.listeners = new GatewayEventListeners();
		this.stopped = true;
		this.generation = 0;
		this.connectionAbort = null;
		this.lastSeq = null;
		this.connectNonce = null;
		this.serverCapabilities = [];
		this.connectSent = false;
		this.connectRequestSent = false;
		this.handshakeTimer = null;
		this.reconnectSignal = null;
		this.socketOpened = false;
		this.helloReceived = false;
		this.readyForRequests = false;
		this.connectTiming = null;
		this.reconnectSupervisor = new RetrySupervisor({
			initialMs: e.reconnect.initialMs,
			maxMs: e.reconnect.maxMs,
			factor: e.reconnect.multiplier,
			jitter: 0
		});
		this.requests = new GatewayPendingRequests({
			createRequestId: e.createRequestId,
			createRequestError: e.createRequestError,
			createRequestTimeoutError: e.createRequestTimeoutError,
			createRequestAbortError: e.createRequestAbortError,
			requestTimeoutMs: e.requestTimeoutMs,
			nowMs: () => this.nowMs(),
			onTiming: e.onRequestTiming,
			onCallbackError: e.onCallbackError
		});
	}
	get connected() {
		return this.socket?.isOpen() ?? false;
	}
	get hasPendingRequests() {
		return this.requests.hasPending;
	}
	get connecting() {
		return this.connectSent && !this.helloReceived;
	}
	/** A transport upgrade is in flight; the socket adapter bounds how long it may stay open. */
	get opening() {
		return this.socket !== null && !this.socketOpened;
	}
	get hasUnboundedPendingRequests() {
		return this.requests.hasUnboundedPending;
	}
	start() {
		if (this.socket || this.reconnectSignal) return;
		this.stopped = false;
		this.reconnectSupervisor.cancel();
		this.connect();
	}
	stop() {
		this.stopped = true;
		this.connectionAbort?.abort();
		this.clearHandshakeTimer();
		this.reconnectSignal = null;
		this.reconnectSupervisor.reset();
		const e = this.socket;
		if (e && this.opts.notifyStoppedClose) this.stoppedSocket = {
			socket: e,
			context: this.closeContext()
		};
		this.socket = null;
		this.connectFailure = void 0;
		this.connectTiming = null;
		this.requests.flush(/* @__PURE__ */ new Error("gateway client stopped"));
		e?.close();
	}
	request(e, t, n) {
		const r = this.socket;
		if (!r || this.socketOpened && !r.isOpen()) return Promise.reject(/* @__PURE__ */ new Error("gateway not connected"));
		if (typeof e !== "string" || e.length === 0) return Promise.reject(/* @__PURE__ */ new Error("invalid request frame: method must be a non-empty string"));
		return this.requests.request(r, e, t, n, !this.readyForRequests);
	}
	addEventListener(e) {
		return this.listeners.add(e);
	}
	closeSocket(e, t) {
		this.connectionAbort?.abort();
		this.socket?.close(e, t);
	}
	resetReconnectBackoff(e) {
		this.reconnectSignal = null;
		this.reconnectSupervisor.reset(e);
	}
	recordTiming(e, t, n, r) {
		const i = this.nowMs();
		const a = this.connectTiming;
		if (!a || a.generation !== t) return;
		a.hasChallenge ||= e === "challenge";
		a.usedFallback ||= e === "fallback";
		this.invoke("connect timing", () => this.opts.onTiming?.({
			phase: e,
			generation: t,
			durationMs: Math.max(0, i - a.startedAtMs),
			phaseDurationMs: Math.max(0, i - a.lastAtMs),
			hasChallenge: a.hasChallenge,
			usedFallback: a.usedFallback,
			plan: n,
			detail: r
		}));
		a.lastAtMs = i;
		if (e === "hello" || e === "failed") this.connectTiming = null;
	}
	connect() {
		if (this.stopped) return;
		const e = this.generation + 1;
		this.lastSeq = null;
		this.connectNonce = null;
		this.connectChallengeTs = void 0;
		this.serverCapabilities = [];
		this.connectSent = this.connectRequestSent = false;
		this.socketOpened = false;
		this.helloReceived = false;
		this.readyForRequests = false;
		this.connectFailure = void 0;
		let t;
		try {
			t = this.opts.createSocket({
				open: () => {
					if (!this.isActive(t, e)) return;
					this.socketOpened = true;
					this.recordTiming("socket-open", e);
					if (this.connectNonce) {
						this.sendConnect(t, e);
						return;
					}
					this.clearHandshakeTimer();
					const n = Date.now();
					this.handshakeTimer = setTimeout(() => {
						this.handshakeTimer = null;
						if (!this.isActive(t, e) || this.connectSent || !t.isOpen()) return;
						if (this.opts.handshake.mode === "fallback") {
							this.recordTiming("fallback", e);
							this.sendConnect(t, e);
							return;
						}
						const r = Date.now() - n;
						const i = new Error(this.opts.handshake.timeoutMessage?.(r) ?? `gateway connect challenge timeout after ${r}ms`);
						this.opts.onConnectError?.(i);
						t.close(1008, "connect challenge timeout");
					}, this.opts.handshake.timeoutMs);
					this.handshakeTimer.unref?.();
				},
				message: (n) => this.handleMessage(t, e, n),
				close: (n, r) => {
					if (this.socket !== t) {
						if (this.stoppedSocket?.socket === t) {
							const e = {
								...this.stoppedSocket.context,
								code: n,
								reason: r
							};
							this.stoppedSocket = void 0;
							this.invoke("close", () => this.opts.onClose?.(e, {
								retry: false,
								notify: true
							}));
						}
						return;
					}
					this.socket = null;
					this.connectionAbort?.abort();
					this.clearHandshakeTimer();
					const i = {
						...this.closeContext(),
						code: n,
						reason: r,
						generation: e
					};
					this.connectFailure = void 0;
					const a = this.opts.resolveClose(i);
					this.requests.flush(a.pendingError ?? i.connectFailure?.error ?? /* @__PURE__ */ new Error(`gateway closed (${n}): ${r}`));
					this.invoke("close", () => this.opts.onClose?.(i, a));
					if (a.retry && !this.stopped && !this.socket && !this.reconnectSignal) {
						const e = i.connectFailure?.error;
						const t = e instanceof GatewayProtocolRequestError && e.retryable && e.retryAfterMs !== void 0 && Number.isFinite(e.retryAfterMs) && e.retryAfterMs > 0 ? e.retryAfterMs : void 0;
						this.scheduleReconnect(a.reconnectDelayMs ?? i.connectFailure?.reconnectDelayMs, t);
					}
				},
				error: (n) => {
					if (!this.isActive(t, e) || this.connectSent) return;
					this.connectFailure = { error: n };
					this.opts.onConnectError?.(n);
				}
			});
		} catch (e) {
			const t = toStringifiedError(e);
			this.opts.onSocketFactoryError?.(t);
			this.opts.onConnectError?.(t);
			if (this.opts.rethrowSocketFactoryError?.(t)) {
				if (this.generation > 0 && !this.stopped && !this.socket && !this.reconnectSignal) this.opts.onReconnectStopped?.(t);
				throw t;
			}
			if (this.opts.shouldRetrySocketFactoryError?.(t) && !this.stopped && !this.socket && !this.reconnectSignal) this.scheduleReconnect();
			else if (this.generation > 0 && !this.stopped && !this.socket && !this.reconnectSignal) this.opts.onReconnectStopped?.(t);
			return;
		}
		this.generation = e;
		this.connectionAbort = new AbortController();
		this.socket = t;
		const n = this.nowMs();
		this.connectTiming = {
			generation: e,
			startedAtMs: n,
			lastAtMs: n,
			hasChallenge: false,
			usedFallback: false
		};
	}
	sendConnect(e, t) {
		if (!this.isActive(e, t) || !e.isOpen() || this.connectSent) return;
		this.connectSent = true;
		this.clearHandshakeTimer();
		this.handshakeTimer = startGatewayConnectTimeout(() => {
			if (this.isActive(e, t) && !this.helloReceived) e.close(4e3, "connect timeout");
		});
		let n;
		try {
			n = this.opts.buildConnectPlan({
				nonce: this.connectNonce,
				challengeTs: this.connectChallengeTs,
				serverCapabilities: this.serverCapabilities,
				generation: t,
				...this.connectAuthority(e, t)
			});
		} catch (n) {
			this.handleConnectPlanError(e, t, n);
			return;
		}
		if (n instanceof Promise) {
			n.then((n) => this.sendConnectPlan(e, t, n)).catch((n) => this.handleConnectPlanError(e, t, n));
			return;
		}
		this.sendConnectPlan(e, t, n);
	}
	handleConnectPlanError(e, t, n) {
		if (!this.isConnectCurrent(e, t)) return;
		const r = toStringifiedError(n);
		const i = this.opts.onConnectPlanError?.(r) ?? DEFAULT_CONNECT_FAILURE;
		this.opts.onConnectError?.(i.error ?? r);
		if (i.stop) this.stopped = true;
		e.close(i.closeCode, i.closeReason);
	}
	sendConnectPlan(e, t, n) {
		if (!this.isConnectCurrent(e, t)) return;
		const r = {
			...this.connectAuthority(e, t),
			generation: t,
			nonce: this.connectNonce,
			challengeTs: this.connectChallengeTs,
			plan: n
		};
		this.recordTiming("connect-plan-ready", t, n);
		this.requests.request(e, "connect", this.opts.buildConnectParams(n), { onSent: () => {
			this.connectRequestSent = true;
			this.recordTiming("request-sent", t, n);
		} }).then((i) => {
			if (!this.isConnectCurrent(e, t)) return;
			this.helloReceived = true;
			this.requests.setSuspensionPhase(i.snapshot?.suspension?.phase);
			this.clearHandshakeTimer();
			this.connectFailure = void 0;
			this.reconnectSupervisor.reset();
			this.recordTiming("hello", t, n);
			const publishHello = () => {
				if (!this.isConnectCurrent(e, t)) return;
				this.invoke("hello", () => this.opts.onHello?.(i));
				if (!this.isConnectCurrent(e, t)) return;
				this.requests.releaseHeldRequests(() => this.isConnectCurrent(e, t));
				if (this.isConnectCurrent(e, t)) this.readyForRequests = true;
			};
			const a = this.opts.onConnectHello?.(i, r);
			if (a instanceof Promise) return a.then(publishHello);
			return publishHello();
		}).catch((n) => {
			if (!this.isActive(e, t)) return;
			const i = n instanceof GatewayProtocolRequestError ? n : new GatewayProtocolRequestError({ message: String(n) });
			this.connectFailure = { error: i };
			const a = this.opts.onConnectFailure?.(i, r) ?? DEFAULT_CONNECT_FAILURE;
			const applyFailure = (n) => {
				if (!this.isActive(e, t)) return;
				this.connectFailure = {
					error: i,
					reconnectDelayMs: n.reconnectDelayMs
				};
				if (n.keepOpen) {
					this.clearHandshakeTimer();
					return;
				}
				if (n.stop) this.stopped = true;
				this.connectionAbort?.abort();
				e.close(n.closeCode, n.closeReason);
			};
			if (a instanceof Promise) return a.then(applyFailure);
			return applyFailure(a);
		}).catch((n) => {
			if (!this.isConnectCurrent(e, t)) return;
			this.opts.onConnectError?.(toStringifiedError(n));
			this.closeSocket(DEFAULT_CONNECT_FAILURE.closeCode, DEFAULT_CONNECT_FAILURE.closeReason);
		});
	}
	handleMessage(e, t, n) {
		if (!this.isActive(e, t) || this.connectionAbort?.signal.aborted) return;
		let r;
		try {
			r = JSON.parse(n);
		} catch (e) {
			this.opts.onParseError?.(e);
			return;
		}
		if (isGatewayEventFrame(r)) {
			this.opts.onActivity?.();
			if (r.event === "connect.challenge") {
				const n = r.payload;
				const i = typeof n?.nonce === "string" ? n.nonce.trim() : "";
				if (!i) {
					if (this.opts.handshake.mode === "require-challenge") {
						const t = /* @__PURE__ */ new Error("gateway connect challenge missing nonce");
						this.opts.onConnectError?.(t);
						e.close(1008, "connect challenge missing nonce");
					}
					return;
				}
				this.connectNonce = i;
				this.serverCapabilities = filterStringEntries(n?.capabilities);
				const a = n?.ts;
				this.connectChallengeTs = typeof a === "number" && Number.isSafeInteger(a) && a >= 0 ? a : null;
				this.recordTiming("challenge", t);
				this.sendConnect(e, t);
				return;
			}
			const n = r.seq;
			if (n !== void 0) {
				if (this.lastSeq !== null && n > this.lastSeq + 1) {
					const i = this.lastSeq + 1;
					const a = asRecord(r.payload).state;
					if (r.event === "chat" && (a === "final" || a === "error" || a === "aborted")) this.dispatchEvent(e, t, r);
					if (!this.isActive(e, t) || this.connectionAbort?.signal.aborted) return;
					this.invoke("gap", () => this.opts.onGap?.({
						expected: i,
						received: n
					}));
					if (this.isActive(e, t) && !this.connectionAbort?.signal.aborted) this.closeSocket(4e3, "event sequence gap");
					return;
				}
				this.lastSeq = n;
			}
			this.dispatchEvent(e, t, r);
			return;
		}
		if (!isGatewayResponseFrame(r)) return;
		this.opts.onActivity?.();
		this.requests.handleResponse(r);
	}
	dispatchEvent(e, t, n) {
		const r = this.listeners.snapshot();
		if (n.event === "gateway.suspension") this.requests.setSuspensionPhase(asRecord(n.payload).phase);
		else if (n.event === "shutdown" && typeof asRecord(n.payload).restartExpectedMs === "number") this.requests.setSuspensionPhase("draining");
		this.invoke("event", () => this.opts.onEvent?.(n));
		for (const [i, a] of r) {
			if (!this.isActive(e, t) || this.connectionAbort?.signal.aborted) return;
			if (this.listeners.isCurrent(i, a)) this.invoke("event listener", () => i(n));
		}
	}
	scheduleReconnect(e, t = 0) {
		if (e !== void 0) this.reconnectSupervisor.nextDelayOverrideMs = e;
		const n = this.reconnectSupervisor.next();
		if (!n) return;
		this.reconnectSignal = n.signal;
		let r = e;
		if (r === void 0) {
			const e = Math.max(n.delayMs, t);
			const i = Math.max(this.opts.reconnect.maxMs, Math.min(Number.MAX_VALUE, t * 1.2));
			const a = Math.max(t, Math.min(e, i / 1.2));
			const o = Math.min(e * 1.2, i);
			r = Math.ceil(a + Math.random() * (o - a));
		}
		r = resolveSleepDelayMs(r);
		sleepWithAbort(r, n.signal).then(() => {
			if (this.reconnectSignal !== n.signal) return;
			this.reconnectSignal = null;
			this.invoke("reconnect", () => this.connect());
		}, () => {
			if (this.reconnectSignal === n.signal) this.reconnectSignal = null;
		});
		this.invoke("reconnect scheduled", () => this.opts.onReconnectScheduled?.(r, n.signal));
	}
	closeContext() {
		return {
			generation: this.generation,
			socketOpened: this.socketOpened,
			helloReceived: this.helloReceived,
			connectRequestSent: this.connectRequestSent,
			connectFailure: this.connectFailure
		};
	}
	isConnectCurrent(e, t) {
		return this.isActive(e, t) && e.isOpen() && !this.connectionAbort?.signal.aborted;
	}
	connectAuthority(e, t) {
		const n = this.connectionAbort?.signal;
		if (!n) throw new Error("gateway connection authority is unavailable");
		return {
			signal: n,
			assertCurrent: () => {
				n.throwIfAborted();
				if (!this.isConnectCurrent(e, t)) throw new Error("gateway connection retired");
			}
		};
	}
	isActive(e, t) {
		return !this.stopped && this.socket === e && this.generation === t;
	}
	nowMs() {
		return this.opts.nowMs?.() ?? Date.now();
	}
	clearHandshakeTimer() {
		this.handshakeTimer = clearGatewayConnectTimeout(this.handshakeTimer);
	}
	invoke(e, t) {
		try {
			t();
		} catch (t) {
			this.opts.onCallbackError?.(e, t);
		}
	}
};
//#endregion
//#region packages/gateway-client/src/reconnect-policy.ts
const NON_RECOVERABLE_AUTH_ERRORS = /* @__PURE__ */ new Set([
	ConnectErrorDetailCodes.AUTH_TOKEN_MISSING,
	ConnectErrorDetailCodes.AUTH_BOOTSTRAP_TOKEN_INVALID,
	ConnectErrorDetailCodes.AUTH_PASSWORD_MISSING,
	ConnectErrorDetailCodes.AUTH_PASSWORD_MISMATCH,
	ConnectErrorDetailCodes.AUTH_RATE_LIMITED,
	ConnectErrorDetailCodes.AUTH_DEVICE_TOKEN_MISMATCH,
	ConnectErrorDetailCodes.AUTH_SCOPE_MISMATCH,
	ConnectErrorDetailCodes.AUTH_IDENTITY_HEADER_REQUIRED,
	ConnectErrorDetailCodes.AUTH_VERIFIED_USER_REQUIRED,
	ConnectErrorDetailCodes.CONTROL_UI_BUILD_MISMATCH,
	ConnectErrorDetailCodes.PAIRING_REQUIRED,
	ConnectErrorDetailCodes.PAIRING_REJECTED,
	ConnectErrorDetailCodes.PAIRING_EXPIRED,
	ConnectErrorDetailCodes.CONTROL_UI_DEVICE_IDENTITY_REQUIRED,
	ConnectErrorDetailCodes.DEVICE_IDENTITY_REQUIRED
]);
function shouldPauseGatewayReconnect(e) {
	const t = readConnectErrorDetailCode(e.details);
	if (!t) return false;
	const n = readPairingConnectErrorDetails(e.details);
	if (t === ConnectErrorDetailCodes.PAIRING_REQUIRED && (n?.pauseReconnect === false || n?.recommendedNextStep === "wait_then_retry")) return false;
	if (t === ConnectErrorDetailCodes.AUTH_TOKEN_MISMATCH) return e.tokenMismatchIsTerminal === true && !e.deviceTokenRetryPending;
	if (t === ConnectErrorDetailCodes.AUTH_IDENTITY_HEADER_REQUIRED) return !e.deviceTokenRetryPending;
	return NON_RECOVERABLE_AUTH_ERRORS.has(t) || e.protocolMismatchIsTerminal === true && t === ConnectErrorDetailCodes.PROTOCOL_MISMATCH || e.clientVersionMismatchIsTerminal === true && t === ConnectErrorDetailCodes.CLIENT_VERSION_MISMATCH;
}
//#endregion
//#region packages/gateway-client/src/request-error.ts
var GatewayClientRequestError = class extends GatewayProtocolRequestError {
	constructor(e) {
		super({
			...e,
			message: formatConnectErrorMessage({
				message: e.message,
				details: e.details
			})
		});
		this.name = "GatewayClientRequestError";
	}
};
var GatewayClientRequestTimeoutError = class extends GatewayProtocolRequestTimeoutError {
	constructor(e) {
		super(e, `gateway request timeout for ${e.method}`);
		this.name = "GatewayClientRequestTimeoutError";
	}
};
const GATEWAY_CONNECT_ASSEMBLY_ERROR = Symbol("gateway.connectAssemblyError");
function markGatewayConnectAssemblyError(e) {
	Object.defineProperty(e, GATEWAY_CONNECT_ASSEMBLY_ERROR, {
		configurable: true,
		value: true
	});
	return e;
}
function isGatewayConnectAssemblyError(e) {
	return e instanceof Error && e[GATEWAY_CONNECT_ASSEMBLY_ERROR] === true;
}
//#endregion
//#region packages/gateway-client/src/websocket-data.ts
function rawDataToString(e, t = "utf8") {
	if (Array.isArray(e)) return Buffer$1.concat(e).toString(t);
	return e instanceof ArrayBuffer ? Buffer$1.from(e).toString(t) : e.toString(t);
}
//#endregion
//#region packages/gateway-client/src/websocket-transport.ts
const PRIVATE_OR_LOOPBACK_IPV4_RANGES = /* @__PURE__ */ new Set([
	"loopback",
	"private",
	"linkLocal",
	"carrierGradeNat"
]);
const PRIVATE_OR_LOOPBACK_IPV6_RANGES = /* @__PURE__ */ new Set([
	"loopback",
	"linkLocal",
	"uniqueLocal",
	"deprecatedSiteLocal"
]);
function isPrivateOrLoopbackIpAddress(e) {
	return (e.kind() === "ipv4" ? PRIVATE_OR_LOOPBACK_IPV4_RANGES : PRIVATE_OR_LOOPBACK_IPV6_RANGES).has(e.range());
}
function isGatewayLoopbackHost(e) {
	const t = parseHostForAddressChecks(e);
	return Boolean(t && (t.isLocalhost || isLoopbackIpAddress(t.unbracketedHost)));
}
function isPrivateOrLoopbackHost(e) {
	const t = parseHostForAddressChecks(e);
	if (!t) return false;
	if (t.isLocalhost) return true;
	const n = parseGatewayIpAddress(t.unbracketedHost);
	return Boolean(n && isPrivateOrLoopbackIpAddress(n));
}
function isTrustedPlaintextWebSocketHost(e) {
	if (isPrivateOrLoopbackHost(e)) return true;
	const t = e.toLowerCase().trim().replace(/\.+$/, "");
	return t.endsWith(".local") || t.endsWith(".ts.net");
}
function isSecureWebSocketUrl(e, t) {
	const n = URL.parse(e);
	if (!n) return false;
	const r = n.protocol === "https:" ? "wss:" : n.protocol === "http:" ? "ws:" : n.protocol;
	if (r === "wss:") return true;
	if (r !== "ws:") return false;
	if (isTrustedPlaintextWebSocketHost(n.hostname)) return true;
	if (t?.allowPrivateWs === true) {
		const e = n.hostname.startsWith("[") && n.hostname.endsWith("]") ? n.hostname.slice(1, -1) : n.hostname;
		return parseGatewayIpAddress(e) === void 0;
	}
	return false;
}
var GatewayWebSocketTransportConfigurationError = class extends Error {};
var GatewayWebSocketTlsPinError = class extends Error {};
function resolveGatewayWebSocketTransport(e) {
	const t = isWssUrl(e.url);
	if (e.tlsFingerprint && !t) throw new GatewayWebSocketTransportConfigurationError("gateway tls fingerprint requires wss:// gateway url");
	const n = (e.env ?? process.env).OPENCLAW_ALLOW_INSECURE_PRIVATE_WS === "1";
	if (!isSecureWebSocketUrl(e.url, { allowPrivateWs: n })) {
		const t = URL.parse(e.url)?.hostname || e.url;
		throw new GatewayWebSocketTransportConfigurationError(`SECURITY ERROR: Cannot connect to "${t}" over plaintext ws://. Both credentials and chat data would be exposed to network interception. Use wss:// for remote URLs. Safe defaults: keep gateway.bind=loopback and connect via SSH tunnel (ssh -N -L 18789:127.0.0.1:18789 user@gateway-host), or use Tailscale Serve/Funnel. ` + (n ? "" : "Break-glass (trusted private networks only): set OPENCLAW_ALLOW_INSECURE_PRIVATE_WS=1. ") + "Run `openclaw doctor --fix` for guidance.");
	}
	const r = e.normalizeTlsFingerprint ?? normalizeTlsFingerprint;
	const i = e.tlsFingerprint ? normalizeTlsFingerprint(e.tlsFingerprint) : void 0;
	if (e.tlsFingerprint && !i) throw new GatewayWebSocketTransportConfigurationError("gateway tls fingerprint must be a SHA-256 fingerprint");
	const a = { ...e.options };
	if (t && e.tlsServerName) {
		const t = e.tlsServerName;
		a.servername = isIP(t) ? "" : t;
		a.checkServerIdentity = (e, n) => checkServerIdentity(t, n);
	}
	if (t && i) applyGatewayWebSocketTlsPin(a, i, r);
	return { options: a };
}
function applyGatewayWebSocketTlsPin(e, t, n = normalizeTlsFingerprint) {
	e.rejectUnauthorized = false;
	const r = { ...e.headers };
	const i = Object.entries(r).filter(([e]) => e.toLowerCase() === "expect");
	for (const [e] of i) delete r[e];
	e.headers = r;
	e.finishRequest = (e) => {
		e.once("socket", (r) => {
			if (!(r instanceof TLSSocket)) {
				e.destroy(new GatewayWebSocketTlsPinError("gateway tls fingerprint unavailable"));
				return;
			}
			const validatePin = () => {
				if (e.destroyed) return;
				const a = normalizeTlsFingerprint(r.getPeerCertificate()?.fingerprint256);
				const o = a ? n(a) : "";
				if (!o || o !== n(t)) {
					e.destroy(new GatewayWebSocketTlsPinError(o ? "gateway tls fingerprint mismatch" : "gateway tls fingerprint unavailable"));
					return;
				}
				for (const [t, n] of i) if (n !== void 0) e.setHeader(t, n);
				e.end();
			};
			if (r.secureConnecting) {
				r.once("secureConnect", validatePin);
				e.once("close", () => r.off("secureConnect", validatePin));
			} else validatePin();
		});
	};
}
//#endregion
//#region packages/gateway-client/src/websocket.ts
const require = createRequire(import.meta.url);
const wsPackageRoot = path.dirname(require.resolve("ws/package.json"));
const WebSocket = require(path.join(wsPackageRoot, "lib/websocket.js"));
const WebSocketServer = require(path.join(wsPackageRoot, "lib/websocket-server.js"));
const createWebSocketStream = require(path.join(wsPackageRoot, "lib/stream.js"));
//#endregion
//#region packages/gateway-client/src/client.ts
const DEFAULT_HOST_DEPS = {
	loadOrCreateDeviceIdentity: () => void 0,
	signDevicePayload: () => {
		throw new Error("GatewayClient device signature dependency is not configured");
	},
	publicKeyRawBase64UrlFromPem: () => {
		throw new Error("GatewayClient public key dependency is not configured");
	},
	loadDeviceAuthToken: () => null,
	storeDeviceAuthToken: () => {},
	clearDeviceAuthToken: () => {},
	beforeConnect: () => {},
	registerGatewayLoopbackBypass: () => void 0,
	logDebug: () => {},
	logError: () => {},
	redactForLog: (e) => e,
	normalizeTlsFingerprint
};
function resolveHostDeps(e) {
	return Object.fromEntries(Object.entries(DEFAULT_HOST_DEPS).map(([t, n]) => [t, e?.[t] ?? n]));
}
const DEFAULT_GATEWAY_CLIENT_URL = "ws://127.0.0.1:18789";
const DEFAULT_CLIENT_VERSION = "0.0.0";
var GatewayClientTransportPolicyError = class extends GatewayWebSocketTransportConfigurationError {};
const FORCE_STOP_TERMINATE_GRACE_MS = 250;
const STOP_AND_WAIT_TIMEOUT_MS = 1e3;
const MAX_SUPPRESSED_TRANSIENT_PRE_HELLO_CLEAN_CLOSES = 1;
var GatewayClient$1 = class {
	constructor(e) {
		this.ws = null;
		this.stopped = false;
		this.useLegacyNodeProtocolEnvelope = false;
		this.nodeProtocolTransitionPending = false;
		this.pendingDeviceTokenRetry = false;
		this.deviceTokenRetryBudgetUsed = false;
		this.approvalRuntimeTokenCompatibilityDisabled = false;
		this.approvalRuntimeTokenRetryBudgetUsed = false;
		this.lastTick = null;
		this.tickIntervalMs = 3e4;
		this.tickTimer = null;
		this.pendingStop = null;
		this.transportValidated = false;
		this.suppressedTransientPreHelloCleanCloses = 0;
		this.deps = resolveHostDeps(e.hostDeps);
		this.deviceAuth = new GatewayClientDeviceAuth(this.deps);
		this.opts = {
			...e,
			deviceIdentity: e.deviceIdentity === null ? void 0 : e.deviceIdentity ?? this.deps.loadOrCreateDeviceIdentity()
		};
		this.requestTimeoutMs = typeof e.requestTimeoutMs === "number" && Number.isFinite(e.requestTimeoutMs) ? e.requestTimeoutMs : DEFAULT_GATEWAY_REQUEST_TIMEOUT_MS;
		const t = resolveConnectChallengeTimeoutMs(this.opts.connectChallengeTimeoutMs, {
			env: this.opts.env,
			configuredTimeoutMs: this.opts.preauthHandshakeTimeoutMs
		});
		this.protocol = new GatewayProtocolClient({
			createSocket: (e) => this.createSocket(e),
			createRequestId: randomUUID,
			createRequestError: (e) => new GatewayClientRequestError(e),
			createRequestTimeoutError: (e, t, n) => new GatewayClientRequestTimeoutError({
				method: e,
				timeoutMs: t,
				requestSent: n
			}),
			createRequestAbortError: (e) => createAbortError(`gateway request aborted for ${e}`),
			buildConnectPlan: ({ nonce: e, challengeTs: t, serverCapabilities: n, generation: r, ...i }) => {
				if (!e) throw new Error("gateway connect challenge missing nonce");
				if (this.opts.deviceIdentity && t == null) throw new Error("gateway connect challenge timestamp invalid");
				const a = this.opts.role ?? "operator";
				const assemble = (o) => {
					i.assertCurrent();
					const s = t ?? Date.now();
					const c = selectGatewayConnectAuth({
						token: this.opts.token,
						bootstrapToken: this.opts.bootstrapToken,
						preferBootstrapToken: this.opts.preferBootstrapToken,
						deviceToken: this.opts.deviceToken,
						password: this.opts.password,
						approvalRuntimeToken: this.approvalRuntimeTokenCompatibilityDisabled ? void 0 : this.opts.approvalRuntimeToken,
						agentRuntimeIdentityToken: this.opts.agentRuntimeIdentityToken,
						storedToken: o?.token,
						storedScopes: o?.scopes,
						pendingDeviceTokenRetry: this.pendingDeviceTokenRetry,
						trustedDeviceTokenRetry: this.isTrustedDeviceRetryEndpoint()
					});
					const { authDeviceToken: l, authApprovalRuntimeToken: u, authAgentRuntimeIdentityToken: d, signatureToken: f, resolvedDeviceToken: p, storedToken: m, storedScopes: h, usingStoredDeviceToken: g } = c;
					if (this.pendingDeviceTokenRetry && l) this.pendingDeviceTokenRetry = false;
					const _ = buildGatewayConnectAuth(c);
					const v = resolveGatewayConnectScopes({
						requestedScopes: this.opts.scopes,
						usingStoredDeviceToken: g,
						storedScopes: h,
						defaultScopes: ["operator.admin"]
					});
					const y = this.opts.mode ?? GATEWAY_CLIENT_MODES.BACKEND;
					const b = this.opts.clientName ?? GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT;
					const x = a === "node" && y === GATEWAY_CLIENT_MODES.NODE && b === GATEWAY_CLIENT_NAMES.NODE_HOST;
					const S = shouldNegotiateLegacyNodeProtocol(this.opts);
					const C = x && (this.useLegacyNodeProtocolEnvelope || this.opts.maxProtocol === 3 && (this.opts.minProtocol ?? 3) <= 3);
					const w = C ? 3 : S ? 4 : this.opts.minProtocol ?? (y === GATEWAY_CLIENT_MODES.PROBE ? 3 : a === "node" && y === GATEWAY_CLIENT_MODES.NODE ? 3 : 4);
					const T = C ? 3 : S ? 4 : this.opts.maxProtocol ?? 4;
					const { platform: E, deviceFamily: D, modelIdentifier: O } = resolveNodeProtocolClientMetadata(this.opts, process.platform, C);
					const k = {
						minProtocol: w,
						maxProtocol: T,
						client: {
							id: b,
							displayName: this.opts.clientDisplayName,
							version: this.opts.clientVersion ?? DEFAULT_CLIENT_VERSION,
							buildId: this.opts.clientBuildId,
							platform: E,
							deviceFamily: D,
							modelIdentifier: O,
							mode: y,
							instanceId: this.opts.instanceId
						},
						...resolveModelCatalogConnect({
							caps: Array.isArray(this.opts.caps) ? this.opts.caps : [],
							modelCatalog: C ? void 0 : this.opts.modelCatalog,
							serverCapabilities: n
						}),
						commands: Array.isArray(this.opts.commands) ? this.opts.commands : void 0,
						computerUse: C ? void 0 : this.opts.computerUse,
						workerRuns: C ? void 0 : this.opts.workerRuns,
						permissions: this.opts.permissions && typeof this.opts.permissions === "object" ? this.opts.permissions : void 0,
						pathEnv: this.opts.pathEnv,
						auth: _,
						role: a,
						scopes: v,
						device: void 0
					};
					if (this.opts.deviceIdentity) {
						const t = buildDeviceAuthPayloadV3({
							deviceId: this.opts.deviceIdentity.deviceId,
							clientId: this.opts.clientName ?? GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT,
							clientMode: y,
							role: a,
							scopes: v,
							signedAtMs: s,
							token: f ?? null,
							nonce: e,
							platform: E,
							deviceFamily: D
						});
						const n = this.deps.signDevicePayload(this.opts.deviceIdentity.privateKeyPem, t);
						k.device = {
							id: this.opts.deviceIdentity.deviceId,
							publicKey: this.deps.publicKeyRawBase64UrlFromPem(this.opts.deviceIdentity.publicKeyPem),
							signature: n,
							signedAt: s,
							nonce: e
						};
					}
					const A = {
						params: k,
						authApprovalRuntimeToken: u,
						authAgentRuntimeIdentityToken: d,
						resolvedDeviceToken: p,
						storedScopes: h,
						storedToken: m,
						usingStoredDeviceToken: g
					};
					this.connectionStoredToken = {
						generation: r,
						token: A.storedToken ?? null
					};
					return A;
				};
				const o = this.opts.deviceIdentity ? this.deviceAuth.load({
					deviceId: this.opts.deviceIdentity.deviceId,
					role: a,
					env: this.opts.env,
					...i
				}) : null;
				return o instanceof Promise ? o.then(assemble) : assemble(o);
			},
			buildConnectParams: (e) => e.params,
			onConnectPlanError: (e) => {
				this.stopped = true;
				const t = markGatewayConnectAssemblyError(e);
				const n = `gateway connect failed: ${formatGatewayClientErrorForLog(e)}`;
				if (this.opts.mode === GATEWAY_CLIENT_MODES.PROBE || isGatewayClientStoppedError(e)) this.logDebug(n);
				else this.logError(n);
				return {
					closeCode: 1008,
					closeReason: "connect failed",
					stop: true,
					error: t
				};
			},
			onConnectHello: (e, t) => {
				const n = t.plan;
				t.assertCurrent();
				const r = this.opts.role ?? "operator";
				const i = e.auth;
				const a = this.connectionStoredToken;
				const persisted = () => {
					if (i?.deviceToken && (i.role ?? r) === r && a) a.token = i.deviceToken;
					if (this.opts.preferBootstrapToken) {
						this.opts.token = void 0;
						this.opts.bootstrapToken = void 0;
						this.opts.password = void 0;
						this.opts.preferBootstrapToken = false;
					}
				};
				let o = void 0;
				if (i?.deviceToken && this.opts.deviceIdentity) {
					const e = i.role ?? r;
					const t = e === r && i.deviceToken === n.storedToken ? n.storedScopes ?? i.scopes ?? [] : i.scopes ?? [];
					if (e === r && a) a.receiptToken = i.deviceToken;
					o = this.deviceAuth.store({
						deviceId: this.opts.deviceIdentity.deviceId,
						role: e,
						token: i.deviceToken,
						scopes: t,
						env: this.opts.env,
						...e === r ? { expectedToken: n.storedToken ?? null } : {}
					}, persisted, (e) => {
						n.persistenceFailed = true;
						const t = this.notifyConnectError(e);
						this.logError(`gateway device token persistence failed: ${formatGatewayClientErrorForLog(e)}`);
						return t;
					});
					if (a && o instanceof Promise) a.persistence = o;
				} else persisted();
				const complete = () => {
					if (t.signal.aborted || !this.protocol.connected) return;
					t.assertCurrent();
					const n = this.useLegacyNodeProtocolEnvelope && shouldNegotiateLegacyNodeProtocol(this.opts) && e.protocol > 3;
					if (n) this.useLegacyNodeProtocolEnvelope = false;
					this.nodeProtocolTransitionPending = false;
					this.pendingDeviceTokenRetry = false;
					this.deviceTokenRetryBudgetUsed = false;
					this.suppressedTransientPreHelloCleanCloses = 0;
					this.tickIntervalMs = typeof e.policy?.tickIntervalMs === "number" ? e.policy.tickIntervalMs : 3e4;
					if (n) {
						this.protocol.resetReconnectBackoff(250);
						this.protocol.closeSocket(1012, "gateway protocol upgraded");
						return;
					}
					this.lastTick = Date.now();
					this.startTickWatch();
				};
				return o instanceof Promise ? o.then(complete) : complete();
			},
			onHello: (e) => {
				this.opts.onHelloOk?.(e);
			},
			onConnectFailure: (e, t) => {
				const n = t.plan;
				if (n.persistenceFailed) return {
					closeCode: 1008,
					closeReason: "connect failed"
				};
				const r = e instanceof GatewayClientRequestError ? readConnectErrorDetailCode(e.details) : null;
				const i = this.opts.deviceIdentity && n.usingStoredDeviceToken && r === ConnectErrorDetailCodes.AUTH_DEVICE_TOKEN_MISMATCH ? this.clearDeviceToken(this.opts.deviceIdentity.deviceId, { token: n.storedToken }) : void 0;
				const a = this.resolveConnectRequestFailure(e, n);
				return i instanceof Promise ? i.then(() => a) : a;
			},
			resolveClose: (e) => this.resolveClose(e),
			onClose: (e, t) => {
				clearInterval(this.tickTimer ?? void 0);
				this.tickTimer = null;
				if (t.notify) this.opts.onClose?.(e.code, e.reason, this.closeInfo(e));
			},
			notifyStoppedClose: true,
			onConnectError: (e) => this.notifyConnectError(e),
			onReconnectStopped: (e) => this.notifyReconnectPaused({
				code: 1008,
				reason: e.message,
				detailCode: null
			}),
			onParseError: (e) => this.logDebug(`gateway client parse error: ${formatGatewayClientErrorForLog(e)}`),
			onEvent: (e) => this.opts.onEvent?.(e),
			onGap: (e) => this.opts.onGap?.(e),
			onRequestTiming: (e) => this.opts.onRequestTiming?.(e),
			onActivity: () => {
				this.lastTick = Date.now();
			},
			onCallbackError: (e, t) => this.logDebug(`gateway client ${e === "hello" ? "hello-ok" : e === "gap" ? "event" : e} handler error: ${formatGatewayClientErrorForLog(t)}`),
			handshake: {
				mode: "require-challenge",
				timeoutMs: t,
				timeoutMessage: (e) => `gateway connect challenge timeout (waited ${e}ms, limit ${t}ms)`
			},
			reconnect: {
				initialMs: 1e3,
				multiplier: 2,
				maxMs: 3e4
			},
			requestTimeoutMs: this.requestTimeoutMs,
			shouldRetrySocketFactoryError: (e) => !(e instanceof GatewayWebSocketTransportConfigurationError) && !(e instanceof SyntaxError) && !(e instanceof TypeError) && !(e instanceof RangeError),
			rethrowSocketFactoryError: (e) => e instanceof GatewayClientTransportPolicyError
		});
	}
	/** Current transport state, including CLOSING before the close callback fires.
	* This is not authentication or readiness evidence on its own. */
	get connected() {
		return !this.stopped && this.protocol.connected;
	}
	getConnectionMetadata() {
		return {
			clientName: this.opts.clientName,
			hasDeviceIdentity: Boolean(this.opts.deviceIdentity),
			mode: this.opts.mode,
			preauthHandshakeTimeoutMs: this.opts.preauthHandshakeTimeoutMs
		};
	}
	updateNodeManifest(e) {
		this.opts = {
			...this.opts,
			caps: [...e.caps],
			commands: [...e.commands],
			computerUse: e.computerUse === void 0 ? void 0 : structuredClone(e.computerUse),
			workerRuns: e.workerRuns ? structuredClone(e.workerRuns) : void 0
		};
		if (!this.stopped) this.protocol.closeSocket(1012, "node manifest changed");
	}
	start() {
		if (this.stopped) return;
		this.protocol.start();
	}
	createSocket(e) {
		const t = this.opts.url ?? DEFAULT_GATEWAY_CLIENT_URL;
		const n = this.opts.edgeAuthHeaders;
		const r = n && Object.keys(n).length > 0 ? n : void 0;
		if (r && new URL(t).protocol !== "wss:") throw new GatewayWebSocketTransportConfigurationError("edge auth headers require a wss:// Gateway URL");
		const i = resolvePreauthHandshakeTimeoutMs({
			env: this.opts.env,
			configuredTimeoutMs: this.opts.preauthHandshakeTimeoutMs
		});
		const a = resolveGatewayWebSocketTransport({
			url: t,
			tlsFingerprint: this.opts.tlsFingerprint,
			tlsServerName: this.opts.tlsServerName,
			env: this.opts.env,
			normalizeTlsFingerprint: this.deps.normalizeTlsFingerprint,
			options: {
				maxPayload: 26214400,
				handshakeTimeout: i,
				...this.opts.origin ? { origin: this.opts.origin } : {},
				...r ? {
					followRedirects: false,
					headers: r
				} : {}
			}
		});
		this.deps.beforeConnect();
		let o;
		let s;
		try {
			try {
				s = this.deps.registerGatewayLoopbackBypass(t);
				this.opts.assertConnectionCurrent?.();
			} catch (e) {
				throw new GatewayClientTransportPolicyError(e instanceof Error ? e.message : String(e));
			}
			o = new WebSocket(t, a.options);
			o.binaryType = "nodebuffer";
		} finally {
			s?.();
		}
		this.ws = o;
		this.transportValidated = false;
		let c;
		o.on("open", () => {
			this.transportValidated = true;
			e.open();
		});
		o.on("message", (t) => e.message(rawDataToString(t)));
		o.on("close", (t, n) => {
			const r = n.toString();
			if (this.ws === o) this.ws = null;
			this.resolvePendingStop(o);
			e.close(t, r);
		});
		o.on("unexpected-response", (t, n) => {
			readUpgradeErrorBody(n).then((r) => {
				const i = n.statusCode;
				const a = safeParseJsonRecord(r)?.error;
				const s = isRecord(a) ? a : void 0;
				const l = n.headers.location;
				const u = l ? redactSensitiveUrlLikeString(Array.isArray(l) ? l[0] ?? "" : l) : void 0;
				const d = `gateway rejected websocket upgrade (HTTP ${i ?? "unknown"})${r ? `: ${r}` : ""}`;
				c = new GatewayClientRequestError({
					code: "UNAVAILABLE",
					message: d,
					retryable: true,
					details: {
						reason: "websocket-upgrade-rejected",
						...i === void 0 ? {} : { httpStatus: i },
						...u ? { location: u } : {},
						...typeof s?.type === "string" ? {
							gatewayErrorType: s.type,
							...typeof s.message === "string" ? { gatewayErrorMessage: s.message } : {}
						} : {}
					}
				});
				e.error(c);
				t.destroy();
				o.close();
			});
		});
		o.on("error", (t) => {
			if (c) return;
			if (t.message === "Opening handshake has timed out") Object.assign(t, { code: "ETIMEDOUT" });
			this.logDebug(`gateway client error: ${formatGatewayClientErrorForLog(t)}`);
			e.error(t instanceof Error ? t : new Error(String(t)));
		});
		return {
			isOpen: () => o.readyState === WebSocket.OPEN,
			send: (e) => {
				this.opts.assertConnectionCurrent?.();
				o.send(e);
			},
			close: (e, t) => o.close(e, t)
		};
	}
	stop() {
		this.beginStop();
	}
	async stopAndWait(e) {
		const t = this.beginStop();
		const n = e?.timeoutMs === void 0 ? STOP_AND_WAIT_TIMEOUT_MS : resolveSafeTimeoutDelayMs(e.timeoutMs);
		try {
			await raceWithTimeout(Promise.resolve(t), n, () => {
				throw new Error(`gateway client stop timed out after ${n}ms`);
			}, { ref: false });
		} finally {
			await this.deviceAuth.drain();
		}
	}
	beginStop() {
		this.stopped = true;
		this.pendingDeviceTokenRetry = false;
		this.deviceTokenRetryBudgetUsed = false;
		clearInterval(this.tickTimer ?? void 0);
		this.tickTimer = null;
		if (this.pendingStop) return this.pendingStop.promise;
		const e = this.ws;
		this.ws = null;
		if (e) {
			let resolve = () => {};
			const t = {
				ws: e,
				promise: new Promise((e) => {
					resolve = e;
				}),
				resolve
			};
			this.pendingStop = t;
			const n = setTimeout(() => {
				try {
					e.terminate();
				} finally {
					this.resolvePendingStop(e);
				}
			}, FORCE_STOP_TERMINATE_GRACE_MS);
			n.unref?.();
			t.terminateTimer = n;
			if (this.protocol.connecting) {
				const e = /* @__PURE__ */ new Error("gateway client stopped");
				this.notifyConnectError(e);
				this.logDebug(`gateway connect failed: ${formatGatewayClientErrorForLog(e)}`);
			}
			this.protocol.stop();
			return t.promise;
		}
		this.protocol.stop();
		return null;
	}
	resolvePendingStop(e) {
		if (this.pendingStop?.ws !== e) return;
		const { resolve: t, terminateTimer: n } = this.pendingStop;
		if (n) clearTimeout(n);
		this.pendingStop = null;
		t();
	}
	logDebug(e) {
		this.deps.logDebug(this.deps.redactForLog(e));
	}
	logError(e) {
		this.deps.logError(this.deps.redactForLog(e));
	}
	shouldRetryWithAlternateNodeProtocol(e) {
		if (!shouldNegotiateLegacyNodeProtocol(this.opts) || !(e instanceof GatewayClientRequestError)) return false;
		const t = readConnectErrorDetailCode(e.details);
		return e.details?.expectedProtocol === (this.useLegacyNodeProtocolEnvelope ? 4 : 3) && (t === ConnectErrorDetailCodes.PROTOCOL_MISMATCH || normalizeLowercaseStringOrEmpty(e.message).includes("protocol mismatch"));
	}
	resolveConnectRequestFailure(e, t) {
		if (this.shouldRetryWithAlternateNodeProtocol(e)) {
			const e = !this.nodeProtocolTransitionPending;
			this.useLegacyNodeProtocolEnvelope = !this.useLegacyNodeProtocolEnvelope;
			this.nodeProtocolTransitionPending = true;
			if (e) this.protocol.resetReconnectBackoff(250);
			this.logDebug(this.useLegacyNodeProtocolEnvelope ? `gateway rejected protocol v${4}; retrying node host with protocol v${3}` : `gateway rejected protocol v${3}; retrying node host with protocol v${4}`);
			return {
				closeCode: 1008,
				closeReason: "connect retry"
			};
		}
		this.nodeProtocolTransitionPending = false;
		const n = e instanceof GatewayClientRequestError ? readConnectErrorDetailCode(e.details) : null;
		if (shouldRetryGatewayWithDeviceToken({
			retryBudgetUsed: this.deviceTokenRetryBudgetUsed,
			currentDeviceToken: t.resolvedDeviceToken,
			explicitToken: this.opts.token?.trim() || void 0,
			storedToken: t.storedToken,
			trustedEndpoint: this.isTrustedDeviceRetryEndpoint(),
			errorDetails: e instanceof GatewayClientRequestError ? e.details : void 0
		})) {
			this.pendingDeviceTokenRetry = true;
			this.deviceTokenRetryBudgetUsed = true;
			this.protocol.resetReconnectBackoff(250);
		}
		const r = resolveGatewayStartupRetryAfterMs(e);
		if (r !== null) {
			this.logDebug(`gateway connect failed: ${formatGatewayClientErrorForLog(e)}`);
			return {
				closeCode: 1013,
				closeReason: "gateway starting",
				reconnectDelayMs: r
			};
		}
		if (t.authAgentRuntimeIdentityToken && this.isUnsupportedConnectAuthField(e, "agentruntimeidentitytoken")) {
			const e = /* @__PURE__ */ new Error("gateway rejected required agent runtime identity auth field; refusing to retry without it");
			this.stopped = true;
			this.notifyConnectError(e);
			this.logError(`gateway connect failed: ${e.message}`);
			return {
				closeCode: 1008,
				closeReason: "connect failed",
				stop: true
			};
		}
		if (!this.approvalRuntimeTokenRetryBudgetUsed && t.authApprovalRuntimeToken && this.isUnsupportedConnectAuthField(e, "approvalruntimetoken")) {
			this.approvalRuntimeTokenCompatibilityDisabled = true;
			this.approvalRuntimeTokenRetryBudgetUsed = true;
			this.protocol.resetReconnectBackoff(250);
			this.logDebug("gateway rejected approval runtime auth field; retrying without it");
			return {
				closeCode: 1008,
				closeReason: "connect retry"
			};
		}
		this.notifyConnectError(e);
		const i = `gateway connect failed: ${formatGatewayClientErrorForLog(e)}`;
		if (this.opts.mode === GATEWAY_CLIENT_MODES.PROBE || isGatewayClientStoppedError(e) || n === ConnectErrorDetailCodes.AUTH_RATE_LIMITED) this.logDebug(i);
		else this.logError(i);
		return {
			closeCode: 1008,
			closeReason: "connect failed"
		};
	}
	resolveClose(e) {
		const t = this.closeInfo(e);
		const n = e.connectFailure?.error instanceof GatewayClientRequestError ? readConnectErrorDetailCode(e.connectFailure.error.details) : null;
		const r = e.connectFailure?.error instanceof GatewayClientRequestError ? e.connectFailure.error.details : void 0;
		if (e.code === 1013 && e.connectFailure?.reconnectDelayMs !== void 0) return {
			retry: true,
			notify: this.opts.notifyOnStartupRetry === true,
			reconnectDelayMs: e.connectFailure.reconnectDelayMs
		};
		if (t.transientPreHelloCleanClose && this.suppressedTransientPreHelloCleanCloses < MAX_SUPPRESSED_TRANSIENT_PRE_HELLO_CLEAN_CLOSES) {
			this.suppressedTransientPreHelloCleanCloses += 1;
			return {
				retry: true,
				notify: true,
				pendingError: /* @__PURE__ */ new Error("gateway transient pre-hello clean close")
			};
		}
		if (t.transientPreHelloCleanClose || e.connectRequestSent && !e.helloReceived && !e.connectFailure) {
			const t = /* @__PURE__ */ new Error(`gateway closed (${e.code}): ${e.reason}`);
			this.notifyConnectError(t);
			this.logError(`gateway connect failed: ${formatGatewayClientErrorForLog(t)}`);
		}
		this.clearStaleDeviceTokenForClose(e);
		if (shouldPauseGatewayReconnect({
			details: r,
			deviceTokenRetryPending: this.pendingDeviceTokenRetry,
			tokenMismatchIsTerminal: true,
			protocolMismatchIsTerminal: !this.nodeProtocolTransitionPending,
			clientVersionMismatchIsTerminal: true
		})) {
			this.notifyReconnectPaused({
				code: e.code,
				reason: e.reason,
				detailCode: n
			});
			return {
				retry: false,
				notify: true
			};
		}
		return {
			retry: true,
			notify: true,
			reconnectDelayMs: e.connectFailure?.reconnectDelayMs
		};
	}
	closeInfo(e) {
		return {
			phase: e.helloReceived ? "post-hello" : "pre-hello",
			socketOpened: e.socketOpened,
			transportValidated: this.transportValidated,
			connectRequestSent: e.connectRequestSent,
			transientPreHelloCleanClose: !e.helloReceived && e.code === 1e3 && e.reason === "",
			...e.connectFailure?.error ? { connectError: e.connectFailure.error } : {}
		};
	}
	clearStaleDeviceTokenForClose(e) {
		const { code: t, reason: n, generation: r } = e;
		if (t !== 1008 || !normalizeLowercaseStringOrEmpty(n).includes("device token mismatch") || !this.opts.deviceIdentity) return;
		const i = this.connectionStoredToken?.generation === r ? this.connectionStoredToken : { token: void 0 };
		this.clearDeviceToken(this.opts.deviceIdentity.deviceId, i, () => !this.opts.token && !this.opts.password);
	}
	clearDeviceToken(e, t, n = () => true) {
		const failed = (t) => {
			this.logDebug(`failed clearing stale device-auth token for device ${e}: ${String(t)}`);
		};
		const cleared = () => this.logDebug(`cleared stale device-auth token for device ${e}`);
		try {
			const r = this.deviceAuth.clear({
				deviceId: e,
				role: this.opts.role ?? "operator",
				env: this.opts.env,
				assertCurrent: () => {
					if (this.stopped) throw new Error("gateway client stopped");
				}
			}, t, n);
			return r instanceof Promise ? r.then(cleared, failed) : cleared();
		} catch (e) {
			failed(e);
		}
	}
	notifyConnectError(e) {
		if (!this.opts.onConnectError) return false;
		try {
			this.opts.onConnectError(e);
			return true;
		} catch (e) {
			this.logDebug(`gateway client connect error handler error: ${formatGatewayClientErrorForLog(e)}`);
			return false;
		}
	}
	notifyReconnectPaused(e) {
		try {
			this.opts.onReconnectPaused?.(e);
		} catch (e) {
			this.logDebug(`gateway client reconnect paused handler error: ${formatGatewayClientErrorForLog(e)}`);
		}
	}
	isUnsupportedConnectAuthField(e, t) {
		if (!(e instanceof GatewayClientRequestError) || e.gatewayCode !== "INVALID_REQUEST") return false;
		const n = normalizeLowercaseStringOrEmpty(e.message);
		return n.includes("invalid connect params") && n.includes(t);
	}
	isTrustedDeviceRetryEndpoint() {
		const e = this.opts.url ?? "ws://127.0.0.1:18789";
		try {
			const t = new URL(e);
			const n = t.protocol === "https:" ? "wss:" : t.protocol === "http:" ? "ws:" : t.protocol;
			if (isGatewayLoopbackHost(t.hostname)) return true;
			return n === "wss:" && Boolean(this.opts.tlsFingerprint?.trim());
		} catch {
			return false;
		}
	}
	startTickWatch() {
		clearInterval(this.tickTimer ?? void 0);
		const e = this.opts.tickWatchMinIntervalMs;
		const t = typeof e === "number" && Number.isFinite(e) ? Math.max(1, Math.min(3e4, e)) : 1e3;
		const n = resolveSafeTimeoutDelayMs(Math.max(this.tickIntervalMs, t));
		this.tickTimer = setInterval(() => {
			if (this.stopped) return;
			if (!this.lastTick) return;
			if (this.protocol.hasPendingRequests && !this.protocol.hasUnboundedPendingRequests) return;
			const e = Date.now() - this.lastTick;
			const t = this.opts.tickWatchTimeoutMs;
			if (e > (typeof t === "number" && Number.isFinite(t) ? Math.max(1, t) : this.tickIntervalMs * 2)) this.protocol.closeSocket(4e3, "tick timeout");
		}, n);
	}
	async request(e, t, n) {
		const r = n?.expectFinal === true;
		const i = n?.timeoutMs === null ? null : typeof n?.timeoutMs === "number" && Number.isFinite(n.timeoutMs) ? n.timeoutMs : r ? null : this.requestTimeoutMs;
		return this.protocol.request(e, t, {
			...n,
			expectFinal: r,
			timeoutMs: i
		});
	}
};
//#endregion
//#region src/infra/net/proxyline-runtime.ts
function loadProxyline() {
	return createRequire(import.meta.url)("@openclaw/proxyline");
}
//#endregion
//#region src/infra/net/undici-global-dispatcher.ts
const HTTP1_ONLY_DISPATCHER_OPTIONS = Object.freeze({ allowH2: false });
let lastAppliedTimeoutKey = null;
let lastAppliedProxyBootstrapKey = null;
const timedProxylineManagedDispatchers = /* @__PURE__ */ new WeakMap();
function isTimedProxylineManagedDispatcher(e) {
	return typeof e === "object" && e !== null ? timedProxylineManagedDispatchers.has(e) : false;
}
function resolveDispatcherKind(e) {
	const t = e?.constructor?.name;
	if (typeof t !== "string" || t.length === 0) return "unsupported";
	if (t.includes("EnvHttpProxyAgent")) return "env-proxy";
	if (isTimedProxylineManagedDispatcher(e) || isProxylineDispatcher(e)) return "proxyline-managed";
	if (t.includes("ProxyAgent")) return "unsupported";
	if (t.includes("Agent")) return "agent";
	return "unsupported";
}
function resolveEnvProxyBootstrapKey(e) {
	const t = [.../* @__PURE__ */ new Set([e.httpProxy, e.httpsProxy])].map((e) => e ? resolveActiveManagedProxyTlsOptions({ proxyUrl: e }) : void 0);
	return JSON.stringify([
		e.httpProxy,
		e.httpsProxy,
		t
	]);
}
function resolveCurrentDispatcherInfo(e) {
	let t;
	try {
		t = e.getGlobalDispatcher();
	} catch {
		return null;
	}
	const n = resolveDispatcherKind(t);
	if (n === "unsupported") return null;
	return {
		kind: n,
		dispatcher: t
	};
}
/**
* Re-evaluate proxy env changes for root undici imports. Installs
* EnvHttpProxyAgent when proxy env is present, and restores a direct Agent
* after proxy env is cleared.
*/
function forceResetGlobalDispatcher(e) {
	lastAppliedTimeoutKey = null;
	const t = resolveEnvHttpProxyAgentOptions();
	if (!t) {
		if (lastAppliedProxyBootstrapKey === null) return;
		lastAppliedProxyBootstrapKey = null;
		try {
			const { setGlobalDispatcher: e } = loadUndiciGlobalDispatcherDeps();
			e(createHttp1Agent());
		} catch {}
		return;
	}
	try {
		const n = loadUndiciGlobalDispatcherDeps();
		const { setGlobalDispatcher: r } = n;
		if (e?.preserveProxylineManaged) {
			if (resolveCurrentDispatcherInfo(n)?.kind === "proxyline-managed") {
				lastAppliedProxyBootstrapKey = resolveEnvProxyBootstrapKey(t);
				return;
			}
		}
		r(createHttp1EnvHttpProxyAgent(t));
		lastAppliedProxyBootstrapKey = resolveEnvProxyBootstrapKey(t);
	} catch {}
}
//#endregion
//#region src/infra/net/proxy/proxy-lifecycle.ts
const PROXY_ENV_KEYS = [
	"http_proxy",
	"https_proxy",
	"HTTP_PROXY",
	"HTTPS_PROXY"
];
const NO_PROXY_ENV_KEYS = ["no_proxy", "NO_PROXY"];
const LOOPBACK_NO_PROXY = "127.0.0.1,localhost,localhost.,::1,[::1],127.0.0.0/8";
const managedLoopbackBypassPolicy = ({ url: e }) => getActiveManagedProxyLoopbackMode() === "gateway-only" && isLoopbackProxyUrl(e);
const PROXY_ACTIVE_KEYS = [
	"OPENCLAW_PROXY_ACTIVE",
	"OPENCLAW_PROXY_LOOPBACK_MODE",
	"OPENCLAW_PROXY_CA_FILE"
];
const ALL_PROXY_ENV_KEYS = [
	...PROXY_ENV_KEYS,
	...NO_PROXY_ENV_KEYS,
	...PROXY_ACTIVE_KEYS
];
let proxylineHandle = null;
const MANAGED_PROXY_UNDICI_OPTIONS = Object.freeze({ allowH2: false });
function applyProxyEnv(e, t, n) {
	for (const t of PROXY_ENV_KEYS) process.env[t] = e;
	process.env["OPENCLAW_PROXY_ACTIVE"] = "1";
	process.env["OPENCLAW_PROXY_LOOPBACK_MODE"] = t;
	if (n) process.env["OPENCLAW_PROXY_CA_FILE"] = n;
	else delete process.env["OPENCLAW_PROXY_CA_FILE"];
	for (const e of NO_PROXY_ENV_KEYS) process.env[e] = t === "gateway-only" ? LOOPBACK_NO_PROXY : "";
}
/** Reinstalls Proxyline routing in child processes that inherited active proxy env. */
function ensureInheritedManagedProxyRoutingActive() {
	if (process.env["OPENCLAW_PROXY_ACTIVE"] !== "1") return;
	const e = process.env["HTTP_PROXY"];
	if (!e || !isHttpUrl(e)) return;
	const t = resolveManagedProxyCaFileForUrl({
		proxyUrl: e,
		caFileOverride: process.env["OPENCLAW_PROXY_CA_FILE"]
	});
	const n = loadManagedProxyTlsOptionsSync(t);
	applyProxyEnv(e, getActiveManagedProxyLoopbackMode() ?? "gateway-only", t);
	proxylineHandle = loadProxyline().installGlobalProxy({
		mode: "managed",
		proxyUrl: e,
		...n ? { proxyTls: n } : {},
		ifActive: "reuse-compatible",
		bypassPolicy: managedLoopbackBypassPolicy,
		undici: MANAGED_PROXY_UNDICI_OPTIONS
	});
	forceResetGlobalDispatcher({ preserveProxylineManaged: true });
}
function isLoopbackProxyUrl(e) {
	const t = URL.parse(e);
	if (!t) return false;
	const n = t.hostname.toLowerCase().replace(/\.+$/, "");
	return (isHttpUrl(t) || isWebSocketUrl(t)) && (n === "localhost" || isLoopbackIpAddress(n));
}
function assertManagedProxyAllowsLoopback(e, t) {
	if (isLoopbackProxyUrl(e) && getActiveManagedProxyLoopbackMode() === "block") throw new Error(`proxy: ${t} connections are blocked by proxy.loopbackMode; run openclaw config set proxy.loopbackMode gateway-only to allow local runtime traffic.`);
}
function registerManagedProxyGatewayLoopbackBypass(e) {
	assertManagedProxyAllowsLoopback(e, "Gateway loopback control-plane");
}
//#endregion
//#region src/shared/gateway-client-platform.ts
function resolveGatewayClientPlatformIdentity(e) {
	switch (e) {
		case "darwin": return {
			platform: "macos",
			deviceFamily: "Mac"
		};
		case "win32": return {
			platform: "windows",
			deviceFamily: "Windows"
		};
		case "linux": return {
			platform: e,
			deviceFamily: "Linux"
		};
		default: return { platform: e };
	}
}
//#endregion
//#region src/gateway/client.ts
function shouldSuppressStoredDeviceAuth(e) {
	return Boolean(e.deviceAuthScope && (e.token?.trim() || e.password?.trim())) || !e.deviceAuthScope && e.sharedStateMode === "read-only" && Boolean(e.password?.trim()) && !e.token?.trim() && !e.bootstrapToken?.trim() && !e.deviceToken?.trim() && !e.approvalRuntimeToken?.trim() && !e.agentRuntimeIdentityToken?.trim() && !e.preferBootstrapToken;
}
var GatewayClient = class {
	#e;
	#t;
	#n;
	#r;
	#i;
	#a = new AbortController();
	constructor(e) {
		if (e.sshTunnel && !e.deviceAuthScope) throw new Error("Gateway SSH route requires its own device-auth scope");
		if (e.preparedSshTunnel && !e.sshTunnel) throw new Error("Prepared Gateway SSH tunnel requires its selected route");
		this.#t = e;
		this.#n = e.preparedSshTunnel;
		if (!e.sshTunnel && !this.needsDeviceIdentity()) this.#e = this.createClient(e.url);
	}
	needsDeviceIdentity() {
		return this.#t.deviceIdentity === void 0 && (this.#t.sharedStateMode === "read-only" || !this.#t.hostDeps?.loadOrCreateDeviceIdentity);
	}
	createClient(e, t) {
		const n = this.#t;
		const { deviceAuthScope: r, preparedDeviceAuth: i, sharedStateMode: a, sshTunnel: o, preparedSshTunnel: s, ...c } = n;
		const l = resolveGatewayClientPlatformIdentity(process.platform);
		const u = shouldSuppressStoredDeviceAuth(n);
		for (const e of Object.values(c.edgeAuthHeaders ?? {})) registerSecretValueForRedaction(e);
		const d = a === "read-only";
		const f = i ? { expectedToken: i.token } : void 0;
		let p;
		const observe = (e) => {
			const t = e.deviceId;
			const n = normalizeDeviceAuthRole(e.role);
			return (e) => {
				p = {
					deviceId: t,
					role: n,
					expectedToken: e.expectedToken
				};
			};
		};
		const observedFor = (e) => p?.deviceId === e.deviceId && p.role === normalizeDeviceAuthRole(e.role) ? p : void 0;
		const writeFence = (e) => {
			if (f) return f;
			const t = observedFor(e);
			return t ? { expectedToken: t.expectedToken } : void 0;
		};
		const clearFence = (e) => {
			const t = f?.expectedToken ?? e.expectedToken;
			const n = observedFor(e)?.expectedToken;
			return {
				...f,
				...typeof n === "string" && n !== t && n.trim() === t ? { observedToken: n } : {}
			};
		};
		const m = {
			loadDeviceAuthToken: r ? async (e) => {
				if (d) return u ? null : loadOriginDeviceTokenReadOnly({
					...e,
					gatewayScope: r
				});
				const t = await loadOriginDeviceToken({
					...e,
					gatewayScope: r,
					onSnapshot: observe(e)
				});
				return u ? null : t;
			} : d ? u ? () => null : loadDeviceAuthTokenReadOnly : (e) => loadDeviceAuthToken({
				...e,
				onSnapshot: observe(e)
			}),
			storeDeviceAuthToken: d ? () => {} : (e) => {
				const t = {
					...e,
					...writeFence(e)
				};
				return r ? storeOriginDeviceToken({
					...t,
					gatewayScope: r
				}) : storeDeviceAuthToken(t);
			},
			clearDeviceAuthToken: d ? () => {} : (e) => {
				const t = {
					...e,
					...clearFence(e)
				};
				return r ? clearOriginDeviceToken({
					...t,
					gatewayScope: r
				}) : clearDeviceAuthToken(t);
			}
		};
		const h = i ? {
			...m,
			loadDeviceAuthToken: () => i
		} : m;
		const g = {
			signDevicePayload: signEd25519Payload,
			publicKeyRawBase64UrlFromPem: publicKeyRawBase64UrlFromEd25519Pem,
			...h,
			beforeConnect: ensureInheritedManagedProxyRoutingActive,
			registerGatewayLoopbackBypass: registerManagedProxyGatewayLoopbackBypass,
			logDebug,
			logError,
			redactForLog: (e) => redactToolPayloadText(sanitizeTerminalText(redactToolPayloadText(e))),
			...c.hostDeps,
			...d ? {
				loadOrCreateDeviceIdentity: () => void 0,
				...h
			} : {}
		};
		if (o) {
			const e = g.beforeConnect;
			g.beforeConnect = () => {
				e?.();
				if (this.#a.signal.aborted || !this.#n?.isActive()) throw new Error("Gateway SSH tunnel is no longer active");
			};
		}
		return new GatewayClient$1({
			...c,
			url: e,
			...t ? { tlsServerName: t } : {},
			clientVersion: c.clientVersion ?? VERSION,
			platform: c.platform ?? l.platform,
			deviceFamily: c.deviceFamily ?? (c.platform === void 0 ? l.deviceFamily : void 0),
			hostDeps: g
		});
	}
	start() {
		if (this.#r || this.#a.signal.aborted) return;
		if (this.#e) {
			this.#e.start();
			return;
		}
		this.#r = this.startPreparedClient().catch((e) => {
			if (this.#a.signal.aborted) return;
			this.stop();
			const t = e instanceof Error ? e : new Error(String(e));
			this.notifyClosed(t);
		});
	}
	async startPreparedClient() {
		if (this.needsDeviceIdentity()) {
			const e = { env: this.#t.env };
			const t = this.#t.sharedStateMode === "read-only" ? await loadDeviceIdentityIfPresentAsync(e) : await loadOrCreateDeviceIdentityAsync(e);
			this.#t = {
				...this.#t,
				deviceIdentity: t
			};
		}
		if (this.#a.signal.aborted) return;
		if (this.#t.sshTunnel) await this.startSsh();
		else {
			this.#e = this.createClient(this.#t.url);
			this.#e.start();
		}
	}
	async startSsh() {
		const e = this.#t.sshTunnel;
		if (!e) return;
		const t = new URL(this.#t.url ?? "");
		if (!this.#n) {
			const { startSshPortForward: n } = await import("./ssh-tunnel-BPPb8UyL.mjs");
			this.#a.signal.throwIfAborted();
			this.#n = await n({
				...e,
				localPortPreferred: Number(t.port) || (t.protocol === "wss:" ? 443 : 80),
				timeoutMs: this.#t.preauthHandshakeTimeoutMs ?? 1e4,
				signal: this.#a.signal
			});
		}
		if (this.#a.signal.aborted) {
			await this.#n.stop();
			return;
		}
		if (!this.#n.isActive()) throw new Error("Gateway SSH tunnel closed before connection");
		this.#n.closed.then(() => {
			if (!this.#a.signal.aborted) {
				this.stop();
				this.notifyClosed();
			}
		});
		const n = t.protocol === "wss:" ? parseHostForAddressChecks(t.hostname)?.unbracketedHost : void 0;
		t.hostname = "127.0.0.1";
		t.port = String(this.#n.localPort);
		this.#e = this.createClient(t.href, n);
		this.#e.start();
	}
	notifyClosed(e) {
		if (e) try {
			this.#t.onConnectError?.(e);
		} catch {
			logError("Gateway connect-error callback failed");
		}
		try {
			this.#t.onClose?.(1006, e?.message ?? "Gateway SSH tunnel closed");
		} catch {
			logError("Gateway close callback failed");
		}
	}
	stop() {
		this.stopAndWait().catch((e) => logError(String(e)));
	}
	stopAndWait(e) {
		this.#a.abort();
		this.#e?.stop();
		return this.#i ??= (async () => {
			try {
				await this.#r;
				await this.#e?.stopAndWait(e);
			} finally {
				await this.#n?.stop();
			}
		})();
	}
	request(e, t, n) {
		return this.#e ? this.#e.request(e, t, n) : Promise.reject(/* @__PURE__ */ new Error("Gateway connection has not started"));
	}
	/** Current transport state, including CLOSING before the close callback fires.
	* This is not authentication or readiness evidence on its own. */
	get connected() {
		return this.#e?.connected ?? false;
	}
	getConnectionMetadata() {
		return this.#e?.getConnectionMetadata() ?? {
			clientName: this.#t.clientName,
			hasDeviceIdentity: Boolean(this.#t.deviceIdentity),
			mode: this.#t.mode,
			preauthHandshakeTimeoutMs: this.#t.preauthHandshakeTimeoutMs
		};
	}
	updateNodeManifest(e) {
		if (this.#e) this.#e.updateNodeManifest(e);
		else this.#t = {
			...this.#t,
			...e
		};
	}
};
//#endregion
//#region src/shared/gateway-edge-auth-headers.ts
const HTTP_HEADER_NAME_PATTERN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u;
const TRANSPORT_OWNED_HEADERS = /* @__PURE__ */ new Set([
	"host",
	"connection",
	"upgrade",
	"content-length",
	"sec-websocket-key",
	"sec-websocket-version",
	"sec-websocket-protocol",
	"sec-websocket-extensions"
]);
function findEdgeAuthIssue(e) {
	const t = Object.entries(e);
	if (t.length === 0) return { message: "invalid gateway.remote.edgeAuth: header map must not be empty" };
	const n = /* @__PURE__ */ new Map();
	for (const [e] of t) {
		if (!HTTP_HEADER_NAME_PATTERN.test(e)) return {
			headerName: e,
			message: `invalid gateway.remote.edgeAuth header name: ${JSON.stringify(e)}`
		};
		const t = e.toLowerCase();
		if (TRANSPORT_OWNED_HEADERS.has(t)) return {
			headerName: e,
			message: `gateway.remote.edgeAuth cannot set transport-owned header "${e}"`
		};
		const r = n.get(t);
		if (r) return {
			headerName: e,
			message: `gateway.remote.edgeAuth header names "${r}" and "${e}" differ only by case`
		};
		n.set(t, e);
	}
	return null;
}
//#endregion
//#region src/gateway/edge-auth.ts
function normalizeEdgeAuthHeadersConfig(e) {
	if (e === void 0 || e === null) return;
	if (!isRecord(e)) throw new Error("invalid gateway.remote.edgeAuth: expected a header map");
	const t = findEdgeAuthIssue(e);
	if (t) throw new Error(t.message);
	const n = Object.entries(e).map(([e, t]) => {
		return [e, normalizeRequiredSecretInput(t, `gateway.remote.edgeAuth header "${e}"`)];
	});
	return Object.fromEntries(n);
}
async function resolveEdgeAuthHeaders(e) {
	if (!e.value) return;
	if (URL.parse(e.targetUrl)?.protocol !== "wss:") throw new Error("gateway.remote.edgeAuth requires a wss:// connection target");
	const t = await Promise.all(Object.entries(e.value).map(async ([t, n]) => {
		const r = await materializeSecretInput({
			config: e.config,
			value: n,
			env: e.env
		});
		if (!r) throw new Error(`gateway.remote.edgeAuth header "${t}" resolved empty`);
		registerSecretValueForRedaction(r);
		return [t, r];
	}));
	return Object.freeze(Object.fromEntries(t));
}
function gatewayEdgeAuthValueForTarget(e) {
	const t = e.config.gateway?.remote;
	if (!t?.url || gatewayOriginScope(e.targetUrl) !== gatewayOriginScope(t.url)) return;
	return t.edgeAuth;
}
//#endregion
//#region src/gateway/auth-resolve.ts
/** Merge sparse runtime auth overrides without erasing configured values. */
function mergeGatewayAuthConfig(e, t) {
	const n = { ...e };
	if (!t) return n;
	for (const e of [
		"mode",
		"token",
		"password",
		"allowTailscale",
		"rateLimit",
		"trustedProxy"
	]) if (t[e] !== void 0) Object.assign(n, { [e]: t[e] });
	return n;
}
/** Apply auth mode and Tailscale policy to credentials already selected by their owner. */
function resolveGatewayAuthFromCredentials(e) {
	const { authConfig: t, authOverride: n, token: r, password: i } = e;
	const a = n?.mode ?? t.mode ?? (i ? "password" : "token");
	return {
		mode: a,
		modeSource: n?.mode !== void 0 ? "override" : t.mode ? "config" : i ? "password" : r ? "token" : "default",
		token: r,
		password: i,
		allowTailscale: t.allowTailscale ?? (e.tailscaleMode === "serve" && a !== "password" && a !== "trusted-proxy"),
		trustedProxy: t.trustedProxy
	};
}
/** Resolve auth from an env-substituted config while retaining its resolution facts. */
function resolveGatewayAuthForConfig(e) {
	const t = e.authOverride ?? void 0;
	const n = mergeGatewayAuthConfig(e.config.gateway?.auth, t);
	const r = {
		...e.config,
		gateway: {
			...e.config.gateway,
			auth: n
		}
	};
	const i = [...t?.token !== void 0 ? ["gateway.auth.token"] : [], ...t?.password !== void 0 ? ["gateway.auth.password"] : []];
	copyConfigResolutionFactsExcept(e.config, r, i);
	const a = createGatewayCredentialPlan({
		config: r,
		env: e.env
	});
	return resolveGatewayAuthFromCredentials({
		authConfig: n,
		authOverride: t,
		token: a.localToken.hasSecretRef ? void 0 : a.localToken.value ?? a.envToken ?? a.remoteToken.value,
		password: a.localPassword.hasSecretRef ? void 0 : a.localPassword.value ?? a.envPassword ?? (a.authMode === "trusted-proxy" ? void 0 : a.remotePassword.value),
		tailscaleMode: e.tailscaleMode
	});
}
//#endregion
//#region src/gateway/explicit-connection-policy.ts
function hasExplicitGatewayConnectionAuth(e) {
	return Boolean(trimToUndefined(e?.token) || trimToUndefined(e?.password));
}
function targetMayRequireConfiguredEdgeAuth(e) {
	const t = URL.parse(e)?.protocol;
	return t === "wss:" || t === "https:";
}
/**
* True when the caller fully addressed the Gateway with flags. Config is then
* consulted only for gateway.remote.edgeAuth, so a broken config must not block
* the connection: this is the historical recovery path for an invalid config.
*/
function isExplicitGatewayConnection(e) {
	return !e.config && Boolean(trimToUndefined(e.urlOverride)) && hasExplicitGatewayConnectionAuth(e.explicitAuth);
}
/** Returns true when url/auth flags are sufficient and loading OpenClaw config is unnecessary. */
function canSkipGatewayConfigLoad(e) {
	const t = trimToUndefined(e.urlOverride);
	if (!t || e.config || !hasExplicitGatewayConnectionAuth(e.explicitAuth)) return false;
	return !targetMayRequireConfiguredEdgeAuth(t);
}
/** Preserve configured server inference unless this connection actually skipped config. */
function resolveGatewayConnectionAuth(e) {
	return e.configSkipped ? resolveGatewayAuthFromCredentials({
		authConfig: {},
		...e.auth
	}) : resolveGatewayAuthForConfig({
		config: e.config,
		tailscaleMode: e.config.gateway?.tailscale?.mode
	});
}
//#endregion
//#region src/infra/node-commands.ts
const NODE_FS_LIST_DIR_COMMAND = "fs.listDir";
const NODE_TERMINAL_UPLOAD_COMMAND = "terminal.upload";
const NODE_BROWSER_PROXY_COMMAND = "browser.proxy";
const NODE_BROWSER_PROXY_UPLOAD_COMMAND = "browser.proxy.upload.v1";
const NODE_BROWSER_PROXY_COMMANDS = [NODE_BROWSER_PROXY_COMMAND, NODE_BROWSER_PROXY_UPLOAD_COMMAND];
const NODE_WORKER_BUNDLE_INSTALL_COMMAND = "worker.bundle.install.v1";
const NODE_WORKER_SUPERVISOR_LAUNCH_COMMAND = "worker.launch.v1";
const NODE_WORKER_SUPERVISOR_STATUS_COMMAND = "worker.status.v1";
const NODE_WORKER_SUPERVISOR_CANCEL_COMMAND = "worker.cancel.v1";
const NODE_WORKER_PROCESSES_COMMAND = "worker.processes.v1";
const NODE_WORKER_ENVIRONMENT_STOP_COMMAND = "worker.environment.stop.v1";
const NODE_WORKER_WORKSPACE_EXEC_COMMAND = "worker.workspace.exec.v1";
const NODE_WORKER_WORKSPACE_PREPARE_COMMAND = "worker.workspace.prepare.v1";
const NODE_WORKER_WORKSPACE_RETAIN_COMMAND = "worker.workspace.retain.v1";
const NODE_WORKER_DESKTOP_STREAM_COMMAND = "worker.desktop.stream.v1";
const NODE_WORKER_DESKTOP_LAUNCH_COMMAND = "worker.desktop.launch.v1";
const NODE_WORKER_DESKTOP_COMPUTER_COMMAND = "worker.desktop.computer.v1";
const NODE_WORKER_PORTAL_STREAM_COMMAND = "worker.portal.stream.v1";
const NODE_WORKER_PRIVATE_COMMANDS = [
	NODE_WORKER_BUNDLE_INSTALL_COMMAND,
	NODE_WORKER_SUPERVISOR_LAUNCH_COMMAND,
	NODE_WORKER_SUPERVISOR_STATUS_COMMAND,
	NODE_WORKER_SUPERVISOR_CANCEL_COMMAND,
	NODE_WORKER_ENVIRONMENT_STOP_COMMAND,
	NODE_WORKER_PROCESSES_COMMAND,
	NODE_WORKER_WORKSPACE_EXEC_COMMAND,
	NODE_WORKER_WORKSPACE_PREPARE_COMMAND,
	NODE_WORKER_WORKSPACE_RETAIN_COMMAND,
	NODE_WORKER_DESKTOP_STREAM_COMMAND,
	NODE_WORKER_DESKTOP_LAUNCH_COMMAND,
	NODE_WORKER_DESKTOP_COMPUTER_COMMAND,
	NODE_WORKER_PORTAL_STREAM_COMMAND
];
const PRIVATE_NODE_INVOKE_COMMAND_SET = new Set(NODE_WORKER_PRIVATE_COMMANDS);
const NODE_ADMIN_ONLY_INVOKE_COMMANDS = [
	...NODE_BROWSER_PROXY_COMMANDS,
	NODE_FS_LIST_DIR_COMMAND,
	NODE_TERMINAL_UPLOAD_COMMAND
];
const NODE_ADMIN_ONLY_INVOKE_COMMAND_SET = new Set(NODE_ADMIN_ONLY_INVOKE_COMMANDS);
/** Returns true when direct node invocation crosses an admin-only host boundary. */
function isAdminOnlyNodeInvokeCommand(e) {
	return typeof e === "string" && NODE_ADMIN_ONLY_INVOKE_COMMAND_SET.has(e);
}
/** Returns true for every versioned Browser node proxy command. */
function isBrowserProxyNodeInvokeCommand(e) {
	return typeof e === "string" && NODE_BROWSER_PROXY_COMMANDS.includes(e);
}
//#endregion
//#region src/state/agent-database-preparation-context.ts
const preparation = new AsyncContext(Symbol("agentDatabasePreparation"));
//#endregion
//#region src/plugins/plugin-return-value.ts
const promiseThen = Object.getOwnPropertyDescriptor(Promise.prototype, "then");
const promiseSpecies = Object.getOwnPropertyDescriptor(Promise, Symbol.species);
//#endregion
//#region src/plugins/runtime/execution-frame.ts
const PluginRuntimeExecutionFrame = resolveGlobalSingleton(Symbol.for("openclaw.pluginRuntimeExecutionFrame"), () => class RuntimeFrame extends InvocationFrame {
	constructor(e, t, n, r = e.invocation) {
		super(e, r);
		this.gatewayScope = t;
		this.generationRegistry = n;
	}
	get runtimePluginId() {
		return this.gatewayScope?.pluginId;
	}
	withScopes(e) {
		return new RuntimeFrame(e, this.gatewayScope, this.generationRegistry);
	}
});
function getPluginRuntimeExecutionFrame(e = getPluginExecutionFrame()) {
	return e instanceof PluginRuntimeExecutionFrame ? e : void 0;
}
//#endregion
//#region src/plugins/runtime/gateway-context-binding-owner.ts
const { getGatewayContextBindingSlot, prepareGatewayContextBindingOwner } = resolveGlobalSingleton(Symbol.for("openclaw.gatewayContextBindingOwner"), () => {
	const e = Symbol("gatewayContextBindingOwner");
	class GatewayContextBindingOwner {
		#e;
		constructor(e) {
			this.#e = e;
			Object.setPrototypeOf(this, null);
		}
		static read(e, t) {
			return typeof e === "object" && e !== null && #e in e && e.#e === t ? e : void 0;
		}
	}
	function readSlot(t) {
		const n = Object.getOwnPropertyDescriptor(t, e)?.value;
		return GatewayContextBindingOwner.read(n, t);
	}
	/** Reserve exact-owner storage before admission freezes the public context. */
	function prepareOwner(t) {
		if (!readSlot(t)) Object.defineProperty(t, e, { value: new GatewayContextBindingOwner(t) });
		return t;
	}
	return {
		getGatewayContextBindingSlot: readSlot,
		prepareGatewayContextBindingOwner: prepareOwner
	};
});
//#endregion
//#region src/plugins/runtime/gateway-context-binding.ts
const { bindGatewayContextResolver, getGatewayContextLifetime, getGatewayContextResolver, clearGatewayContextResolver } = resolveGlobalSingleton(Symbol.for("openclaw.gatewayContextBindings"), () => {
	const e = Symbol("gatewayContextBinding");
	const t = Symbol("gatewayContextLifetime");
	class GatewayContextBinding {
		#e;
		#t;
		constructor(e) {
			this.#e = e;
			Object.setPrototypeOf(this, null);
		}
		static read(e, t) {
			return typeof e === "object" && e !== null && #e in e && e.#e === t ? e : void 0;
		}
		static get(e) {
			return e.#t;
		}
		static set(e, t) {
			e.#t = t;
		}
	}
	class GatewayContextLifetime {
		#e;
		#t = new AbortController();
		constructor(e) {
			this.#e = e;
			Object.setPrototypeOf(this, null);
		}
		static read(e, t) {
			return typeof e === "object" && e !== null && #e in e && e.#e === t ? e.#t : void 0;
		}
	}
	function getGatewayContextBinding(t) {
		const n = getGatewayContextBindingSlot(t);
		const r = n && Object.getOwnPropertyDescriptor(n, e)?.value;
		return GatewayContextBinding.read(r, t);
	}
	function getLifetime(e) {
		const n = Object.getOwnPropertyDescriptor(e, t)?.value;
		const r = GatewayContextLifetime.read(n, e);
		if (r) return r;
		const i = new GatewayContextLifetime(e);
		Object.defineProperty(e, t, { value: i });
		return GatewayContextLifetime.read(i, e);
	}
	function bindResolver(t, n) {
		if (n) {
			prepareGatewayContextBindingOwner(t);
			let r = getGatewayContextBinding(t);
			if (!r) {
				const n = getGatewayContextBindingSlot(t);
				r = new GatewayContextBinding(t);
				Object.defineProperty(n, e, { value: r });
			}
			GatewayContextBinding.set(r, n);
		}
	}
	function readResolver(e) {
		const t = getGatewayContextBinding(e);
		return t ? GatewayContextBinding.get(t) : void 0;
	}
	function clearResolver(e) {
		const t = getGatewayContextBinding(e);
		const n = t !== void 0 && GatewayContextBinding.get(t) !== void 0;
		if (t) GatewayContextBinding.set(t, void 0);
		return n;
	}
	return {
		bindGatewayContextResolver: bindResolver,
		getGatewayContextLifetime: getLifetime,
		getGatewayContextResolver: readResolver,
		clearGatewayContextResolver: clearResolver
	};
});
//#endregion
//#region src/plugins/runtime/gateway-request-scope.ts
const ExpiredPluginRegistryScopeError = resolveGlobalSingleton(Symbol.for("openclaw.expiredPluginRegistryScopeError"), () => class extends Error {
	constructor() {
		super("Plugin registry scope is no longer available");
	}
});
function getPluginRuntimeGatewayRequestScope() {
	return getPluginRuntimeExecutionFrame()?.gatewayScope;
}
/** Reads registration/request/active registry precedence without initializing a cold runtime. */
function getPluginRegistryForContext() {
	const e = getPluginRegistryState();
	return e?.registrationContext?.registry ?? getPluginRuntimeGatewayRequestScope()?.pluginRegistry ?? e?.activeRegistry ?? null;
}
//#endregion
//#region src/shared/gateway-method-policy.ts
const RESERVED_ADMIN_GATEWAY_METHOD_PREFIXES = [
	"exec.approvals.",
	"config.",
	"wizard.",
	"update."
];
const RESERVED_ADMIN_GATEWAY_METHOD_SCOPE = "operator.admin";
/** Resolve the mandatory scope for reserved gateway methods. */
function resolveReservedGatewayMethodScope(e) {
	if (!RESERVED_ADMIN_GATEWAY_METHOD_PREFIXES.some((t) => e.startsWith(t))) return;
	return RESERVED_ADMIN_GATEWAY_METHOD_SCOPE;
}
//#endregion
//#region src/shared/session-method-scopes-base.ts
const SESSIONS_PATCH_WRITE_SCOPE_MUTATIONS = /* @__PURE__ */ new Set([
	"label",
	"autoLabel",
	"icon",
	"color",
	"category",
	"boardFace",
	"boardPresentation",
	"pinned",
	"sidebarRoot",
	"archived",
	"snoozedUntil",
	"unread",
	"model",
	"agentRuntime",
	"thinkingLevel",
	"cyberAccessProgram",
	"fastMode",
	"permissionMode",
	"communication"
]);
const SESSIONS_PATCH_WRITE_SCOPE_ENVELOPE_FIELDS = /* @__PURE__ */ new Set([
	"key",
	"agentId",
	"expectedSessionId",
	"expectedLifecycleRevision",
	"expectedPermissionMode",
	"expectedMarkedUnreadAt",
	"expectedSidebarRoot",
	"expectedCategory",
	"expectedArchived",
	"expectedSidebarAncestors"
]);
const SESSIONS_DELETE_WRITE_SCOPE_FIELDS = /* @__PURE__ */ new Set([
	"key",
	"agentId",
	"deleteTranscript",
	"expectedSessionId",
	"archivedOnly"
]);
/** Browser-safe session mutation policy for methods without protocol validation. */
function resolveBaseSessionMutationRequiredScope(e, t) {
	if (e === "sessions.create") {
		if (!isRecord(t)) return "operator.write";
		if (t.incognito === true || typeof t.key === "string" && isIncognitoSessionKey(t.key) || typeof t.parentSessionKey === "string" && isIncognitoSessionKey(t.parentSessionKey) || Object.hasOwn(t, "execNode") || Object.hasOwn(t, "toolOverrides") || t.permissionMode === "full") return "operator.admin";
		return "operator.write";
	}
	if (e === "sessions.patch") {
		if (!isRecord(t)) return "operator.write";
		if (t.permissionMode === "full" || Object.hasOwn(t, "sandboxMode")) return "operator.admin";
		return Object.keys(t).every((e) => SESSIONS_PATCH_WRITE_SCOPE_ENVELOPE_FIELDS.has(e) || SESSIONS_PATCH_WRITE_SCOPE_MUTATIONS.has(e)) ? "operator.write" : "operator.admin";
	}
	if (e === "sessions.patchMany") {
		if (!isRecord(t) || !isRecord(t.patch)) return "operator.write";
		if (t.patch.permissionMode === "full" || Object.hasOwn(t.patch, "sandboxMode")) return "operator.admin";
		return Object.keys(t.patch).every((e) => SESSIONS_PATCH_WRITE_SCOPE_MUTATIONS.has(e)) ? "operator.write" : "operator.admin";
	}
	if (e === "sessions.delete") {
		if (!isRecord(t) || t.archivedOnly !== true) return "operator.admin";
		return Object.keys(t).every((e) => SESSIONS_DELETE_WRITE_SCOPE_FIELDS.has(e)) ? "operator.write" : "operator.admin";
	}
}
//#endregion
//#region packages/gateway-protocol/src/compiled/protocol.generated/predicates.js
/*!
TypeBox

The MIT License (MIT)

Copyright (c) 2017-2026 Haydn Paterson

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
var __defProp = Object.defineProperty;
var __export = (e, t) => {
	for (var n in t) __defProp(e, n, {
		get: t[n],
		enumerable: !0
	});
};
function hasValidNodeHostResources(e) {
	return e.memoryFreeBytes <= e.memoryTotalBytes && (e.diskTotalBytes === void 0 ? e.diskAvailableBytes === void 0 : e.diskAvailableBytes !== void 0 && e.diskAvailableBytes <= e.diskTotalBytes);
}
function hasValidSessionExecAction(e) {
	let t = e.action ?? "run";
	return t === "run" ? e.argv !== void 0 && e.processId === void 0 : t === "start" ? e.argv !== void 0 && e.processId !== void 0 : e.processId !== void 0 && e.argv === void 0 && e.input === void 0 && e.timeoutMs === void 0;
}
var Uuid = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
function IsUuid(e) {
	return Uuid.test(e);
}
var DAYS = [
	0,
	31,
	28,
	31,
	30,
	31,
	30,
	31,
	31,
	30,
	31,
	30,
	31
];
var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
function IsLeapYear(e) {
	return e % 4 === 0 && (e % 100 !== 0 || e % 400 === 0);
}
function IsDate(e) {
	let t = DATE.exec(e);
	if (!t) return !1;
	let n = +t[1], r = +t[2], i = +t[3];
	return r >= 1 && r <= 12 && i >= 1 && i <= (r === 2 && IsLeapYear(n) ? 29 : DAYS[r]);
}
var TIME = /^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:([Zz])|([+-])(\d\d):(\d\d))?$/;
function IsTime(e, t = !0) {
	let n = TIME.exec(e);
	if (!n || t && !n[4] && !n[5]) return !1;
	let r = +n[1], i = +n[2], a = +n[3];
	if (r > 23 || i > 59 || a > 60) return !1;
	if (n[5]) {
		let e = +n[6], t = +n[7];
		if (e > 23 || t > 59) return !1;
	}
	if (a < 60) return !0;
	let o = n[5] === "-" ? -1 : 1, s = +(n[6] || 0), c = +(n[7] || 0);
	return ((r * 60 + i - o * (s * 60 + c)) % 1440 + 1440) % 1440 === 1439;
}
function IsDateTime(e) {
	let t = e.split(/T/i);
	return t.length === 2 && IsDate(t[0]) && IsTime(t[1]);
}
function CodePointCount(e) {
	let t = 0, n = 0, r = 0;
	for (; n < e.length;) {
		let i = e.charCodeAt(n++) >> 10;
		t += +((r << 8 | i) !== 13879), r = i;
	}
	return t;
}
function IsMaxLength(e, t) {
	return e.length <= t || e.length <= t << 1 && CodePointCount(e) <= t;
}
function IsMinLength(e, t) {
	return e.length >= t << 1 || e.length >= t && CodePointCount(e) >= t;
}
var guard_exports = {};
__export(guard_exports, {
	CodePointCount: () => CodePointCount2,
	Counted: () => Counted,
	Entries: () => Entries,
	EntriesRegExp: () => EntriesRegExp,
	Every: () => Every,
	EveryAll: () => EveryAll,
	GraphemeCount: () => GraphemeCount2,
	HasPropertyKey: () => HasPropertyKey,
	IsArray: () => IsArray,
	IsBigInt: () => IsBigInt,
	IsBoolean: () => IsBoolean,
	IsClassInstance: () => IsClassInstance,
	IsConstructor: () => IsConstructor,
	IsDeepEqual: () => IsDeepEqual,
	IsEqual: () => IsEqual,
	IsFunction: () => IsFunction,
	IsGreaterEqualThan: () => IsGreaterEqualThan,
	IsGreaterThan: () => IsGreaterThan,
	IsInteger: () => IsInteger,
	IsLessEqualThan: () => IsLessEqualThan,
	IsLessThan: () => IsLessThan,
	IsMaxLength: () => IsMaxLength2,
	IsMinLength: () => IsMinLength2,
	IsMultipleOf: () => IsMultipleOf,
	IsNull: () => IsNull,
	IsNumber: () => IsNumber,
	IsObject: () => IsObject,
	IsObjectNotArray: () => IsObjectNotArray,
	IsString: () => IsString,
	IsSymbol: () => IsSymbol,
	IsUndefined: () => IsUndefined,
	IsUnsafePropertyKey: () => IsUnsafePropertyKey,
	IsValueLike: () => IsValueLike,
	Keys: () => Keys,
	ShiftLeft: () => ShiftLeft,
	Some: () => Some,
	SomeAll: () => SomeAll,
	Symbols: () => Symbols,
	Values: () => Values
});
function IsBetween(e, t, n) {
	return e >= t && e <= n;
}
function IsZeroWidthJoiner(e) {
	return e === 8205;
}
function IsRegionalIndicator(e) {
	return IsBetween(e, 127462, 127487);
}
function IsVariationSelector(e) {
	return IsBetween(e, 65024, 65039);
}
function IsCombiningMark(e) {
	return IsBetween(e, 768, 879) || IsBetween(e, 6832, 6911) || IsBetween(e, 7616, 7679) || IsBetween(e, 65056, 65071);
}
function CodePointLength(e) {
	return e > 65535 ? 2 : 1;
}
function ConsumeModifiers(e, t) {
	for (; t < e.length;) {
		let n = e.codePointAt(t);
		if (IsCombiningMark(n) || IsVariationSelector(n)) t += CodePointLength(n);
		else break;
	}
	return t;
}
function NextGraphemeClusterIndex(e, t) {
	let n = e.codePointAt(t), r = t + CodePointLength(n);
	for (r = ConsumeModifiers(e, r); r < e.length - 1 && IsZeroWidthJoiner(e.codePointAt(r));) {
		let t = e.codePointAt(r + 1);
		r += 1 + CodePointLength(t), r = ConsumeModifiers(e, r);
	}
	return IsRegionalIndicator(n) && r < e.length && IsRegionalIndicator(e.codePointAt(r)) && (r += CodePointLength(e.codePointAt(r))), r;
}
function GraphemeCount(e) {
	let t = 0, n = 0;
	for (; n < e.length;) n = NextGraphemeClusterIndex(e, n), t++;
	return t;
}
function IsArray(e) {
	return Array.isArray(e);
}
function IsBigInt(e) {
	return IsEqual(typeof e, "bigint");
}
function IsBoolean(e) {
	return IsEqual(typeof e, "boolean");
}
function IsConstructor(e) {
	if (IsUndefined(e) || !IsFunction(e)) return !1;
	let t = Function.prototype.toString.call(e);
	return !!(/^class\s/.test(t) || /\[native code\]/.test(t));
}
function IsFunction(e) {
	return IsEqual(typeof e, "function");
}
function IsInteger(e) {
	return Number.isInteger(e);
}
function IsNull(e) {
	return IsEqual(e, null);
}
function IsNumber(e) {
	return Number.isFinite(e);
}
function IsObjectNotArray(e) {
	return IsObject(e) && !IsArray(e);
}
function IsObject(e) {
	return IsEqual(typeof e, "object") && !IsNull(e);
}
function IsString(e) {
	return IsEqual(typeof e, "string");
}
function IsSymbol(e) {
	return IsEqual(typeof e, "symbol");
}
function IsUndefined(e) {
	return IsEqual(e, void 0);
}
function IsEqual(e, t) {
	return e === t;
}
function IsGreaterThan(e, t) {
	return e > t;
}
function IsLessThan(e, t) {
	return e < t;
}
function IsLessEqualThan(e, t) {
	return e <= t;
}
function IsGreaterEqualThan(e, t) {
	return e >= t;
}
function IsMultipleOf(e, t) {
	if (IsBigInt(e) || IsBigInt(t)) return BigInt(e) % BigInt(t) === 0n;
	let n = 1e-10;
	if (!IsNumber(e) || IsInteger(e) && 1 / t % 1 === 0) return !0;
	let r = e % t;
	return Math.min(Math.abs(r), Math.abs(r - t), Math.abs(r + t)) < n;
}
function IsClassInstance(e) {
	if (!IsObject(e)) return !1;
	let t = globalThis.Object.getPrototypeOf(e);
	return IsNull(t) ? !1 : IsEqual(typeof t.constructor, "function") && !(IsEqual(t.constructor, globalThis.Object) || IsEqual(t.constructor.name, "Object"));
}
function IsValueLike(e) {
	return IsBigInt(e) || IsBoolean(e) || IsNull(e) || IsNumber(e) || IsString(e) || IsUndefined(e);
}
function GraphemeCount2(e) {
	return GraphemeCount(e);
}
function CodePointCount2(e) {
	return CodePointCount(e);
}
function IsMaxLength2(e, t) {
	return IsMaxLength(e, t);
}
function IsMinLength2(e, t) {
	return IsMinLength(e, t);
}
function Every(e, t, n) {
	return e.every((e, r) => r < t || n(e, r));
}
function EveryAll(e, t, n) {
	let r = !0;
	return e.forEach((e, i) => {
		i >= t && !n(e, i) && (r = !1);
	}), r;
}
function Some(e, t) {
	return e.some((e, n) => t(e, n));
}
function SomeAll(e, t) {
	let n = !1;
	return e.forEach((e, r) => {
		t(e, r) && (n = !0);
	}), n;
}
function Counted(e, t) {
	return e.reduce((e, n, r) => t(n, r) ? ++e : e, 0);
}
function ShiftLeft(e, t, n) {
	return IsEqual(e.length, 0) ? n() : t(e[0], e.slice(1));
}
function IsUnsafePropertyKey(e) {
	return IsEqual(e, "__proto__") || IsEqual(e, "constructor") || IsEqual(e, "prototype");
}
function HasPropertyKey(e, t) {
	return IsUnsafePropertyKey(t) ? Object.prototype.hasOwnProperty.call(e, t) : t in e;
}
function EntriesRegExp(e) {
	return Keys(e).map((t) => [new RegExp(`^${t}$`), e[t]]);
}
function Entries(e) {
	return Object.entries(e);
}
function Keys(e) {
	return Object.getOwnPropertyNames(e);
}
function Symbols(e) {
	return Object.getOwnPropertySymbols(e);
}
function Values(e) {
	return Object.values(e);
}
function DeepEqualObject(e, t) {
	if (!IsObject(t)) return !1;
	let n = Keys(e);
	return IsEqual(n.length, Keys(t).length) && n.every((n) => IsDeepEqual(e[n], t[n]));
}
function DeepEqualArray(e, t) {
	return IsArray(t) && IsEqual(e.length, t.length) && e.every((n, r) => IsDeepEqual(e[r], t[r]));
}
function IsDeepEqual(e, t) {
	return IsArray(e) ? DeepEqualArray(e, t) : IsObject(e) ? DeepEqualObject(e, t) : IsEqual(e, t);
}
var globals_exports = {};
__export(globals_exports, {
	IsBigInt64Array: () => IsBigInt64Array,
	IsBigUint64Array: () => IsBigUint64Array,
	IsBoolean: () => IsBoolean2,
	IsDate: () => IsDate2,
	IsFloat32Array: () => IsFloat32Array,
	IsFloat64Array: () => IsFloat64Array,
	IsInt16Array: () => IsInt16Array,
	IsInt32Array: () => IsInt32Array,
	IsInt8Array: () => IsInt8Array,
	IsMap: () => IsMap,
	IsNumber: () => IsNumber2,
	IsRegExp: () => IsRegExp,
	IsSet: () => IsSet,
	IsString: () => IsString2,
	IsTypeArray: () => IsTypeArray,
	IsUint16Array: () => IsUint16Array,
	IsUint32Array: () => IsUint32Array,
	IsUint8Array: () => IsUint8Array,
	IsUint8ClampedArray: () => IsUint8ClampedArray
});
function IsBoolean2(e) {
	return e instanceof Boolean;
}
function IsNumber2(e) {
	return e instanceof Number;
}
function IsString2(e) {
	return e instanceof String;
}
function IsTypeArray(e) {
	return globalThis.ArrayBuffer.isView(e);
}
function IsInt8Array(e) {
	return e instanceof globalThis.Int8Array;
}
function IsUint8Array(e) {
	return e instanceof globalThis.Uint8Array;
}
function IsUint8ClampedArray(e) {
	return e instanceof globalThis.Uint8ClampedArray;
}
function IsInt16Array(e) {
	return e instanceof globalThis.Int16Array;
}
function IsUint16Array(e) {
	return e instanceof globalThis.Uint16Array;
}
function IsInt32Array(e) {
	return e instanceof globalThis.Int32Array;
}
function IsUint32Array(e) {
	return e instanceof globalThis.Uint32Array;
}
function IsFloat32Array(e) {
	return e instanceof globalThis.Float32Array;
}
function IsFloat64Array(e) {
	return e instanceof globalThis.Float64Array;
}
function IsBigInt64Array(e) {
	return e instanceof globalThis.BigInt64Array;
}
function IsBigUint64Array(e) {
	return e instanceof globalThis.BigUint64Array;
}
function IsRegExp(e) {
	return e instanceof globalThis.RegExp;
}
function IsDate2(e) {
	return e instanceof globalThis.Date;
}
function IsSet(e) {
	return e instanceof globalThis.Set;
}
function IsMap(e) {
	return e instanceof globalThis.Map;
}
var F64 = /* @__PURE__ */ new Float64Array(1);
var F64In = new DataView(F64.buffer);
var F64Out = new Uint8Array(F64.buffer);
var encoder = new TextEncoder();
var External = [
	/(^approval$)/u,
	/(^id$|^urlPath$|^createdAtMs$|^expiresAtMs$|^presentation$|^status$|^sourceSessionKey$)/u,
	/^(?!\.{1,2}$)(?:[^\uD800-\uDFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF])+$/u,
	/(^kind$|^commandText$|^commandPreview$|^warningText$|^streamProposal$|^host$|^nodeId$|^agentId$|^scope$|^allowedDecisions$)/u,
	/(^jobId$|^name$|^operation$)/u,
	/(^kind$|^target$|^recipientCount$|^recipients$|^audience$)/u,
	/(^kind$|^amount$|^currency$|^target$)/u,
	/(^kind$|^target$|^visibility$)/u,
	/(^kind$|^automation$|^command$|^expiresInDays$)/u,
	/(^kind$|^title$|^description$|^detail$|^severity$|^pluginId$|^toolName$|^agentId$|^scope$|^allowedDecisions$|^externalResolution$)/u,
	/(^label$|^decisions$)/u,
	/(^kind$|^title$|^description$|^proposalHash$|^agentId$|^allowedDecisions$)/u,
	/^[a-f0-9]{64}$/u,
	/(^id$|^urlPath$|^createdAtMs$|^expiresAtMs$|^presentation$|^resolvedAtMs$|^source$|^resolver$|^status$|^decision$|^reason$)/u,
	/(^agentId$|^sessionKey$)/u,
	/(^kind$|^id$)/u,
	/(^id$|^urlPath$|^createdAtMs$|^expiresAtMs$|^presentation$|^resolvedAtMs$|^source$|^resolver$|^status$|^decision$|^reason$)/u,
	/(^id$|^urlPath$|^createdAtMs$|^expiresAtMs$|^presentation$|^resolvedAtMs$|^source$|^resolver$|^status$|^reason$)/u,
	/(^id$|^urlPath$|^createdAtMs$|^expiresAtMs$|^presentation$|^resolvedAtMs$|^source$|^resolver$|^status$|^reason$)/u,
	/(^items$|^nextCursor$)/u,
	/(^applied$|^approval$)/u,
	/(^schemaVersion$|^receiptId$|^contextId$|^executionId$|^runId$|^actionId$|^occurredAt$|^representedSubject$|^action$|^decision$|^enforcement$|^source$|^missingEvidence$|^remediation$)/u,
	/(^state$|^principal$)/u,
	/(^kind$|^domainRef$|^principalRef$)/u,
	/(^family$|^operation$|^resourceRef$|^targetRef$|^summary$)/u,
	/(^outcome$|^reasonCode$)/u,
	/(^coverageState$|^evaluatorRef$|^policyRefs$|^grantRefs$|^contextFieldsUsed$)/u,
	/(^owner$|^recordRef$|^decisionBoundary$)/u,
	/(^code$|^text$)/u,
	/(^schemaVersion$|^contextId$|^executionId$|^runId$|^createdAt$|^trustDomain$|^invoker$|^ingress$|^agentPrincipal$|^agentDefinition$|^runtimeInstance$|^representedSubject$|^sponsor$|^applicableGrants$|^assurance$|^lineage$|^coverageState$|^missingEvidence$)/u,
	/(^kind$|^domainRef$|^state$)/u,
	/(^principal$|^state$)/u,
	/(^kind$|^domainRef$|^principalRef$|^displayLabel$)/u,
	/(^kind$|^sourceRef$|^boundary$|^state$)/u,
	/(^kind$|^domainRef$|^principalRef$|^displayLabel$)/u,
	/(^definitionRef$|^revisionRef$|^state$)/u,
	/(^runtimeRef$|^kind$|^state$)/u,
	/(^principal$|^state$)/u,
	/(^principal$|^relationshipRef$|^state$)/u,
	/(^grantRef$|^state$)/u,
	/(^kind$|^evidenceRef$|^strength$)/u,
	/(^parentContextId$|^parentExecutionId$|^parentRunId$|^parentAgentPrincipal$|^delegationRef$|^depth$)/u,
	/(^agentId$|^overwrite$)/u,
	/(^idempotencyKey$|^agentId$|^providerId$|^planFingerprint$|^itemIds$|^overwrite$)/u,
	/^[a-f0-9]{64}$/u,
	/(^durationMs$|^samplingIntervalBytes$|^includeCollected$|^includeObjectsCollectedByMajorGC$|^includeObjectsCollectedByMinorGC$)/u,
	/(^reason$)/u,
	/(^pluginId$|^path$|^baseHash$|^reveal$)/u,
	/(^source$|^pluginId$|^skillName$|^path$|^version$)/u,
	/(^source$|^catalogId$|^version$|^skillName$|^path$)/u,
	/(?!)/u,
	/(^action$|^person$|^deviceId$|^include$|^limit$)/u,
	/(^sessionKey$|^scope$)/u,
	/(^skillId$|^revision$|^sessionKey$)/u,
	/^[a-f0-9-]{36}$/u,
	/^[a-f0-9]{64}$/u,
	/(^skillId$|^expectedRevision$|^slug$|^content$|^files$|^retainFiles$)/u,
	/^[a-f0-9-]{36}$/u,
	/^[a-z0-9][a-z0-9-]{0,62}$/u,
	/(^path$|^content$|^encoding$|^executable$)/u,
	/(^skillId$|^expectedRevision$|^action$|^revision$)/u,
	/(^sessionKey$|^action$|^skillId$|^revision$)/u,
	/(^slug$|^source$)/u,
	/(^kind$|^slug$|^version$)/u,
	/(^action$|^slug$|^sizeBytes$|^sha256$)/u,
	/(^action$|^uploadId$|^offset$|^data$)/u,
	/(^action$|^uploadId$)/u,
	/(^text$|^idempotencyKey$|^sessionKey$|^wake$|^deviceId$|^instanceId$|^host$|^ip$|^mode$|^version$|^platform$|^deviceFamily$|^modelIdentifier$|^lastInputSeconds$|^reason$|^roles$|^scopes$|^tags$)/u,
	/(^agentId$|^modelProvider$|^modelId$)/u,
	/\S/u,
	/(^agentId$|^modelProvider$|^modelId$|^query$|^providerId$)/u,
	/(^binding$|^toolCallId$|^operation$|^review$)/u,
	/(^command$|^execCommand$|^cwd$|^environment$|^pty$)/u,
	/^\S(?:.*\S)?$/u,
	/(^argv$|^resolvedPath$|^envKeys$|^reason$|^analysis$)/u,
	/(^parsed$|^allowlistMatched$|^safeBinMatched$|^durableApprovalMatched$|^inlineEval$|^heredoc$|^shellWrapper$)/u,
	/(^binding$|^toolCallId$|^operation$|^id$|^warningText$)/u,
	/(^binding$|^toolCallId$|^operation$|^id$)/u,
	/(^generation$|^toolId$|^toolCallId$|^arguments$)/u,
	/^.*$/u,
	/(^generation$|^toolCallId$)/u,
	/(^type$|^event$|^payload$)/u,
	/(^generation$|^toolCallId$|^seq$|^result$)/u,
	/(^content$|^details$|^isError$|^terminate$|^progress$)/u,
	/(^type$|^text$|^textSignature$)/u,
	/(^type$|^data$|^mimeType$)/u,
	/(^text$|^visibility$|^privacy$|^id$)/u,
	/^\S(?:.*\S)?$/u,
	/(^key$|^agentId$|^profileId$|^deviceId$|^autoDevice$|^machineClass$|^os$)/u,
	/(^key$|^agentId$|^expected$|^target$|^abandonSource$)/u,
	/(^generation$|^environmentId$|^ownerEpoch$)/u,
	/(^kind$)/u,
	/(^kind$|^profileId$|^machineClass$|^os$)/u,
	/(^kind$|^deviceId$)/u,
	/(^coverage$|^children$|^truncated$)/u,
	/(^id$|^label$|^status$)/u,
	/(^operationId$|^action$|^sessionId$|^goalId$|^goal$|^runId$|^replayed$|^status$)/u,
	/(^schemaVersion$|^id$|^objective$|^status$|^createdAt$|^updatedAt$|^tokenStart$|^tokenStartFresh$|^tokensUsed$|^tokenBudget$|^continuationTurns$|^lastStatusNote$|^pausedAt$|^blockedAt$|^completedAt$|^usageLimitedAt$|^budgetLimitedAt$)/u,
	/(^ok$|^key$|^agentId$|^displayName$|^boardFace$|^boardPresentation$)/u,
	/(^ok$|^candidates$)/u,
	/(^key$|^agentId$|^displayName$|^boardFace$|^boardPresentation$)/u,
	/(^senderId$|^chatId$|^subagent$)/u,
	/(^agentId$|^sessionKey$|^catalog$|^cols$|^rows$)/u,
	/(^catalogId$|^hostId$|^threadId$|^agentId$|^sourceHomeId$)/u,
	/(^sessionId$|^data$)/u,
	/(^sessionId$|^cols$|^rows$)/u,
	/(^sessionId$)/u,
	/(^sessionId$|^name$|^contentBase64$)/u,
	/(^path$|^size$|^uploadPathStyle$)/u,
	/(^message$|^agentId$|^provider$|^model$|^to$|^replyTo$|^sessionId$|^sessionKey$|^createSessionIfMissing$|^expectedExistingSessionId$|^expectedExistingSessionLifecycleRevision$|^thinking$|^deliver$|^attachments$|^channel$|^replyChannel$|^accountId$|^replyAccountId$|^threadId$|^groupId$|^groupChannel$|^groupSpace$|^timeout$|^bestEffortDeliver$|^lane$|^cwd$|^cleanupBundleMcpOnRunEnd$|^modelRun$|^promptMode$|^extraSystemPrompt$|^bootstrapContextMode$|^bootstrapContextRunKind$|^acpTurnSource$|^internalRuntimeHandoffId$|^execApprovalFollowupExpectedSessionId$|^internalEvents$|^inputProvenance$|^suppressPromptPersistence$|^sessionEffects$|^sourceReplyDeliveryMode$|^disableMessageTool$|^swarmCollector$|^swarmOutputSchema$|^voiceWakeTrigger$|^idempotencyKey$|^label$)/u,
	/(^type$|^source$|^childSessionKey$|^childSessionId$|^announceType$|^taskLabel$|^status$|^statusLabel$|^result$|^noVisibleResult$|^modelRouteChange$|^attachments$|^mediaUrls$|^statsLine$|^replyInstruction$)/u,
	/(^type$|^path$|^url$|^mediaUrl$|^filePath$|^mimeType$|^name$|^sizeBytes$|^durationMs$|^width$|^height$)/u,
	/(^kind$|^originSessionId$|^sourceSessionKey$|^sourceChannel$|^sourceTool$|^sourceRole$|^sourcePromptPrefix$|^jobId$|^runId$)/u,
	/^.*$/u,
	/(^agentId$|^sessionKey$)/u,
	/(^runId$|^timeoutMs$)/u,
	/(^includeSessionPlacement$)/u,
	/(^name$|^agentId$|^onboarding$|^expectedOwnerId$|^workspace$|^model$|^emoji$|^avatar$)/u,
	/(^agentId$|^name$|^workspace$|^model$|^agentRuntime$|^emoji$|^avatar$)/u,
	/(^agentId$|^prompt$)/u,
	/\S/u,
	/(^name$|^description$|^svg$)/u,
	/(^agentId$|^deleteFiles$)/u,
	/(^agentId$)/u,
	/(^agentId$|^name$)/u,
	/(^agentId$|^name$|^content$|^expectedWorkspace$|^expectedHash$|^expectedMissing$)/u,
	/^[a-fA-F0-9]{64}$/u,
	/(^agentId$|^path$|^offset$|^limit$)/u,
	/(^agentId$|^path$)/u,
	/(^provider$|^apiKey$|^agentId$)/u,
	/\S/u,
	/(^provider$|^profileId$|^warning$)/u,
	/(^provider$|^profileIds$|^credentialType$|^agentId$)/u,
	/(^provider$|^profileIds$|^agentId$)/u,
	/(^operation$|^agentId$)/u,
	/(^refresh$|^refreshUsage$|^agentId$)/u,
	/(^agentId$|^sessionKey$|^authProfileId$|^provider$|^includeDetails$|^includeProviderCapabilities$|^includeDefaultModels$|^preparedOnly$|^refresh$|^view$)/u,
	/(^agentId$|^sessionKey$|^refresh$)/u,
	/(^agentId$|^includePlugins$)/u,
	/(^agentId$|^selectedScope$)/u,
	/(^agentId$|^selectedScope$|^selected$|^effective$)/u,
	/(^scope$|^configured$|^identity$)/u,
	/(^stale$|^source$|^credentialKind$|^credentialState$|^account$|^gitAuthor$|^evidence$|^accessExpiresAtMs$|^refreshState$|^oauthScopes$|^repositoryGrants$)/u,
	/(^login$)/u,
	/(^name$|^email$)/u,
	/\S/u,
	/(^scope$|^agentId$|^mode$|^secretName$|^gitAuthor$)/u,
	/^github-setup-[a-f0-9]{32}$/u,
	/(^name$|^email$)/u,
	/\S/u,
	/(^scope$|^agentId$|^mode$)/u,
	/(^scope$|^agentId$)/u,
	/(^requestId$|^userCode$|^verificationUri$|^expiresInMs$|^pollAfterMs$)/u,
	/^github-device-[a-f0-9]{32}$/u,
	/^[A-Z0-9]{4}-[A-Z0-9]{4}$/u,
	/(^requestId$)/u,
	/(^status$|^retryAfterMs$)/u,
	/(^status$|^retryAfterMs$)/u,
	/(^status$)/u,
	/(^status$)/u,
	/(^status$)/u,
	/(^status$|^retryAfterMs$)/u,
	/(^status$|^reason$)/u,
	/(^status$|^githubStatus$)/u,
	/(^cancelled$)/u,
	/(^sessionKey$|^agentId$)/u,
	/(^name$|^args$|^sessionKey$|^agentId$|^confirm$|^idempotencyKey$|^conversationReadOrigin$)/u,
	/(^agentId$|^name$|^installId$|^dangerouslyForceUnsafeInstall$|^timeoutMs$)/u,
	/(^agentId$|^source$|^slug$|^version$|^force$|^timeoutMs$)/u,
	/(^agentId$|^source$|^uploadId$|^slug$|^force$|^sha256$|^timeoutMs$)/u,
	/(^kind$|^slug$|^sizeBytes$|^sha256$|^force$|^idempotencyKey$)/u,
	/(^uploadId$|^offset$|^dataBase64$)/u,
	/(^uploadId$|^sha256$)/u,
	/(^skillKey$|^enabled$|^apiKey$|^env$)/u,
	/^.*$/u,
	/(^agentId$|^source$|^slug$|^all$|^force$)/u,
	/(^query$|^limit$)/u,
	/(^slug$|^version$)/u,
	/(^agentId$)/u,
	/(^agentId$|^limit$|^beforeMs$)/u,
	/(^agentId$|^name$|^filePath$|^versionId$|^draftId$)/u,
	/(^agentId$|^name$|^reason$)/u,
	/(^agentId$|^name$|^versionId$)/u,
	/(^agentId$|^runId$)/u,
	/(^agentId$|^skillKey$)/u,
	/(^agentId$|^path$)/u,
	/(^provider$|^profileId$|^timeoutMs$|^agentId$)/u,
	/(^agentId$|^channel$|^query$|^limit$)/u,
	/(^agentId$|^sourceSessionKey$|^operationId$|^conversationRef$|^message$)/u,
	/^conv_[a-f0-9]{32}$/u,
	/(^agentId$|^turnId$)/u,
	/(^agentId$|^sourceSessionKey$|^turnId$|^conversationRef$|^message$|^timeoutMs$)/u,
	/(^githubAccountIds$)/u,
	/(^sessionKey$|^agentId$|^query$)/u,
	/(^agentId$|^visibility$|^query$)/u,
	/(^users$|^truncated$)/u,
	/(^profileId$|^displayName$|^avatarUrl$|^online$)/u,
	/(^ids$)/u,
	/(^gatewayInstanceId$|^revision$|^items$)/u,
	/(^id$|^senderProfileId$|^senderLabel$|^senderAvatarUrl$|^sessionKey$|^agentId$|^sessionTitle$|^messageId$|^createdAt$|^expiresAt$|^excerpt$)/u,
	/(^gatewayInstanceId$|^revision$)/u,
	/(^gatewayInstanceId$|^sessionKey$|^agentId$|^messageId$|^errorMessage$)/u,
	/(^imageBase64$|^expectedAssetId$|^expectedPreference$)/u,
	/^[A-Za-z0-9_-]{1,128}$/u,
	/(^source$|^presentation$|^showOnNewSession$|^showInSessions$|^visibility$)/u,
	/(^kind$)/u,
	/(^kind$)/u,
	/(^kind$|^assetId$)/u,
	/(^expectedAssetId$|^expectedPreference$)/u,
	/(^keys$)/u,
	/^.{1,256}$/u,
	/(^entries$|^expectedEntries$)/u,
	/^.{1,256}$/u,
	/^.{1,256}$/u,
	/(^agentId$|^content$|^expectedHash$)/u,
	/(^requestId$)/u,
	IsUuid,
	/(^profile$)/u,
	/(^id$|^displayName$|^avatarMime$|^mergedInto$|^createdAt$|^updatedAt$|^emails$|^githubIdentity$|^hasAvatar$|^role$|^effectiveRole$|^roleSource$)/u,
	/(^host$|^login$|^profileUrl$|^avatarUrl$)/u,
	/\S/u,
	/(^email$|^targetProfileId$)/u,
	/(^sourceProfileId$|^targetProfileId$)/u,
	/(^profile$|^movedAliasKinds$)/u,
	/(^profileId$|^identity$)/u,
	/(^channelId$|^accountId$|^senderId$)/u,
	/^\S(?:.*\S)?$/u,
	/(^removed$)/u,
	/(^profileId$)/u,
	/(^links$)/u,
	/(^profileId$|^displayName$)/u,
	/(^profileId$|^role$)/u,
	/(^profileId$|^mime$|^avatarBase64$)/u,
	/(^profile$|^avatarRevision$)/u,
	/(^profileId$|^cursor$)/u,
	/(^profileId$|^authProfileId$)/u,
	/(^profileId$|^provider$|^method$)/u,
	/(^profileId$|^connectId$|^stepId$|^value$)/u,
	/(^profileId$|^connectId$)/u,
	/(^profileId$|^authProfileId$)/u,
	/(^profileId$|^provider$)/u,
	/(^sessionKey$|^agentId$|^cursor$|^knownState$|^limit$|^maxBytes$|^offset$|^pendingBefore$|^inputRunIds$|^messageId$|^sessionId$|^maxChars$|^toolResultMaxChars$)/u,
	/(^pendingInputs$|^sessionInfo$|^commands$)/u,
	/(^shortId$|^slugHint$|^agentId$|^limit$|^maxBytes$|^toolResultMaxChars$)/u,
	/(^agentId$|^includeModels$|^ifRevision$|^authProfileId$|^sessionKey$)/u,
	/(^sessionKey$|^agentId$|^sessionId$|^messageId$|^maxChars$)/u,
	/(^sessionKey$|^agentId$|^items$)/u,
	/(^id$|^name$|^input$)/u,
	/(^sessionKey$|^agentId$|^sessionId$|^inputIds$)/u,
	/(^sessionKey$|^runId$)/u,
	/(^sessionKey$|^agentId$|^sessionId$|^message$|^mentions$|^workContext$|^intent$|^thinking$|^fastMode$|^fastAutoOnSeconds$|^queueMode$|^deliver$|^originatingChannel$|^originatingTo$|^originatingAccountId$|^originatingThreadId$|^replyToId$|^attachments$|^toolBindings$|^timeoutMs$|^systemInputProvenance$|^systemProvenanceReceipt$|^suppressCommandInterpretation$|^expectedLeafEntryId$|^expectedSessionRoutingContract$|^expectedPermissionMode$|^expectedToolOverrides$|^idempotencyKey$)/u,
	/(^profileId$|^start$|^end$)/u,
	/(^page$|^title$|^sessionKey$|^sessionId$|^agentId$|^workspace$|^file$|^selection$|^detail$)/u,
	/^[\s\S]*$/u,
	/(^kind$|^version$|^issuedAtMs$)/u,
	/(^type$|^mimeType$|^fileName$|^origin$|^content$|^sizeBytes$|^durationMs$|^width$|^height$)/u,
	/^.*$/u,
	/(^mcpServers$|^mcpToolsDeny$|^skills$|^webSearch$)/u,
	/^.*$/u,
	/^.*$/u,
	/(^sessionKey$|^agentId$|^sessionId$|^runId$|^preserveSideRuns$|^discardPendingInput$)/u,
	/(^sessionKey$|^agentId$|^message$|^label$)/u,
	/(^limit$|^cursor$|^query$|^providerId$|^accountId$|^agentId$|^startedAfter$|^startedBefore$)/u,
	IsDateTime,
	/(^selector$)/u,
	/(^selector$|^includeUtterances$|^limit$|^cursor$|^query$)/u,
	/(^selector$|^format$)/u,
	/(^channel$|^action$|^params$|^reply$|^accountId$|^requesterAccountId$|^requesterSenderId$|^senderIsOwner$|^sessionKey$|^sessionId$|^inboundTurnKind$|^agentId$|^toolContext$|^conversationReadOrigin$|^idempotencyKey$)/u,
	/(^replyToId$|^source$)/u,
	/(^replyToId$|^source$|^mode$)/u,
	/(^currentChannelId$|^currentMessagingTarget$|^currentGraphChannelId$|^currentChannelProvider$|^currentThreadTs$|^currentMessageId$|^replyToMode$|^hasRepliedRef$|^sameChannelThreadRequired$|^skipCrossContextDecoration$)/u,
	/(^value$)/u,
	/(^to$|^message$|^mediaUrl$|^mediaUrls$|^buffer$|^filename$|^contentType$|^asVoice$|^gifPlayback$|^channel$|^accountId$|^agentId$|^replyToId$|^threadId$|^forceDocument$|^silent$|^parseMode$|^sessionKey$|^idempotencyKey$)/u,
	/(^to$|^question$|^options$|^maxSelections$|^durationSeconds$|^durationHours$|^silent$|^isAnonymous$|^threadId$|^channel$|^accountId$|^idempotencyKey$)/u,
	/(^endpoint$|^keys$)/u,
	/^https:\/\//u,
	/(^p256dh$|^auth$)/u,
	/(^endpoint$)/u,
	/(^title$|^body$)/u,
	/(^endpoint$|^scope$|^preferences$)/u,
	/(^categories$|^detailLevel$|^quietHours$|^agentIds$)/u,
	/(^approvalRequested$|^agentFinished$|^agentQuestion$|^humanMentioned$|^scheduledTaskFailed$)/u,
	/(^enabled$|^startMinute$|^endMinute$|^timeZone$)/u,
	/(^endpoint$|^scope$|^preferences$)/u,
	/(^enabled$|^label$|^categories$|^detailLevel$|^quietHours$|^agentIds$)/u,
	/(^approvalRequested$|^agentFinished$|^agentQuestion$|^humanMentioned$|^scheduledTaskFailed$)/u,
	/(^enabled$|^startMinute$|^endMinute$|^timeZone$)/u,
	/(^enabled$|^phase$)/u,
	/(^provider$|^model$|^sessionKey$)/u,
	/(^sessionKey$|^voiceSessionId$)/u,
	/(^sessionKey$|^voiceSessionId$|^voice$)/u,
	/(^changeId$|^voiceSessionId$|^outcome$|^error$)/u,
	/(^changeId$|^voiceSessionId$|^sessionKey$|^voice$|^phase$)/u,
	/(^includeSecrets$)/u,
	/(^config$)/u,
	/(^talk$|^session$|^ui$|^clientHints$)/u,
	/(^provider$|^providers$|^realtime$|^resolved$|^consultThinkingLevel$|^consultFastMode$|^speechLocale$|^interruptOnSpeech$|^silenceTimeoutMs$)/u,
	/^.*$/u,
	/(^apiKey$)/u,
	/(^source$|^provider$|^id$)/u,
	/^[a-z][a-z0-9_-]{0,63}$/u,
	/^[A-Z][A-Z0-9_]{0,127}$/u,
	/(^source$|^provider$|^id$)/u,
	/^\//u,
	/~(?:[^01]|$)/u,
	/(^source$|^provider$|^id$)/u,
	/^(?!.*(?:^|\/)\.{1,2}(?:\/|$))[A-Za-z0-9][A-Za-z0-9._:/#-]{0,255}$/u,
	/(^source$|^provider$|^id$)/u,
	/(^provider$|^providers$|^model$|^speakerVoice$|^speakerVoiceId$|^voice$|^instructions$|^mode$|^transport$|^vadThreshold$|^silenceDurationMs$|^prefixPaddingMs$|^reasoningEffort$|^brain$|^consultRouting$)/u,
	/(^provider$|^config$)/u,
	/(^mainKey$)/u,
	/(^seamColor$)/u,
	/(^realtime$)/u,
	/(^modelSource$|^gatewayRelaySupported$)/u,
	/(^sessionKey$|^voiceSessionId$|^voiceChangeId$|^provider$|^model$|^voice$|^vadThreshold$|^silenceDurationMs$|^prefixPaddingMs$|^reasoningEffort$|^mode$|^transport$|^brain$|^capabilities$)/u,
	/^[A-Za-z0-9_-]{1,128}$/u,
	/(^provider$|^transport$|^voiceSessionId$|^clientSecret$|^offerUrl$|^offerHeaders$|^model$|^voice$|^expiresAt$|^clientControl$)/u,
	/(^owner$)/u,
	/(^provider$|^transport$|^voiceSessionId$|^protocol$|^clientSecret$|^websocketUrl$|^audio$|^initialMessage$|^model$|^voice$|^expiresAt$)/u,
	/(^inputEncoding$|^inputSampleRateHz$|^outputEncoding$|^outputSampleRateHz$)/u,
	/(^provider$|^transport$|^voiceSessionId$|^relaySessionId$|^audio$|^model$|^voice$|^expiresAt$)/u,
	/(^provider$|^transport$|^voiceSessionId$|^roomUrl$|^token$|^model$|^voice$|^expiresAt$)/u,
	/(^sessionKey$|^voiceSessionId$)/u,
	/(^ok$)/u,
	/(^sessionKey$|^voiceSessionId$|^callId$|^name$|^args$|^relaySessionId$)/u,
	/(^runId$|^idempotencyKey$|^agentId$|^agentSessionKey$)/u,
	/(^sessionKey$|^voiceSessionId$|^entryId$|^role$|^text$|^timestamp$)/u,
	/(^sessionKey$|^voiceSessionId$|^text$)/u,
	/(^sessionKey$|^text$|^mode$)/u,
	/(^sessionKey$|^voiceChangeId$|^capabilities$|^spawnedBy$|^provider$|^model$|^voice$|^language$|^vadThreshold$|^silenceDurationMs$|^prefixPaddingMs$|^reasoningEffort$|^mode$|^transport$|^brain$|^ttlMs$)/u,
	/^[a-z]{2}$/u,
	/(^sessionId$|^audioBase64$|^timestamp$)/u,
	/(^sessionId$|^markName$)/u,
	/(^sessionId$|^turnId$|^reason$)/u,
	/(^ok$|^status$|^turnId$)/u,
	/(^sessionId$|^sessionKey$|^text$|^mode$)/u,
	/(^sessionId$|^callId$|^result$|^options$)/u,
	/(^suppressResponse$|^willContinue$)/u,
	/(^sessionId$|^disposition$|^discard$)/u,
	/(^text$|^voiceId$|^modelId$|^outputFormat$|^speed$|^rateWpm$|^stability$|^similarity$|^style$|^speakerBoost$|^seed$|^normalize$|^language$|^latencyTier$)/u,
	/(^probe$|^timeoutMs$|^channel$)/u,
	/(^channel$|^accountId$)/u,
	/(^format$|^channel$|^accountId$|^expectedOwnerId$)/u,
	/(^channel$|^accountId$|^requestId$|^notify$|^bootstrapCommandOwner$)/u,
	/(^channel$|^accountId$|^code$|^expectedOwnerId$)/u,
	/(^channel$|^accountId$|^requestId$)/u,
	/(^channel$|^accountId$)/u,
	/(^pluginId$|^title$|^description$|^detail$|^severity$|^scope$|^toolName$|^toolCallId$|^policySubject$|^mcpTool$|^allowedDecisions$|^agentId$|^sessionKey$|^approvalReviewerDeviceIds$|^turnSourceChannel$|^turnSourceTo$|^turnSourceAccountId$|^turnSourceThreadId$|^timeoutMs$|^twoPhase$)/u,
	/(^pluginKey$|^tool$)/u,
	/(^server$|^tool$)/u,
	/\S/u,
	/(^id$|^decision$|^reviewer$)/u,
	/(^channel$|^accountId$|^senderId$)/u,
	/(^pluginId$)/u,
	/(^source$|^packageName$|^version$)/u,
	/(^catalogId$|^version$)/u,
	/^[A-Za-z0-9_-]+$/u,
	/(^plugins$|^waitForDrain$|^acknowledgeCapabilities$)/u,
	/(^pluginId$|^installHash$|^sourceDigests$)/u,
	/^.*$/u,
	/(^reviewToken$)/u,
	/(^query$|^limit$)/u,
	/(^query$|^searchSource$|^intent$|^category$|^cursor$|^pageSize$)/u,
	/^[a-z][a-z0-9-]*$/u,
	/(^id$|^version$)/u,
	/(^enable$|^mode$|^acknowledgeInstallPolicyWarning$|^acknowledgeCapabilities$|^source$|^packageName$|^version$|^expectedPluginId$|^expectedIntegrity$)/u,
	/(^enable$|^mode$|^acknowledgeInstallPolicyWarning$|^acknowledgeCapabilities$|^source$|^pluginId$|^version$|^pin$)/u,
	/(^enable$|^mode$|^acknowledgeInstallPolicyWarning$|^acknowledgeCapabilities$|^source$|^spec$|^pin$|^expectedPluginId$|^expectedIntegrity$)/u,
	/(^enable$|^mode$|^acknowledgeInstallPolicyWarning$|^acknowledgeCapabilities$|^source$|^spec$)/u,
	/(^enable$|^mode$|^acknowledgeInstallPolicyWarning$|^acknowledgeCapabilities$|^source$|^path$|^link$)/u,
	/(^enable$|^mode$|^acknowledgeInstallPolicyWarning$|^acknowledgeCapabilities$|^source$|^archivePath$)/u,
	/(^enable$|^mode$|^acknowledgeInstallPolicyWarning$|^acknowledgeCapabilities$|^source$|^marketplace$|^plugin$)/u,
	/(^enable$|^mode$|^acknowledgeInstallPolicyWarning$|^acknowledgeCapabilities$|^source$|^pluginId$|^spec$)/u,
	/(^pluginId$|^enabled$|^allowlistPolicy$|^acknowledgeCapabilities$)/u,
	/(^pluginId$|^keepFiles$)/u,
	/(^ok$|^descriptors$|^generation$|^methods$|^controlUiTabs$|^controlUiWidgetKinds$|^controlUiLinkReaders$|^pluginSurfaceUrls$)/u,
	/(^id$|^pluginId$|^pluginName$|^surface$|^linkReader$|^label$|^description$|^icon$|^path$|^placement$|^group$|^order$|^version$|^schema$|^requiredScopes$)/u,
	/(^hosts$|^pathPattern$|^detailMethod$|^previewMethod$|^imageMethod$|^sessionScoped$|^progressive$)/u,
	/(^pluginId$|^id$|^label$|^description$|^icon$|^path$|^placement$|^slug$|^requiresGatewayAuth$|^group$|^order$)/u,
	/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,
	/(^pluginId$|^kind$|^label$)/u,
	/(^pluginId$|^id$|^label$|^icon$|^linkReader$)/u,
	/(^hosts$|^pathPattern$|^detailMethod$|^previewMethod$|^imageMethod$|^sessionScoped$|^progressive$)/u,
	/^.*$/u,
	/(^pluginId$)/u,
	/(^reports$)/u,
	/(^pluginId$|^revision$|^status$|^error$)/u,
	/(^pluginId$|^actionId$|^sessionKey$|^agentId$|^payload$)/u,
	/(^ok$|^result$|^continueAgent$|^reply$)/u,
	/(^ok$|^error$|^code$|^details$)/u,
	/(^channel$|^force$|^timeoutMs$|^verbose$|^accountId$)/u,
	/(^channel$|^sessionKey$|^timeoutMs$|^accountId$|^currentQrDataUrl$)/u,
	/^data:image\/png;base64,/u,
	/(^sessionKey$|^agentId$|^provider$|^scope$|^includeArgs$)/u,
	/(^expectedOwnerId$|^outcome$)/u,
	/(^createdAt$|^archivePath$|^status$|^kind$|^target$|^namespace$|^error$|^pushFailed$|^bytes$|^location$|^retention$)/u,
	/(^name$|^provider$|^locationId$|^key$|^namespace$|^plaintextBytes$|^storedBytes$)/u,
	/(^kept$|^deleted$)/u,
	/(^name$)/u,
	/(^probe$)/u,
	/(^command$|^params$|^generation$|^timeoutMs$|^idempotencyKey$)/u,
	/(^agentId$|^sessionKey$|^runId$|^kind$|^status$|^direction$|^channel$|^after$|^before$|^limit$|^cursor$)/u,
	/(^runId$|^executionId$|^executionCursor$|^executionLimit$|^decisionCursor$|^decisionLimit$)/u,
	/(^agentId$|^sessionKey$|^runId$|^kind$|^status$|^after$|^before$|^limit$|^cursor$)/u,
	/(^mode$|^text$|^sessionKey$|^agentId$)/u,
	/(^sessionKey$|^agentId$|^markdown$|^plan$|^expectedRevision$)/u,
	/(^step$|^status$)/u,
	/(^sessionKey$|^agentId$|^idempotencyKey$)/u,
	/(^sessionKey$|^runId$|^agentId$|^messageRole$|^type$|^limit$|^cursor$)/u,
	/(^sessionKey$|^runId$|^agentId$|^messageRole$|^artifactId$)/u,
	/(^sessionKey$|^runId$|^agentId$|^messageRole$|^artifactId$|^transport$|^previewWidth$)/u,
	/(^profileId$|^idempotencyKey$)/u,
	/(^sessionKey$|^agentId$|^profileId$|^idempotencyKey$|^machineClass$|^os$|^presentation$)/u,
	/(^sessionKey$|^agentId$|^environmentId$)/u,
	/(^sessionKey$|^agentId$|^environmentId$|^action$|^processId$|^argv$|^input$|^timeoutMs$)/u,
	/^[A-Za-z0-9][A-Za-z0-9._:-]*$/u,
	{ check: hasValidSessionExecAction },
	/(^profileId$|^projectPath$)/u,
	/(^environmentId$|^preparationKey$|^reused$)/u,
	/(^environmentId$|^force$)/u,
	/(^runtimeId$|^projection$|^includeDesktopSetup$|^includePreparedDetails$)/u,
	/(^environmentId$|^includePreparedDetails$)/u,
	/(^environmentId$)/u,
	/(^environmentId$|^port$|^title$|^description$|^path$)/u,
	/^\//u,
	/(^id$|^environmentId$)/u,
	/(^source$|^control$|^credentials$)/u,
	/(^kind$)/u,
	/(^username$|^password$)/u,
	/(^source$|^control$)/u,
	/(^kind$|^environmentId$)/u,
	/(^source$|^control$|^credentials$)/u,
	/(^kind$|^nodeId$)/u,
	/(^transport$|^wsPath$|^expiresAtMs$|^control$|^audio$|^audioUnavailableReason$|^canResize$|^vncPassword$|^auth$|^preauthenticated$)/u,
	/(^wsPath$|^encoding$|^sampleRate$|^channels$)/u,
	/(^source$|^app$)/u,
	/(^wsPath$)/u,
	/(^released$)/u,
	/(^machineName$|^hostname$|^platform$|^release$|^arch$|^osLabel$|^lanAddress$|^port$|^nodeVersion$|^pid$|^processInstanceId$|^uptimeMs$|^cpuCount$|^cpuModel$|^loadAverage$|^memoryTotalBytes$|^memoryFreeBytes$|^eventLoop$|^processMemory$|^diskTotalBytes$|^diskAvailableBytes$|^diskPath$|^disks$|^defaultAgentUtilityModel$)/u,
	/(^degraded$|^degradedSinceMs$|^reasons$|^intervalMs$|^delayP99Ms$|^delayMaxMs$|^utilization$|^cpuCoreRatio$|^cpuBreakdown$)/u,
	/(^mainThreadCoreRatio$|^workerCoreRatio$|^otherThreadsCoreRatio$|^hostUtilization$|^hostCpuCount$)/u,
	/(^rssBytes$|^heapUsedBytes$|^heapTotalBytes$|^externalBytes$|^arrayBuffersBytes$)/u,
	/(^path$|^totalBytes$|^availableBytes$)/u,
	/(^status$|^model$|^runtime$)/u,
	/(^id$|^kind$|^label$)/u,
	/(^status$|^model$|^runtime$)/u,
	/(^status$)/u,
	/(^status$)/u,
	/(^observedAt$|^status$|^people$|^devices$|^totalPeople$|^truncated$|^message$)/u,
	/(^id$|^profileId$|^name$|^online$|^onlineSince$|^activity$|^deviceCount$|^devices$)/u,
	/(^at$|^source$|^deviceId$)/u,
	/(^id$|^nodeId$|^name$|^kind$|^personIds$|^online$|^activity$|^connections$)/u,
	/(^id$|^clientId$|^platform$|^deviceFamily$|^timeZone$|^network$|^location$)/u,
	/(^ip$)/u,
	/(^source$|^status$|^city$|^region$|^country$|^countryCode$|^attribution$)/u,
	/(^text$|^url$)/u,
	/(^nodeId$|^title$|^body$|^environment$)/u,
	/(^commandName$|^targetIds$|^allowedPaths$|^forcedActivePaths$|^optionalActivePaths$|^providerOverrides$)/u,
	/(^webSearch$|^webFetch$)/u,
	/(^ok$|^assignments$|^diagnostics$|^inactiveRefPaths$)/u,
	/(^path$|^pathSegments$|^value$)/u,
	/(^entries$)/u,
	/(^name$|^scopeKind$|^scopeId$|^createdAtMs$|^updatedAtMs$|^updatedBy$|^kind$|^allowedHosts$)/u,
	/^[A-Z][A-Z0-9_]{0,127}$/u,
	/(^name$|^scopeKind$|^scopeId$|^createdAtMs$|^updatedAtMs$|^updatedBy$|^kind$|^value$)/u,
	/(^expectedOwnerId$|^inheritExistingKind$|^valueSource$|^name$|^value$|^kind$|^allowedHosts$)/u,
	/^(?:[A-Z][A-Z0-9_]{0,127}|github-setup-[a-f0-9]{32})$/u,
	/(^expectedOwnerId$|^name$)/u,
	/(^expectedOwnerId$|^inheritExistingKind$|^entries$)/u,
	/(^name$|^value$|^kind$)/u,
	/(^expectedOwnerId$|^name$|^allowedHosts$)/u,
	/(^ok$|^reloaded$|^kind$|^warningCount$)/u,
	/(^sessionKey$|^agentId$)/u,
	/(^title$|^prompt$|^tldr$|^cwd$|^sessionKey$|^agentId$)/u,
	/\S/u,
	/\S/u,
	/\S/u,
	/(^taskId$|^mode$|^cloudProfileId$|^cwd$)/u,
	/(^taskId$|^reason$)/u,
	/(^raw$|^baseHash$)/u,
	/(^raw$|^baseHash$|^sessionKey$|^deliveryContext$|^note$|^restartDelayMs$)/u,
	/(^channel$|^to$|^accountId$|^threadId$)/u,
	/(^raw$|^baseHash$|^sessionKey$|^deliveryContext$|^note$|^restartDelayMs$|^replacePaths$|^response$)/u,
	/(^path$)/u,
	/^[A-Za-z0-9_./\[\]\-*]+$/u,
	/(^path$|^schema$|^reloadKind$|^hint$|^hintPath$|^children$)/u,
	/(^label$|^help$|^docsUrl$|^tags$|^group$|^groups$|^order$|^advanced$|^sensitive$|^placeholder$|^multiline$|^presentation$|^itemTemplate$)/u,
	/(^id$|^title$|^order$|^properties$)/u,
	/(^key$|^path$|^type$|^required$|^hasChildren$|^reloadKind$|^hint$|^hintPath$)/u,
	/(^sessionId$|^message$|^wizardAnswer$|^wizardCancel$|^welcomeVariant$|^reset$|^context$|^delegation$)/u,
	/(^stepId$|^value$)/u,
	/(^stepId$)/u,
	/(^page$|^plugin$)/u,
	/^[A-Za-z0-9/_-]{1,64}$/u,
	/(^id$|^name$|^installed$|^declared$|^setting$)/u,
	/^[A-Za-z0-9@][A-Za-z0-9@._/-]{0,127}$/u,
	/(^tools$|^providers$|^channels$|^contracts$|^skills$|^mcpServers$|^incomplete$)/u,
	/(^path$|^label$)/u,
	/(^agentId$|^sessionKey$|^turnSourceChannel$|^turnSourceTo$|^turnSourceAccountId$|^turnSourceThreadId$)/u,
	/(^limit$)/u,
	/(^limit$|^beforeCursor$)/u,
	/(^modelTarget$|^agentId$)/u,
	/(^modelTarget$|^agentId$|^kind$|^modelRef$|^authChoice$|^apiKey$|^workspace$|^nativeSessionCatalogsEnabled$)/u,
	/^provider-auto:.+$/u,
	/^saved-auth:.+$/u,
	/(^modelTarget$|^agentId$|^kind$|^modelRef$|^authChoice$|^apiKey$|^workspace$|^nativeSessionCatalogsEnabled$|^sessionId$)/u,
	/(^expectedOwnerId$|^modelTarget$|^sessionId$|^agentId$|^authChoice$|^selectModel$|^workspace$|^nativeSessionCatalogsEnabled$)/u,
	/(^sessionId$|^agentId$|^runtimeId$|^configPatch$)/u,
	/(^mode$|^workspace$|^installDaemon$|^flow$|^channel$)/u,
	/(^sessionId$|^serverName$)/u,
	/(^sessionId$|^answer$)/u,
	/(^sessionId$|^closeInput$)/u,
	/(^text$)/u,
	/(^sessionKey$|^sessionAgentId$|^includeDisabled$|^limit$|^offset$|^query$|^enabled$|^scheduleKind$|^lastRunStatus$|^trigger$|^sortBy$|^sortDir$|^agentId$|^compact$|^includeDeliveryPreviews$)/u,
	/(^id$)/u,
	/(^jobId$)/u,
	/(^name$|^declarationKey$|^displayName$|^owner$|^agentId$|^sessionKey$|^description$|^enabled$|^deleteAfterRun$|^schedule$|^pacing$|^activeHours$|^idleOnly$|^trigger$|^sessionTarget$|^wakeMode$|^payload$|^delivery$|^failureAlert$)/u,
	/\S/u,
	/(^agentId$|^sessionKey$|^accountId$)/u,
	/(^kind$|^source$|^options$)/u,
	/^[a-z0-9][a-z0-9._-]*$/u,
	/(^kind$|^at$)/u,
	/(^kind$|^everyMs$|^anchorMs$)/u,
	/(^kind$|^expr$|^tz$|^staggerMs$)/u,
	/(^kind$|^command$|^cwd$)/u,
	/(^kind$|^command$|^cwd$|^mode$|^match$|^batchMs$|^maxBatchBytes$)/u,
	/(^min$|^max$)/u,
	/(^start$|^end$|^timezone$)/u,
	/^([01][0-9]|2[0-3]):[0-5][0-9]$/u,
	/^(([01][0-9]|2[0-3]):[0-5][0-9]|24:00)$/u,
	/(^script$|^once$)/u,
	/^session:.+/u,
	/(^kind$|^text$|^toolsAllow$|^toolsAllowIsDefault$)/u,
	/(^kind$|^message$|^model$|^fallbacks$|^thinking$|^timeoutSeconds$|^allowUnsafeExternalContent$|^lightContext$|^skipIfScratchEmpty$|^includeReasoning$|^toolsAllow$|^toolsAllowIsDefault$)/u,
	/(^kind$|^argv$|^cwd$|^env$|^input$|^timeoutSeconds$|^noOutputTimeoutSeconds$|^outputMaxBytes$|^toolsAllow$|^toolsAllowIsDefault$)/u,
	/(^kind$|^script$|^timeoutSeconds$|^toolBudget$|^toolsAllow$|^toolsAllowIsDefault$)/u,
	/(^mode$|^channel$|^threadId$|^accountId$|^bestEffort$|^failureDestination$|^target$|^directPolicy$|^to$)/u,
	/(^channel$|^to$|^mode$|^accountId$)/u,
	/(^mode$|^channel$|^threadId$|^accountId$|^bestEffort$|^failureDestination$|^target$|^directPolicy$|^completionDestination$|^to$)/u,
	/(^mode$|^to$)/u,
	/(^mode$|^channel$|^threadId$|^accountId$|^bestEffort$|^failureDestination$|^to$)/u,
	/(^after$|^channel$|^to$|^cooldownMs$|^includeSkipped$|^mode$|^accountId$)/u,
	/(^id$|^patch$|^expectedConfigRevision$)/u,
	/(^name$|^displayName$|^agentId$|^sessionKey$|^description$|^enabled$|^deleteAfterRun$|^schedule$|^pacing$|^activeHours$|^idleOnly$|^trigger$|^sessionTarget$|^wakeMode$|^payload$|^delivery$|^failureAlert$|^state$)/u,
	/\S/u,
	/(^min$|^max$)/u,
	/(^start$|^end$|^timezone$)/u,
	/(^script$|^once$)/u,
	/(^kind$|^text$|^toolsAllow$|^toolsAllowIsDefault$)/u,
	/(^kind$|^message$|^model$|^fallbacks$|^thinking$|^timeoutSeconds$|^allowUnsafeExternalContent$|^lightContext$|^skipIfScratchEmpty$|^includeReasoning$|^toolsAllow$|^toolsAllowIsDefault$)/u,
	/(^kind$|^argv$|^cwd$|^env$|^input$|^timeoutSeconds$|^noOutputTimeoutSeconds$|^outputMaxBytes$|^toolsAllow$|^toolsAllowIsDefault$)/u,
	/(^kind$|^script$|^timeoutSeconds$|^toolBudget$|^toolsAllow$|^toolsAllowIsDefault$)/u,
	/(^mode$|^target$|^directPolicy$|^channel$|^threadId$|^accountId$|^bestEffort$|^failureDestination$|^completionDestination$|^to$)/u,
	/(^channel$|^to$|^mode$|^accountId$)/u,
	/(^mode$|^to$)/u,
	/(^after$|^channel$|^to$|^cooldownMs$|^includeSkipped$|^mode$|^accountId$)/u,
	/(^nextRunAtMs$|^runningAtMs$|^lastRunAtMs$|^lastRunStatus$|^lastStatus$|^lastError$|^lastErrorReason$|^lastDurationMs$|^consecutiveErrors$|^consecutiveSkipped$|^lastDelivered$|^lastDeliveryStatus$|^lastDeliveryError$|^lastFailureNotificationDelivered$|^lastFailureNotificationDeliveryStatus$|^lastFailureNotificationDeliveryError$|^lastFailureAlertAtMs$|^lastTriggerEvalAtMs$|^triggerEvalCount$|^lastTriggerFireAtMs$|^triggerState$|^streamStatus$|^streamError$|^streamConsecutiveFailures$|^streamRestartExhausted$|^streamDroppedBatches$|^streamCoalescedBatches$|^streamLastStartedAtMs$|^streamLastExitAtMs$)/u,
	/(^jobId$|^patch$|^expectedConfigRevision$)/u,
	/(^id$|^expectedConfigRevision$)/u,
	/(^jobId$|^expectedConfigRevision$)/u,
	/(^id$|^mode$|^expectedProcessInstanceId$|^waitTimeoutMs$)/u,
	/(^jobId$|^mode$|^expectedProcessInstanceId$|^waitTimeoutMs$)/u,
	/(^agentId$|^view$|^scope$|^id$|^jobId$|^runId$|^limit$|^offset$|^statuses$|^status$|^deliveryStatuses$|^deliveryStatus$|^query$|^sortDir$)/u,
	/^[^/\\]+$/u,
	/(^id$|^runId$|^runAtMs$|^cursor$|^limit$)/u,
	/(^id$|^content$|^expectedRevision$)/u,
	/(^jobId$|^content$|^expectedRevision$)/u,
	/(^scopes$)/u,
	/(^requestId$)/u,
	/(^id$)/u,
	/(^cursor$|^limit$|^kind$)/u,
	/(^id$|^kind$|^decision$|^reviewer$|^grantExpiresInDays$)/u,
	/(^expectedOwnerId$)/u,
	/(^file$|^baseHash$|^expectedOwnerId$)/u,
	/(^version$|^socket$|^defaults$|^agents$)/u,
	/(^path$|^token$)/u,
	/(^security$|^ask$|^askFallback$|^autoAllowSkills$)/u,
	/^.*$/u,
	/(^security$|^ask$|^askFallback$|^autoAllowSkills$|^allowlist$|^mcpTools$)/u,
	/(^id$|^pattern$|^source$|^commandText$|^argPattern$|^lastUsedAt$|^lastUsedCommand$|^lastResolvedPath$)/u,
	/(^server$|^tool$|^source$|^addedAt$|^lastUsedAt$)/u,
	/(^agentId$|^command$|^uses$|^grants$|^authorization$|^expectedOwnerId$)/u,
	/(^match$|^resolvedPath$)/u,
	/(^pattern$|^argPattern$|^resolvedPath$)/u,
	/(^source$|^security$|^ask$|^allowlistSatisfied$|^policySnapshot$|^requireAutoAllowSkills$)/u,
	/(^security$|^ask$|^askFallback$|^autoAllowSkills$|^allowlistRules$)/u,
	/(^pattern$|^argPattern$|^source$)/u,
	/(^operation$)/u,
	/(^operation$|^file$|^baseHash$)/u,
	/(^operation$|^agentId$|^command$|^uses$|^grants$|^authorization$)/u,
	/(^id$|^command$|^commandArgv$|^systemRunPlan$|^env$|^cwd$|^nodeId$|^host$|^security$|^ask$|^warningText$|^scope$|^unavailableDecisions$|^commandSpans$|^agentId$|^resolvedPath$|^sessionKey$|^sessionId$|^runId$|^toolCallId$|^turnSourceChannel$|^turnSourceTo$|^turnSourceAccountId$|^turnSourceThreadId$|^approvalReviewerDeviceIds$|^requireDeliveryRoute$|^suppressDelivery$|^deliverToApprovalClientsOnly$|^timeoutMs$|^twoPhase$)/u,
	/(^argv$|^cwd$|^commandText$|^commandPreview$|^agentId$|^sessionKey$|^policySnapshot$|^mutableFileOperand$)/u,
	/(^argvIndex$|^path$|^sha256$)/u,
	/(^startIndex$|^endIndex$)/u,
	/(^id$|^decision$|^reviewer$|^grantExpiresInDays$)/u,
	/(^limit$)/u,
	/(^grantId$)/u,
	/(^id$|^questions$|^agentId$|^sessionKey$|^runId$|^timeoutMs$)/u,
	/(^questionId$|^header$|^question$|^url$|^options$|^presentation$|^resource$|^multiSelect$|^answerFormat$|^allowEmpty$|^defaultAnswers$|^isOther$|^isSecret$|^secretStore$)/u,
	/^[a-z][a-z0-9_]*$/u,
	/(^label$|^description$|^value$|^thumbnail$|^resourceUri$|^preview$)/u,
	/(^type$|^name$|^arguments$)/u,
	/(^type$|^uri$|^name$|^title$|^description$|^mimeType$)/u,
	/(^viewId$|^selection$|^userOptions$)/u,
	/(^kind$|^accept$)/u,
	/(^name$|^kind$|^allowedHosts$|^reason$)/u,
	/(^id$|^timeoutMs$|^includeResolutionId$)/u,
	/(^id$|^answers$|^secretStoreAllowedHosts$|^resolvedBy$|^resolutionId$)/u,
	/(^answers$)/u,
	/^[a-z][a-z0-9_]*$/u,
	/(^id$|^cancel$|^resolvedBy$)/u,
	/(^capabilityConsentCode$|^pluginId$|^reviewToken$|^widened$|^acceptedAt$)/u,
	/(^channels$|^providers$|^tools$|^contracts$|^hooks$|^mcpServers$|^cliCommands$|^cliBackends$|^skills$|^dangerousConfigFlags$)/u,
	/(^cursor$|^limit$|^maxBytes$)/u,
	/(^refreshCheckout$)/u,
	/(^sentinel$|^updateAvailable$|^activeRun$|^lastRun$|^effectiveChannel$|^schedule$)/u,
	/(^currentVersion$|^latestVersion$|^channel$|^currentSha$|^upstreamRef$|^upstreamSha$|^repositoryUrl$|^commitsBehind$|^commits$)/u,
	/(^sha$|^subject$)/u,
	/(^runId$|^createdAtMs$|^updatedAtMs$|^trigger$|^phase$|^status$|^reason$|^admission$|^origin$|^target$|^before$|^after$|^steps$|^verification$|^repair$|^confirmedAtMs$|^finishedAtMs$|^downtimeMs$)/u,
	/^(ocm:[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}|[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/u,
	/(^owner$|^protocol$|^candidateVersion$|^checks$|^fallbackReason$)/u,
	/(^name$|^status$|^detail$)/u,
	/(^admission$|^candidateAdmission$|^driver$|^previousDrivers$|^requester$|^sessionKey$|^deliveryContext$|^campaignId$|^doctorHint$|^nextAction$)/u,
	/(^protocol$|^verdict$|^reasons$|^warnings$|^facts$)/u,
	/(^code$|^message$|^nextAction$)/u,
	/(^code$|^message$)/u,
	/(^candidateVersion$|^installedVersion$|^nodeEngines$|^checks$)/u,
	/(^host$|^pid$|^startIdentity$)/u,
	/^\d+$/u,
	/(^host$|^pid$|^startIdentity$)/u,
	/(^channel$|^accountId$|^senderId$|^authorizationSource$)/u,
	/(^channel$|^to$|^accountId$|^threadId$)/u,
	/(^channel$|^tag$|^kind$|^version$|^sha$|^installationMethod$)/u,
	/(^version$|^sha$|^buildId$)/u,
	/(^step$|^status$|^startedAtMs$|^endedAtMs$|^exitCode$|^termination$|^signal$|^stderrTail$|^detail$|^failureFacts$|^configChange$|^configWriteRefusal$|^snapshotCapacity$)/u,
	/(^check$|^code$|^message$|^npmErrorCode$|^packageSpec$|^affectedKey$|^pluginId$|^errorName$|^location$|^destination$)/u,
	/(^ownership$|^cause$|^destinationKind$|^prefix$|^packageRoot$|^runningRoot$|^runningPrefix$|^launcher$|^launcherTarget$)/u,
	/(^kind$|^key$)/u,
	/(^kind$|^message$)/u,
	/(^reason$|^message$|^keys$)/u,
	/(^sqliteBytes$|^pluginBytes$|^requiredBytes$|^reason$|^candidates$|^selection$)/u,
	/(^kind$|^directory$|^availableBytes$|^allocationError$)/u,
	/(^kind$|^directory$)/u,
	/(^rollbackOutcome$|^recovery$|^booted$|^runningVersion$|^runningBuildId$|^serviceRunning$|^pid$|^port$|^versionMatch$|^pluginErrors$|^channelsReady$|^readyz$|^coreReady$|^settled$|^noticeDelivered$|^doctorHint$)/u,
	/(^status$|^reason$)/u,
	/(^serviceRestartSafe$|^packageRollbackVerified$|^version$|^buildId$|^service$|^reason$)/u,
	/(^serviceRestartSafe$|^packageRollbackVerified$|^reason$)/u,
	/(^attempt$|^status$|^startedAtMs$|^endedAtMs$|^summary$|^reason$)/u,
	/(^channel$|^autoEnabled$|^install$|^target$|^campaign$)/u,
	/(^kind$|^git$|^immutable$)/u,
	/(^currentSha$|^upstreamSha$|^repositoryUrl$|^commitAtMs$|^installedAtMs$|^status$)/u,
	/(^currentSha$|^upstreamSha$|^repositoryUrl$|^commitAtMs$|^installedAtMs$|^status$|^commitsBehind$)/u,
	/(^currentSha$|^upstreamSha$|^repositoryUrl$|^commitAtMs$|^installedAtMs$|^status$|^commitsAhead$)/u,
	/(^currentSha$|^upstreamSha$|^repositoryUrl$|^commitAtMs$|^installedAtMs$|^status$|^commitsAhead$|^commitsBehind$)/u,
	/(^currentSha$|^upstreamSha$|^repositoryUrl$|^commitAtMs$|^installedAtMs$|^status$|^reason$)/u,
	/(^root$|^currentSha$|^currentPath$|^activationEnabled$|^releaseRetention$|^activation$|^lastActivation$|^prepared$)/u,
	/^[a-f0-9]{40}$/u,
	/(^version$|^mode$|^keepVerifiedGenerations$|^pins$|^generations$)/u,
	/(^sha$|^identity$)/u,
	/(^sha$|^path$|^identity$|^buildDigest$|^publishedRevision$|^verifiedRevision$)/u,
	/(^operationId$|^phase$|^previousSha$|^candidateSha$|^failure$|^recoveryCommand$)/u,
	IsUuid,
	/(^operationId$|^outcome$|^selectedSha$|^verifiedAtMs$|^gateway$)/u,
	/(^pid$|^bootId$|^version$|^buildId$)/u,
	/(^sha$|^path$|^buildDigest$|^preparedAtMs$)/u,
	/(^kind$|^version$)/u,
	/(^kind$|^upstreamRef$|^upstreamSha$|^commitsBehind$)/u,
	/(^id$|^state$|^announcedAtMs$|^applyAtMs$|^holdUntilMs$|^forceAtMs$|^updatedAtMs$)/u,
	/(^ok$|^schedule$)/u,
	/(^requester$|^sessionKey$|^deliveryContext$|^note$|^continuationMessage$|^restartDelayMs$|^timeoutMs$|^target$)/u,
	/(^channel$|^accountId$|^senderId$)/u,
	/(^kind$|^upstreamRef$|^upstreamSha$)/u,
	/^[^\s\u0000-\u001f\u007f-\u009f]+$/u,
	/^[a-fA-F0-9]{40}$/u,
	/(^runId$|^createdAtMs$|^updatedAtMs$|^trigger$|^phase$|^status$|^reason$|^admission$|^origin$|^target$|^before$|^after$|^steps$|^verification$|^repair$|^confirmedAtMs$|^finishedAtMs$|^downtimeMs$)/u,
	/(^runId$|^ok$|^result$|^ackDelivered$|^ackQueued$|^acknowledgement$|^code$|^message$|^handoff$|^restart$|^sentinel$)/u,
	/(^runId$|^expectedOwnerId$)/u,
	/(^dryRun$|^expectedOwnerId$)/u,
	/(^runId$)/u,
	/(^run$)/u,
	/(^limit$)/u,
	/(^runs$)/u,
	/(^runId$|^phase$|^status$|^updatedAtMs$)/u,
	/(^action$|^attemptId$)/u,
	/(^action$|^attemptId$|^previewDigest$)/u,
	/(^status$|^attemptId$|^body$|^previewDigest$|^title$)/u,
	/(^status$|^message$|^url$)/u,
	/(^status$|^fallbackUrl$|^message$)/u,
	/(^status$|^message$)/u,
	/(^status$|^message$)/u,
	/(^status$|^fallbackUrl$|^message$|^url$)/u,
	/(^command$|^sessionKey$|^agentId$|^requestId$)/u,
	/(^kind$|^direction$|^sessionKey$)/u,
	/(^kind$|^sessionKey$)/u,
	/(^kind$|^sessionKey$)/u,
	/(^kind$|^visible$)/u,
	/(^kind$|^open$|^expanded$|^dock$|^panel$|^pluginId$|^panelId$)/u,
	/(^kind$|^open$|^expanded$|^dock$|^panel$|^terminalSessionId$)/u,
	/(^kind$|^open$|^expanded$|^dock$|^panel$)/u,
	/(^kind$|^open$|^expanded$|^dock$|^panel$|^environmentId$)/u,
	/(^kind$|^open$|^expanded$|^dock$|^panel$|^portalId$)/u,
	/(^kind$|^open$|^expanded$|^dock$|^panel$|^environmentId$)/u,
	/(^kind$|^sessionKey$)/u,
	/(^kind$)/u,
	/(^requestId$|^presentation$)/u,
	/(^portalId$|^status$|^reason$)/u,
	/(^id$)/u,
	/(^id$|^mode$|^appearance$)/u,
	/(^accent$|^fontUi$|^fontChat$)/u,
	/(^id$|^definition$|^apply$|^mode$)/u,
	/^[a-z0-9][a-z0-9_-]*$/u,
	/(^name$|^description$|^mascot$|^brandName$|^brandIcon$|^workingIndicator$|^lobsterdex$|^communityLinks$|^workingPhrases$|^critters$|^avatarHat$|^light$|^dark$)/u,
	/^[a-z0-9][a-z0-9_-]{0,31}$/u,
	/^[a-z0-9][a-z0-9_-]{0,31}$/u,
	/(^background$|^foreground$|^card$|^card-foreground$|^popover$|^popover-foreground$|^primary$|^primary-foreground$|^secondary$|^secondary-foreground$|^muted$|^muted-foreground$|^accent$|^accent-foreground$|^destructive$|^destructive-foreground$|^border$|^input$|^ring$|^font-sans$|^font-mono$)/u,
	/(^kind$|^query$|^feed$|^officialOnly$|^pageSize$|^cursor$|^agentId$)/u,
	/(^keywords$|^kinds$|^pageSize$|^cursor$|^agentId$)/u,
	/(^sessionKey$|^agentId$|^environmentId$)/u,
	/(^environmentId$|^port$|^title$|^description$|^path$|^sessionKey$|^agentId$)/u,
	/(^id$|^environmentId$|^sessionKey$|^agentId$)/u,
	/(^source$|^ifRowsRevision$|^rowMode$|^limit$|^offset$|^activeMinutes$|^activityPulseBoundaries$|^activeOnly$|^requireLastInteraction$|^sortBy$|^includeGlobal$|^includeUnknown$|^excludeSubagents$|^excludeCron$|^excludeSystem$|^excludeDock$|^configuredAgentsOnly$|^includeDerivedTitles$|^includeLastMessage$|^includeActivitySummary$|^label$|^projectId$|^workspaceDir$|^group$|^pinned$|^boardFace$|^hasBoard$|^creatorId$|^ownerId$|^ownerFirst$|^involvingMe$|^profileRelation$|^involvingProfileId$|^includePeople$|^includeOwnerSessionCounts$|^spawnedBy$|^agentId$|^search$|^archived$)/u,
	/(^profileId$|^relationship$)/u,
	/(^source$|^ifRowsRevision$|^rowMode$|^limit$|^offset$|^activeMinutes$|^activityPulseBoundaries$|^activeOnly$|^requireLastInteraction$|^sortBy$|^includeGlobal$|^includeUnknown$|^excludeSubagents$|^excludeCron$|^excludeSystem$|^excludeDock$|^configuredAgentsOnly$|^includeDerivedTitles$|^includeLastMessage$|^includeActivitySummary$|^label$|^projectId$|^workspaceDir$|^group$|^pinned$|^boardFace$|^hasBoard$|^creatorId$|^ownerId$|^ownerFirst$|^involvingMe$|^profileRelation$|^involvingProfileId$|^includePeople$|^includeOwnerSessionCounts$|^spawnedBy$|^agentId$|^search$|^archived$|^includeMessageBodies$)/u,
	/(^kind$|^routeSegment$|^hostId$|^identifierAlphabet$|^fullLength$|^minPrefixLength$|^lookup$|^ambiguity$)/u,
	/^[a-z][a-z0-9-]*$/u,
	/(^catalogId$|^metadataOnly$|^cursors$|^agentId$|^progressId$|^allowPartialResults$|^search$|^limitPerHost$|^hostIds$)/u,
	/(^catalogId$|^hostId$|^threadId$|^agentId$|^sourceHomeId$|^limit$|^cursor$)/u,
	/(^catalogId$|^hostId$|^threadId$|^agentId$|^sourceHomeId$)/u,
	/(^catalogId$|^hostId$|^threadId$|^agentId$|^sourceHomeId$|^displayName$)/u,
	/(^catalogId$|^hostId$|^threadId$|^agentId$|^sourceHomeId$|^confirmNoOtherRunner$)/u,
	/(^catalogId$|^hostId$|^agentId$|^cwd$|^initialMessage$)/u,
	/(^agentId$|^sessionKeys$|^recall$|^scope$|^query$|^limit$)/u,
	/(^requesterAgentId$|^requesterSessionKey$|^sandboxed$|^visibility$|^mainSessionKey$|^restrictToSpawned$|^agentToAgent$)/u,
	/(^enabled$|^allow$)/u,
	/(^activeMinutes$|^activeOnly$|^requireLastInteraction$|^sortBy$|^includeGlobal$|^includeUnknown$|^excludeSubagents$|^excludeCron$|^excludeSystem$|^excludeDock$|^configuredAgentsOnly$|^label$|^projectId$|^workspaceDir$|^group$|^pinned$|^boardFace$|^hasBoard$|^creatorId$|^ownerId$|^involvingMe$|^profileRelation$|^involvingProfileId$|^spawnedBy$|^agentId$|^search$|^archived$)/u,
	/(^agent$|^allAgents$|^enforce$|^activeKey$|^fixMissing$|^fixDmScope$)/u,
	/(^keys$|^limit$|^maxChars$)/u,
	/(^key$|^agentId$|^includeNativeSubagents$|^includeDerivedTitles$|^includeLastMessage$)/u,
	/(^key$|^sessionId$|^label$|^reference$|^shortId$|^slugHint$|^agentId$|^spawnedBy$|^includeGlobal$|^includeUnknown$|^allowMissing$)/u,
	/(^key$|^slug$)/u,
	/(^sessionKey$|^agentId$|^path$|^search$)/u,
	/(^sessionKey$|^path$|^agentId$|^messageEntryId$)/u,
	/(^sessionKey$|^path$|^agentId$|^messageEntryId$|^refs$)/u,
	/(^sessionKey$|^path$|^agentId$|^expectedSource$|^content$|^expectedHash$)/u,
	/(^workspaceId$|^root$|^fileRoot$)/u,
	/(^key$|^agentId$)/u,
	/(^sessionKey$|^agentId$|^scope$|^commit$|^summaryOnly$|^poll$)/u,
	/(^sessionKey$|^agentId$|^question$|^selectionContext$|^attachments$|^model$|^thinkingLevel$|^fastMode$)/u,
	/(^sessions$)/u,
	/(^visible$)/u,
	/(^sessionKey$|^agentId$|^visibility$)/u,
	/(^sessionKey$|^agentId$|^expectedSessionId$|^enabled$)/u,
	/(^sessionKey$|^agentId$|^identityId$)/u,
	/(^sessionKey$|^agentId$|^text$)/u,
	/(^sessionKey$|^agentId$|^id$|^resolution$)/u,
	/(^sessionKey$|^agentId$|^sessionId$|^typing$|^preview$|^cursor$)/u,
	/(^sessionKey$|^agentId$|^messageId$|^emoji$|^remove$)/u,
	/(^sessionKey$|^agentId$|^sessionId$|^messageId$|^emoji$|^action$|^actor$|^reactions$)/u,
	/(^type$|^id$|^label$|^avatarUrl$|^identity$)/u,
	/(^type$|^id$)/u,
	/(^type$|^id$)/u,
	/(^type$|^pluginId$|^domain$|^idKind$|^id$)/u,
	/(^type$|^pluginId$|^accountId$|^senderKind$|^id$)/u,
	/(^type$|^actorType$|^source$|^id$)/u,
	/(^emoji$|^count$|^identities$)/u,
	/(^id$|^label$)/u,
	/(^key$|^idempotencyKey$|^agentId$|^surface$|^label$|^displayName$|^titleSource$|^category$|^model$|^agentRuntime$|^contextWindow$|^thinkingLevel$|^cyberAccessProgram$|^fastMode$|^permissionMode$|^communication$|^toolOverrides$|^incognito$|^visibility$|^catalogId$|^parentSessionKey$|^spawnDepth$|^fork$|^forkFrom$|^emitCommandHooks$|^succeedsParent$|^timeoutMs$|^task$|^message$|^mentions$|^attachments$|^projectId$|^projectGitUrl$|^repository$|^deviceFolder$|^worktree$|^worktreeSource$|^worktreeBaseRef$|^worktreeName$|^execNode$|^cwd$)/u,
	/(^send$|^receive$)/u,
	/(^mcpServers$|^mcpToolsDeny$|^skills$|^webSearch$)/u,
	/(^url$|^ref$)/u,
	/(^deviceId$|^path$)/u,
	/^[a-z0-9][a-z0-9-]{0,63}$/u,
	/(^agentId$|^message$|^model$|^catalogId$|^incognito$)/u,
	/(^key$|^agentId$|^message$|^mentions$|^thinking$|^attachments$|^timeoutMs$|^idempotencyKey$)/u,
	/(^key$|^agentId$|^recoverToGateway$)/u,
	/(^expectedGeneration$)/u,
	/(^ok$|^key$|^sessionId$|^placement$)/u,
	/(^state$|^generation$|^createdAtMs$|^updatedAtMs$|^stateChangedAtMs$)/u,
	/(^state$|^generation$|^createdAtMs$|^updatedAtMs$|^stateChangedAtMs$|^providerId$|^profileId$|^machine$|^environmentId$|^activeOwnerEpoch$|^workspaceBaseManifestRef$|^remoteWorkspaceDir$|^workerBundleHash$|^lastTranscriptAckCursor$|^lastLiveEventAckCursor$|^workspaceResultConflict$|^terminalReason$|^terminalAtMs$)/u,
	/(^class$|^os$|^osLabel$|^cpu$|^memoryGb$)/u,
	/^[a-f0-9]{64}$/u,
	/(^paths$|^stagedResultRef$|^totalCount$)/u,
	/(^ok$|^key$|^sessionId$|^placement$)/u,
	/(^state$|^generation$)/u,
	/(^key$|^agentId$|^subscriptionId$|^mode$|^includeApprovals$|^initialHistory$)/u,
	/(^cursor$|^knownState$|^limit$|^maxBytes$|^toolResultMaxChars$|^inputRunIds$)/u,
	/(^key$|^agentId$|^subscriptionId$)/u,
	/(^agentId$|^sessionKeys$)/u,
	/(^key$|^runId$|^agentId$|^clearQueued$)/u,
	/(^key$|^agentId$|^expectedSessionId$|^expectedLifecycleRevision$|^expectedPermissionMode$|^expectedSandboxMode$|^expectedNativeRuntimeConsent$|^expectedToolOverrides$|^expectedMarkedUnreadAt$|^expectedSidebarRoot$|^expectedCategory$|^expectedArchived$|^expectedSidebarAncestors$|^label$|^autoLabel$|^icon$|^color$|^category$|^boardFace$|^boardPresentation$|^statusNote$|^attention$|^ttlMinutes$|^archived$|^pinned$|^sidebarRoot$|^snoozedUntil$|^unread$|^contextWindow$|^thinkingLevel$|^cyberAccessProgram$|^fastMode$|^toolOverrides$|^verboseLevel$|^traceLevel$|^reasoningLevel$|^responseUsage$|^elevatedLevel$|^execHost$|^execSecurity$|^execAsk$|^execNode$|^permissionMode$|^communication$|^sandboxMode$|^nativeRuntimeConsent$|^model$|^agentRuntime$|^completionOwnerSessionKey$|^inheritedToolPolicyVersion$|^inheritedToolAllow$|^inheritedToolDeny$|^sendPolicy$|^groupActivation$)/u,
	/(^key$|^agentId$|^expectedSessionId$|^expectedSidebarRoot$|^expectedCategory$)/u,
	/(^send$|^receive$)/u,
	/(^sessionKey$|^agentId$|^sessionId$|^goalId$|^operationId$|^issuedAtMs$|^action$|^objective$|^expectedGoalUpdatedAt$|^expectedRunId$)/u,
	/(^sessionKey$|^agentId$|^sessionId$|^goalId$|^operationId$|^issuedAtMs$|^action$|^objective$)/u,
	/(^sessionKey$|^agentId$|^sessionId$|^goalId$|^operationId$|^issuedAtMs$|^action$|^note$)/u,
	/(^sessionKey$|^agentId$|^sessionId$|^goalId$|^operationId$|^issuedAtMs$)/u,
	/(^sessionKey$|^agentId$|^sessionId$|^reviewId$|^idempotencyKey$)/u,
	/(^targets$|^patch$)/u,
	/(^key$|^expectedMarkedUnreadAt$|^expectedSidebarRoot$|^expectedCategory$|^expectedArchived$|^expectedSidebarAncestors$|^agentId$|^expectedSessionId$|^expectedLifecycleRevision$|^expectedSandboxMode$|^expectedPermissionMode$|^expectedNativeRuntimeConsent$)/u,
	/(^label$|^autoLabel$|^icon$|^color$|^category$|^boardFace$|^boardPresentation$|^statusNote$|^attention$|^ttlMinutes$|^archived$|^pinned$|^sidebarRoot$|^snoozedUntil$|^unread$|^contextWindow$|^thinkingLevel$|^cyberAccessProgram$|^fastMode$|^toolOverrides$|^verboseLevel$|^traceLevel$|^reasoningLevel$|^responseUsage$|^elevatedLevel$|^execHost$|^execSecurity$|^execAsk$|^execNode$|^permissionMode$|^communication$|^sandboxMode$|^nativeRuntimeConsent$|^model$|^agentRuntime$|^completionOwnerSessionKey$|^inheritedToolPolicyVersion$|^inheritedToolAllow$|^inheritedToolDeny$|^sendPolicy$|^groupActivation$)/u,
	/(^key$|^agentId$|^pluginId$|^namespace$|^value$|^unset$)/u,
	/(^key$|^agentId$|^reason$|^expectedSessionId$)/u,
	/(^key$|^agentId$|^deleteTranscript$|^expectedSessionId$|^expectedLifecycleRevision$|^expectedSessionUpdatedAt$|^emitLifecycleHooks$|^archivedOnly$)/u,
	/(^key$|^agentId$|^owner$)/u,
	/(^type$|^id$)/u,
	/(^key$|^agentId$|^expectedSessionId$|^hidden$)/u,
	/(^groups$|^sectionOrder$)/u,
	/(^name$|^position$)/u,
	/(^defaults$)/u,
	/(^name$|^cwd$|^worktree$)/u,
	/(^names$|^sectionOrder$)/u,
	/(^name$|^to$)/u,
	/(^name$|^cwd$|^worktree$)/u,
	/(^ok$|^defaults$)/u,
	/(^name$)/u,
	/(^ok$|^groups$|^sectionOrder$|^updatedSessions$)/u,
	/(^key$|^agentId$|^maxLines$)/u,
	/(^sessionKey$|^agentId$|^leafEntryId$)/u,
	/(^sessionKey$|^agentId$|^entryId$)/u,
	/(^key$|^agentId$|^agentScope$|^creatorKey$|^startDate$|^endDate$|^mode$|^range$|^groupBy$|^includeHistorical$|^utcOffset$|^timeZone$|^limit$|^projection$|^offset$|^query$|^selectedDays$|^selectedHours$|^selectedSessions$|^recentKeys$|^sort$|^sortDirection$|^includeContextWeight$)/u,
	/^\d{4}-\d{2}-\d{2}$/u,
	/^UTC[+-]\d{1,2}(?::[0-5]\d)?$/u,
	/^\d{4}-\d{2}-\d{2}$/u,
	/(^state$|^embedUrl$|^openUrl$)/u,
	/(^sessionKey$|^agentId$|^idempotencyKey$|^workspacePath$|^title$|^body$|^draft$|^selection$)/u,
	/^[^\r\n]*\S[^\r\n]*$/u,
	/(^source$|^expected$)/u,
	/(^source$|^accountId$|^login$)/u,
	/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u,
	/(^source$|^generation$|^account$)/u,
	/(^accountId$|^login$)/u,
	/(^action$|^pullRequestUrl$|^conflictsResolved$|^expectedHeadCommit$|^sessionKey$|^agentId$)/u,
	/^[a-f0-9]{40}$/u,
	/(^action$|^pullRequestUrl$|^sessionKey$|^agentId$)/u,
	/(^action$|^requestId$|^expectedHeadCommit$|^sessionKey$|^agentId$)/u,
	IsUuid,
	/(^action$|^requestId$|^expectedHeadCommit$|^evidence$|^sessionKey$|^agentId$)/u,
	/(^path$|^sha256$|^sizeBytes$)/u,
	/(^action$|^requestId$|^expectedHeadCommit$|^title$|^body$|^expectedTitle$|^expectedBody$|^sessionKey$|^agentId$)/u,
	/(^action$|^publishingSessionKey$|^requestId$|^expectedHeadCommit$|^mergeMethod$|^sessionKey$|^agentId$)/u,
	/(^action$|^conflictsResolved$|^baseCommit$|^sessionKey$|^agentId$)/u,
	/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u,
	/(^sessionKey$|^agentId$|^requestId$)/u,
	/(^policy$|^custody$|^target$|^request$|^remedies$)/u,
	/(^read$|^write$)/u,
	/(^kind$|^source$)/u,
	/(^kind$)/u,
	/(^kind$|^reason$)/u,
	/(^kind$|^basis$|^freshness$)/u,
	/(^kind$)/u,
	/(^kind$|^reason$)/u,
	/(^kind$|^selection$|^receipt$)/u,
	/(^requestId$|^effect$|^status$)/u,
	/(^kind$|^status$|^headCommit$|^url$)/u,
	/(^requestId$|^effect$|^status$)/u,
	/(^requestId$|^effect$|^status$|^url$|^repository$|^branch$|^headCommit$)/u,
	/(^requestId$|^effect$|^status$|^code$)/u,
	/(^kind$|^selection$)/u,
	/(^kind$|^reason$|^selectedRequestId$)/u,
	/(^kind$)/u,
	/(^kind$)/u,
	/(^kind$)/u,
	/(^kind$|^requestId$)/u,
	/(^sessionKey$|^agentId$|^idempotencyKey$)/u,
	/(^sessionKey$|^agentId$|^requestId$)/u,
	/(^sessionKey$|^agentId$|^requestId$|^generation$|^account$|^requestDigest$)/u,
	/^[a-f0-9]+$/u,
	/(^minProtocol$|^maxProtocol$|^client$|^caps$|^includeSessionMessageBodies$|^commands$|^computerUse$|^workerRuns$|^permissions$|^pathEnv$|^role$|^scopes$|^modelCatalog$|^device$|^auth$|^locale$|^userAgent$)/u,
	/(^id$|^displayName$|^version$|^buildId$|^platform$|^deviceFamily$|^modelIdentifier$|^timeZone$|^mode$|^instanceId$)/u,
	/(^bundleHash$|^openclawVersion$|^protocolFeatures$|^bundlePrewarm$)/u,
	/(^agentId$|^sessionKey$)/u,
	/(^agentId$|^shortId$|^slugHint$)/u,
	/(^id$|^publicKey$|^signature$|^signedAt$|^nonce$)/u,
	/(^token$|^bootstrapToken$|^deviceToken$|^password$|^approvalRuntimeToken$|^agentRuntimeIdentityToken$)/u,
	/(^bundleHash$|^openclawVersion$|^protocolFeatures$|^bundlePrewarm$)/u,
	/(^type$|^id$|^method$|^params$)/u,
	/(^minProtocol$|^maxProtocol$|^client$|^role$|^admission$)/u,
	/(^id$|^version$|^platform$|^mode$)/u,
	/(^environmentId$|^credential$|^ownerEpoch$|^rpcSetVersion$|^handshake$|^sessionId$|^runId$)/u,
	/(^environmentId$|^credential$|^ownerEpoch$|^rpcSetVersion$|^handshake$|^sessionId$|^runId$)/u,
	/(^sentAtMs$|^status$|^githubGeneration$)/u,
	/(^task$|^label$|^agentId$|^model$|^runTimeoutSeconds$|^toolCallId$)/u,
	/(^sessionKey$|^message$|^timeoutSeconds$|^toolCallId$)/u,
	/(^toolCallId$|^action$|^port$|^title$|^description$|^path$|^id$)/u,
	/^\//u,
	/(^toolCallId$|^action$|^person$|^deviceId$|^include$|^limit$)/u,
	/(^command$|^paramsJson$|^timeoutMs$|^idempotencyKey$)/u,
	/(^runEpoch$|^seq$|^baseLeafId$|^messages$)/u,
	/(^role$|^content$|^timestamp$|^operatorMessage$)/u,
	/(^type$|^text$|^textSignature$)/u,
	/(^type$|^data$|^mimeType$)/u,
	/(^turnScoped$)/u,
	/(^role$|^content$|^display$|^timestamp$|^customType$|^details$)/u,
	/(^kind$|^text$)/u,
	/(^role$|^content$|^display$|^timestamp$|^customType$|^details$)/u,
	/(^kind$|^turnScoped$)/u,
	/(^role$|^content$|^api$|^provider$|^model$|^responseModel$|^responseId$|^providerReplay$|^usage$|^timestamp$|^diagnostics$|^stopReason$|^errorMessage$|^errorCode$|^errorType$|^errorBody$|^retryAfterMs$|^itemId$)/u,
	/(^type$|^thinking$|^thinkingSignature$|^redacted$)/u,
	/(^type$|^id$|^name$|^arguments$|^thoughtSignature$|^executionMode$)/u,
	/^\S(?:.*\S)?$/u,
	/(^v$|^type$|^id$|^data$|^replayIndex$|^provider$|^api$|^model$|^baseUrlHash$|^sessionHash$|^authProfileHash$)/u,
	/^[a-z0-9]+$/u,
	/(^input$|^output$|^cacheRead$|^cacheWrite$|^usageReport$|^contextUsage$|^totalTokens$|^cost$)/u,
	/(^state$)/u,
	/(^state$|^promptTokens$|^totalTokens$)/u,
	/(^state$)/u,
	/(^input$|^output$|^cacheRead$|^cacheWrite$|^total$|^totalOrigin$)/u,
	/(^type$|^timestamp$|^error$|^details$)/u,
	/(^name$|^message$|^stack$|^code$)/u,
	/(^role$|^toolCallId$|^toolName$|^content$|^details$|^isError$|^timestamp$)/u,
	/(^runEpoch$|^lastAckedSeq$|^seq$|^runId$|^event$)/u,
	/(^kind$|^payload$)/u,
	/(^text$|^delta$|^replace$|^mediaUrls$|^phase$|^itemId$)/u,
	/^\S(?:.*\S)?$/u,
	/(^kind$|^payload$)/u,
	/(^text$|^delta$|^itemId$)/u,
	/(^kind$|^payload$)/u,
	/(^name$|^toolCallId$|^hideFromChannelProgress$|^phase$|^args$)/u,
	/(^name$|^toolCallId$|^hideFromChannelProgress$|^phase$|^partialResult$)/u,
	/(^name$|^toolCallId$|^hideFromChannelProgress$|^phase$|^meta$|^isError$|^result$|^toolErrorSummary$)/u,
	/(^kind$|^payload$)/u,
	/(^kind$|^title$|^itemId$|^toolCallId$|^approvalId$|^approvalSlug$|^command$|^host$|^reason$|^scope$|^message$|^phase$|^status$)/u,
	/(^kind$|^title$|^itemId$|^toolCallId$|^approvalId$|^approvalSlug$|^command$|^host$|^reason$|^scope$|^message$|^phase$|^status$)/u,
	/(^kind$|^payload$)/u,
	/(^phase$|^startedAt$)/u,
	/(^selectedProvider$|^selectedModel$|^activeProvider$|^activeModel$|^phase$|^reasonSummary$|^attemptSummaries$|^attempts$)/u,
	/(^provider$|^model$|^error$|^reason$|^authMode$|^status$|^code$)/u,
	/(^selectedProvider$|^selectedModel$|^activeProvider$|^activeModel$|^phase$|^previousActiveModel$)/u,
	/(^phase$|^fallbackStepType$|^fallbackStepFromModel$|^fallbackStepToModel$|^fallbackStepFromFailureReason$|^fallbackStepFromFailureDetail$|^fallbackStepChainPosition$|^fallbackStepFinalOutcome$)/u,
	/(^startedAt$|^endedAt$|^stopReason$|^yielded$|^timeoutPhase$|^providerStarted$|^aborted$|^toolErrorSummary$|^livenessState$|^replayInvalid$|^phase$|^error$)/u,
	/(^startedAt$|^endedAt$|^stopReason$|^yielded$|^timeoutPhase$|^providerStarted$|^aborted$|^toolErrorSummary$|^livenessState$|^replayInvalid$|^phase$)/u,
	/(^startedAt$|^endedAt$|^stopReason$|^yielded$|^timeoutPhase$|^providerStarted$|^aborted$|^toolErrorSummary$|^livenessState$|^replayInvalid$|^phase$|^error$|^fallbackExhaustedFailure$)/u,
	/(^requestId$|^terminalPolicy$|^drain$)/u,
	/(^status$|^reason$|^retryAfterMs$|^activeCount$|^blockers$|^writeCustody$)/u,
	/(^kind$|^count$|^message$)/u,
	/(^phase$|^count$)/u,
	/(^status$|^suspensionId$|^expiresAtMs$|^retryAfterMs$|^activeCount$|^blockers$|^writeCustody$)/u,
	/(^status$|^suspensionId$|^expiresAtMs$|^activeCount$|^blockers$|^writeCustody$)/u,
	/(^suspensionId$|^includeLifecycle$)/u,
	/(^status$)/u,
	/(^status$|^ownerId$|^phase$|^expiresAtMs$|^retryAfterMs$|^activeCount$|^blockers$|^writeCustody$)/u,
	/(^status$|^ownerId$|^expiresAtMs$|^writeCustody$)/u,
	/(^suspensionId$)/u,
	/(^suspensionId$|^commit$|^target$)/u,
	/(^pid$|^processInstanceId$)/u,
	/(^type$|^id$|^method$|^params$|^traceparent$|^expectedProfileId$)/u,
	/(^nodeId$)/u,
	/(^nodeId$|^displayName$)/u,
	/(^tools$)/u,
	/(^pluginId$|^name$|^description$|^parameters$|^command$|^mcp$)/u,
	/^[A-Za-z][A-Za-z0-9_-]{0,63}$/u,
	/(^server$|^tool$)/u,
	/(^skills$)/u,
	/(^name$|^description$|^content$)/u,
	/^(?!.*--)[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/u,
	/(^environmentId$|^control$)/u,
	/(^transport$|^wsPath$|^expiresAtMs$|^control$|^canResize$|^vncPassword$)/u,
	/(^environmentId$|^app$)/u,
	/(^app$|^status$)/u,
	/(^ids$)/u,
	/(^nodeId$|^command$|^params$|^timeoutMs$|^idempotencyKey$|^sessionKey$|^turnSourceChannel$|^turnSourceTo$|^turnSourceAccountId$|^turnSourceThreadId$)/u,
	/(^id$|^nodeId$|^ok$|^payload$|^payloadJSON$|^error$)/u,
	/(^code$|^message$|^details$)/u,
	/(^capabilities$|^state$)/u,
	/(^invokeId$|^nodeId$|^seq$|^chunk$)/u,
	/(^event$|^payload$|^payloadJSON$)/u,
	/(^idleSeconds$|^source$|^saturated$)/u,
	/(^action$)/u,
	/(^cpuCount$|^loadAverage$|^memoryTotalBytes$|^memoryFreeBytes$|^diskTotalBytes$|^diskAvailableBytes$)/u,
	{ check: hasValidNodeHostResources },
	/(^maxItems$)/u,
	/(^nodeId$|^type$|^priority$|^expiresInMs$|^wake$)/u,
	/(^deviceId$)/u,
	/(^publicUrl$|^preferRemoteUrl$|^includeQr$|^bootstrapProfile$|^joinUrl$)/u,
	/(^setupId$)/u,
	/(^deviceId$|^label$)/u,
	/(^deviceId$|^role$|^scopes$)/u,
	/(^deviceId$|^role$)/u,
	/(^nodeId$|^file$|^native$|^baseHash$)/u,
	/(^version$|^socket$|^defaults$|^agents$)/u,
	/(^defaultAction$|^rules$)/u,
	/(^pattern$|^action$|^shells$|^description$|^enabled$)/u,
	/(^path$|^exists$|^hash$|^file$|^resolvedDefaults$|^enabled$|^baseHash$|^defaultAction$|^rules$|^constraints$|^message$)/u,
	/(^security$|^ask$|^askFallback$|^autoAllowSkills$)/u,
	/(^baseHashRequired$|^defaultAllowAllowed$|^broadAllowRulesAllowed$|^dangerousAllowRulesAllowed$)/u,
	/(^query$|^category$|^featured$|^limit$)/u,
	/(^name$|^description$|^version$|^scope$|^manifest$|^files$)/u,
	/(^input$|^job$|^output$|^authority$)/u,
	/(^path$|^content$)/u,
	/(^agentId$|^sourceSessionKey$)/u,
	/(^agentId$|^draftId$)/u,
	/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/u,
	/(^agentId$|^draftId$|^content$|^expectedRevision$)/u,
	/(^agentId$|^draftId$|^choices$)/u,
	/(^name$|^displayName$|^description$|^excluded$)/u,
	/(^agentId$|^draftId$|^reviewToken$|^choices$)/u,
	/(^entries$)/u,
	/(^packageName$|^displayName$|^iconUrl$|^summary$|^latestVersion$|^channel$|^official$|^ownerHandle$|^downloads$|^installs$|^featuredAt$|^updatedAtMs$)/u,
	/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u,
	/(^packageName$|^version$)/u,
	/(^detail$)/u,
	/(^packageName$|^displayName$|^iconUrl$|^summary$|^latestVersion$|^channel$|^official$|^ownerHandle$|^downloads$|^installs$|^featuredAt$|^updatedAtMs$|^version$|^agentName$|^agentDescription$|^workspaceFiles$|^skills$|^plugins$|^mcpServers$|^scheduledJobs$|^contents$|^scanStatus$)/u,
	/(^instructions$|^skills$|^integrations$|^automations$)/u,
	/(^name$|^source$|^excerpt$)/u,
	/(^name$|^version$|^excerpt$)/u,
	/(^name$|^kind$|^version$)/u,
	/(^name$|^schedule$|^timezone$)/u,
	/(^packageName$|^version$|^kind$|^name$)/u,
	/(^preview$)/u,
	/(^kind$|^name$|^content$)/u,
	/(^target$)/u,
	/(^schemaVersion$|^records$|^summary$)/u,
	/(^agentId$|^name$|^version$|^sourceKind$|^status$|^agentState$|^bootstrapState$|^orphaned$|^addedAtMs$|^updatedAtMs$|^resources$)/u,
	/(^kind$|^id$|^state$|^reason$|^relationship$|^origin$|^independentOwner$)/u,
	/(^templates$|^healthy$|^attention$|^managed$|^referenced$)/u,
	/(^source$|^agentId$)/u,
	/(^source$|^agentId$|^planIntegrity$|^acknowledgeClawHubRisk$|^acknowledgeCapabilities$|^acknowledgeSkillWarnings$)/u,
	/(^actionId$|^pluginId$|^reviewToken$|^capabilityGrants$|^capabilityGrantsByPluginId$|^acknowledgeRiskWarning$)/u,
	/(^hooks$|^llm$|^subagent$)/u,
	/(^allowPromptInjection$|^allowConversationAccess$)/u,
	/(^effective$|^configured$)/u,
	/(^allowModelOverride$|^allowedModels$|^allowedCompletionModels$|^allowAuthProfileOverride$|^allowAgentIdOverride$)/u,
	/(^allowModelOverride$|^allowedModels$)/u,
	/^.*$/u,
	/(^actionId$|^ref$|^reviewToken$|^acknowledgeRiskWarning$)/u,
	/(^agentId$|^source$)/u,
	/(^agentId$|^source$|^planIntegrity$|^acknowledgeClawHubRisk$|^acknowledgeCapabilities$|^acknowledgeSkillWarnings$)/u,
	/(^agentId$|^planIntegrity$)/u,
	/(^schemaVersion$|^operation$|^planIntegrity$|^target$|^actions$|^capabilities$|^pluginReviews$|^skillReviews$|^blockers$|^trustWarning$|^manifestDisclosure$|^riskAcknowledgementRequired$|^configuredAccess$|^scheduledJobs$|^readiness$)/u,
	/(^agentId$|^workspace$|^name$|^currentVersion$|^targetVersion$)/u,
	/(^kind$|^id$|^action$|^blocked$|^reason$|^effect$)/u,
	/(^type$|^destination$|^source$|^currentDigest$|^desiredDigest$|^currentPresent$)/u,
	/(^type$|^currentDigest$|^desiredDigest$|^proposed$|^ownership$)/u,
	/(^transport$|^command$|^arguments$|^url$|^urlDigest$|^queryParameterNames$|^environment$|^authentication$|^toolFilter$|^timeout$|^connectTimeout$)/u,
	/(^name$|^sourceName$)/u,
	/(^include$|^exclude$)/u,
	/(^relationship$|^origin$|^independentOwner$|^affectedTemplateCount$)/u,
	/(^type$|^relationship$|^origin$|^independentOwner$|^affectedTemplateCount$)/u,
	/(^type$|^current$|^desired$|^ownership$)/u,
	/(^source$|^ref$|^version$|^integrity$)/u,
	/^sha256-[A-Za-z0-9+/]{43}=$/u,
	/(^kind$|^id$|^action$|^reason$)/u,
	/(^actionId$|^pluginId$|^ref$|^version$|^ownerAction$|^integrity$|^declaredCapabilities$|^capabilityGrants$|^capabilityGrantsByPluginId$|^reviewToken$|^riskWarning$)/u,
	/(^channels$|^providers$|^tools$|^contracts$|^hooks$|^mcpServers$|^cliCommands$|^cliBackends$|^skills$|^dangerousConfigFlags$)/u,
	/(^actionId$|^ref$|^version$|^integrity$|^riskWarning$|^reviewToken$)/u,
	/(^code$|^path$|^message$)/u,
	/(^source$|^manifestJson$|^openClawProfileJson$)/u,
	/(^packageName$|^version$|^integrity$|^byteLength$)/u,
	/^sha256:[a-f0-9]{64}$/u,
	/(^coverage$|^current$|^desired$|^unresolved$)/u,
	/(^tools$|^sandbox$|^filesystem$|^heartbeat$|^memorySearch$|^subagentTargets$)/u,
	/(^allowed$|^excluded$|^explicitAllow$|^explicitDeny$)/u,
	/(^mode$|^scope$|^workspaceAccess$|^backend$)/u,
	/(^workspaceOnly$)/u,
	/(^enabled$|^intervalMs$|^activeHours$|^isolatedSession$)/u,
	/(^start$|^end$|^timezone$)/u,
	/(^state$)/u,
	/(^state$)/u,
	/(^state$|^rememberAcrossConversations$|^sessionMemory$|^indexedSources$|^searchSources$|^extraPathCount$)/u,
	/(^allowedAgentIds$|^allowAnyConfiguredAgent$|^implicitSelfAllowed$|^requireAgentId$)/u,
	/(^coverage$|^jobs$)/u,
	/(^id$|^action$|^blocked$|^current$|^proposed$)/u,
	/(^schedule$|^session$|^delivery$|^messageDigest$)/u,
	/(^cron$|^timezone$)/u,
	/(^everyMs$)/u,
	/(^schedule$|^session$|^delivery$|^messageDigest$|^message$)/u,
	/(^ready$|^requirements$)/u,
	/(^kind$|^owner$)/u,
	/(^html$)/u,
	/(^docId$|^sessionKey$)/u,
	/^(?!\.{1,2}$)[A-Za-z0-9._-]+$/u,
	/(^projectId$|^agentId$)/u,
	/(^includeObserved$)/u,
	/(^path$|^name$)/u,
	/(^gitUrl$|^name$)/u,
	/(^query$)/u,
	/(^id$|^deleteCheckout$)/u,
	/^[a-z0-9][a-z0-9-]{0,63}$/u,
	/(^sessionKey$|^agentId$|^ops$)/u,
	/(^kind$|^tabId$|^title$|^chatDock$)/u,
	/^[a-z0-9-]{1,40}$/u,
	/(^kind$|^tabId$|^title$|^chatDock$|^position$)/u,
	/(^kind$|^tabId$)/u,
	/(^kind$|^tabIds$)/u,
	/(^kind$|^name$|^tabId$|^position$|^after$)/u,
	/^[a-z0-9][a-z0-9._-]{0,63}$/u,
	/^[a-z0-9-]{1,40}$/u,
	/^[a-z0-9][a-z0-9._-]{0,63}$/u,
	/(^kind$|^name$|^sizeW$|^sizeH$|^heightMode$)/u,
	/(^kind$|^name$)/u,
	/(^kind$|^html$)/u,
	/(^kind$|^descriptor$)/u,
	/(^serverName$|^toolName$|^uiResourceUri$|^toolCallId$)/u,
	/(^kind$|^pluginKind$|^props$)/u,
	/^[a-z0-9][a-z0-9-]{0,63}:[a-z0-9][a-z0-9._-]{0,63}$/u,
	/(^kind$|^contentKind$|^source$)/u,
	/^[a-z][a-z0-9-]{0,31}$/u,
	/(^sessionKey$|^agentId$|^name$|^revision$|^instanceId$)/u,
	/(^sessionKey$|^agentId$|^name$|^title$|^content$|^presentation$|^heightMode$|^placement$|^declared$|^generatedIdentity$)/u,
	/(^kind$|^viewId$)/u,
	/(^kind$|^docId$)/u,
	/(^tabId$|^size$|^after$)/u,
	/(^netOrigins$|^tools$)/u,
	/(^source$|^key$|^fallbackName$)/u,
	/(^sessionKey$|^agentId$|^name$|^decision$|^revision$|^instanceId$)/u,
	/(^sessionKey$|^agentId$|^widget$|^payload$)/u,
	/(^ticket$|^payload$)/u,
	/(^ticket$)/u,
	/(^ticket$|^bindingId$|^params$)/u,
	/^.*$/u,
	/(^ticket$|^action$|^jobId$)/u,
	/(^ticket$|^action$|^params$)/u,
	/(^repoRoot$|^name$|^baseRef$|^profiles$|^expectedOwnerId$|^expectedRepoIdentity$)/u,
	/^[a-z0-9][a-z0-9-]{0,63}$/u,
	/(^id$|^force$|^ifLossless$|^exactState$|^expectedOwnerId$)/u,
	/(^ownerKind$|^ownerId$|^createdAt$|^lastActiveAt$|^head$|^branchHead$|^indexSha256$)/u,
	/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u,
	/(^id$|^recoverExactState$|^expectedOwnerId$)/u,
	/(^expectedOwnerId$|^jobId$|^retryDeferred$)/u,
	/(^sessionKey$|^path$|^recoveryId$|^expectedOwnerId$)/u,
	/(^id$|^snapshot$|^expectedOwnerId$)/u,
	/(^id$|^expectedSnapshotRef$|^expectedSnapshotOid$|^expectedRemovedAt$|^retainedSourceRef$|^expectedRetainedSourceOid$|^expectedOwnerId$)/u,
	/^refs\/(?:heads|remotes)\/.+/u,
	/(^repoRoot$|^includeRepositoryStatus$)/u,
	/(^path$|^nodeId$)/u,
	/(^path$|^parent$|^home$|^entries$)/u,
	/(^name$|^path$|^hidden$)/u,
	/(^type$|^id$|^ok$|^payload$)/u,
	/(^type$|^environmentId$|^sessionId$|^ownerEpoch$|^rpcSetVersion$|^protocolFeatures$|^credentialExpiresAtMs$|^toolSurface$|^policy$)/u,
	/(^generation$|^presentation$|^tools$|^policy$)/u,
	/(^codeMode$|^toolSearch$|^toolSearchDirectoryLean$|^forceDirectMessageTool$|^skills$)/u,
	/(^enabled$|^executor$|^mode$|^timeoutMs$|^memoryLimitBytes$|^maxOutputBytes$|^maxSnapshotBytes$|^maxPendingToolCalls$|^snapshotTtlSeconds$|^searchDefaultLimit$|^maxSearchLimit$)/u,
	/(^enabled$|^mode$|^include$|^exclude$|^searchDefaultLimit$|^maxSearchLimit$)/u,
	/(^source$|^name$)/u,
	/(^name$|^description$|^location$)/u,
	/(^id$|^execution$|^replay$|^plugin$|^timeout$|^definition$)/u,
	/(^pluginId$|^optional$|^replaySafe$|^sideEffecting$|^mcp$)/u,
	/(^serverName$|^safeServerName$|^toolName$|^operation$|^node$)/u,
	/(^id$|^displayName$)/u,
	/(^minimumMs$|^argument$|^defaultSeconds$|^paddingMs$)/u,
	/(^name$|^label$|^description$|^parameters$|^outputSchema$|^hideFromChannelProgress$|^resultContentSource$|^executionMode$|^catalogMode$|^async$)/u,
	/(^workspaceOnly$|^readOnly$|^applyPatchEnabled$|^applyPatchWorkspaceOnly$|^applyPatchContainmentSource$|^modelContextWindowTokens$|^modelHasVision$|^memoryFlushWritePath$|^imageSanitization$)/u,
	/(^maxBytes$|^maxDimensionPx$)/u,
	/(^heartbeatIntervalMs$|^maxPayload$)/u,
	/(^type$|^id$|^ok$|^error$)/u,
	/(^code$|^message$|^details$|^retryable$|^retryAfterMs$)/u,
	/(^reason$)/u,
	/(^type$|^id$|^ok$|^payload$)/u,
	/(^outcome$|^baseLeafId$)/u,
	/(^outcome$)/u,
	/(^type$|^id$|^ok$|^payload$)/u,
	/(^content$|^details$|^isError$|^terminate$|^progress$|^mcpGuestResult$|^mcpBlockedReason$)/u,
	/(^type$|^id$|^ok$|^payload$)/u,
	/(^type$|^id$|^ok$|^payload$)/u,
	/(^receivedAtMs$|^status$|^ownerEpoch$|^github$)/u,
	/(^generation$|^token$|^expiresAtMs$)/u,
	/(^type$|^id$|^ok$|^payload$)/u,
	/(^entryIds$|^newLeafId$)/u,
	/(^type$|^id$|^ok$|^error$)/u,
	/(^code$|^message$|^details$)/u,
	/(^reason$)/u,
	/(^type$|^id$|^ok$|^payload$)/u,
	/(^ackedSeq$)/u,
	/(^type$|^id$|^ok$|^error$)/u,
	/(^code$|^message$|^details$)/u,
	/(^reason$)/u,
	/(^reason$|^ackedSeq$|^expectedSeq$)/u,
	/(^type$|^id$|^ok$|^payload$)/u,
	/(^resultJson$)/u,
	/(^type$|^id$|^ok$|^payload$)/u,
	/(^status$)/u,
	/(^type$|^id$|^ok$|^error$)/u,
	/(^code$|^message$|^details$)/u,
	/(^reason$)/u,
	/(^type$|^id$|^ok$|^payload$)/u,
	/(^status$)/u,
	/(^type$|^id$|^ok$|^payload$)/u,
	/(^operation$|^binding$|^decision$)/u,
	/(^decision$|^risk$|^rationale$|^userAuthorization$)/u,
	/(^decision$|^risk$|^rationale$|^userAuthorization$)/u,
	/(^operation$|^binding$|^id$|^expiresAtMs$|^decision$)/u,
	/(^operation$|^binding$|^decision$|^terminalReason$)/u
];
var check_2 = (e) => !1;
var check_6 = (e) => typeof e == "string" && (e.length >= 2 || e.length >= 1 && CodePointCount(e) >= 1);
var check_63 = (e) => typeof e == "string" && (e.length >= 2 || e.length >= 1 && CodePointCount(e) >= 1);
var check_68 = (e) => typeof e == "string" && e === "device";
var check_152 = (e) => typeof e == "string" && e === "gateway";
var check_259 = (e) => typeof e == "string" && (e.length >= 2 || e.length >= 1 && CodePointCount(e) >= 1) && (e.length <= 128 || e.length <= 256 && CodePointCount(e) <= 128);
var check_287 = (e) => typeof e == "string" && (e.length >= 2 || e.length >= 1 && CodePointCount(e) >= 1) && (e.length <= 256 || e.length <= 512 && CodePointCount(e) <= 256) && External[73].test(e);
var check_310 = (e) => Number.isInteger(e) && (!(Number.isFinite(e) || typeof e == "bigint") || e >= 1 && e <= 9007199254740991);
var check_324 = (e) => check_325(e);
var check_325 = (e) => typeof e == "object" && e !== null && !Array.isArray(e) && "key" in e && Object.getOwnPropertyNames(e).every((t, n) => External[88].test(t) || check_2(e[t])) && check_6(e.key) && (e.agentId === void 0 || !("agentId" in e) || check_63(e.agentId)) && (e.profileId === void 0 || !("profileId" in e) || check_63(e.profileId)) && (e.deviceId === void 0 || !("deviceId" in e) || check_63(e.deviceId)) && (e.autoDevice === void 0 || !("autoDevice" in e) || check_326(e.autoDevice)) && (e.machineClass === void 0 || !("machineClass" in e) || check_259(e.machineClass)) && (e.os === void 0 || !("os" in e) || check_327(e.os)) && [
	check_328(e),
	check_332(e),
	check_337(e),
	check_339(e)
].reduce((e, t, n) => t === !0 ? ++e : e, 0) === 1;
var check_326 = (e) => typeof e == "boolean" && e === !0;
var check_327 = (e) => typeof e == "string" && (e.length >= 2 || e.length >= 1 && CodePointCount(e) >= 1) && (e.length <= 64 || e.length <= 128 && CodePointCount(e) <= 64);
var check_328 = (e) => (!(typeof e == "object" && e !== null && !Array.isArray(e)) || "profileId" in e) && !check_329(e);
var check_329 = (e) => check_330(e) || check_331(e);
var check_330 = (e) => !(typeof e == "object" && e !== null && !Array.isArray(e)) || "deviceId" in e;
var check_331 = (e) => !(typeof e == "object" && e !== null && !Array.isArray(e)) || "autoDevice" in e;
var check_332 = (e) => (!(typeof e == "object" && e !== null && !Array.isArray(e)) || "deviceId" in e) && !check_333(e);
var check_333 = (e) => check_334(e) || check_331(e) || check_335(e) || check_336(e);
var check_334 = (e) => !(typeof e == "object" && e !== null && !Array.isArray(e)) || "profileId" in e;
var check_335 = (e) => !(typeof e == "object" && e !== null && !Array.isArray(e)) || "machineClass" in e;
var check_336 = (e) => !(typeof e == "object" && e !== null && !Array.isArray(e)) || "os" in e;
var check_337 = (e) => (!(typeof e == "object" && e !== null && !Array.isArray(e)) || "autoDevice" in e) && !check_338(e);
var check_338 = (e) => check_334(e) || check_330(e) || check_335(e) || check_336(e);
var check_339 = (e) => !check_340(e);
var check_340 = (e) => check_334(e) || check_330(e) || check_331(e) || check_335(e) || check_336(e);
var check_341 = (e) => check_342(e);
var check_342 = (e) => typeof e == "object" && e !== null && !Array.isArray(e) && "key" in e && "expected" in e && "target" in e && Object.getOwnPropertyNames(e).every((t, n) => External[89].test(t) || check_2(e[t])) && check_6(e.key) && (e.agentId === void 0 || !("agentId" in e) || check_63(e.agentId)) && check_343(e.expected) && check_345(e.target) && (e.abandonSource === void 0 || !("abandonSource" in e) || check_326(e.abandonSource)) && check_350(e);
var check_343 = (e) => typeof e == "object" && e !== null && !Array.isArray(e) && "generation" in e && "environmentId" in e && "ownerEpoch" in e && Object.getOwnPropertyNames(e).every((t, n) => External[90].test(t) || check_2(e[t])) && check_344(e.generation) && check_287(e.environmentId) && check_310(e.ownerEpoch);
var check_344 = (e) => Number.isInteger(e) && (!(Number.isFinite(e) || typeof e == "bigint") || e >= 0 && e <= 9007199254740991);
var check_345 = (e) => check_346(e) || check_347(e) || check_349(e);
var check_346 = (e) => typeof e == "object" && e !== null && !Array.isArray(e) && "kind" in e && Object.getOwnPropertyNames(e).every((t, n) => External[91].test(t) || check_2(e[t])) && check_152(e.kind);
var check_347 = (e) => typeof e == "object" && e !== null && !Array.isArray(e) && "kind" in e && "profileId" in e && Object.getOwnPropertyNames(e).every((t, n) => External[92].test(t) || check_2(e[t])) && check_348(e.kind) && check_287(e.profileId) && (e.machineClass === void 0 || !("machineClass" in e) || check_259(e.machineClass)) && (e.os === void 0 || !("os" in e) || check_327(e.os));
var check_348 = (e) => typeof e == "string" && e === "profile";
var check_349 = (e) => typeof e == "object" && e !== null && !Array.isArray(e) && "kind" in e && "deviceId" in e && Object.getOwnPropertyNames(e).every((t, n) => External[93].test(t) || check_2(e[t])) && check_68(e.kind) && check_287(e.deviceId);
var check_350 = (e) => check_351(e) || check_352(e);
var check_351 = (e) => typeof e == "object" && e !== null && !Array.isArray(e) && "target" in e && check_346(e.target);
var check_352 = (e) => typeof e == "object" && e !== null && !Array.isArray(e) && "target" in e && check_353(e.target) && !check_354(e);
var check_353 = (e) => check_347(e) || check_349(e);
var check_354 = (e) => !(typeof e == "object" && e !== null && !Array.isArray(e)) || "abandonSource" in e;
var isSessionsDispatchParams = (e) => check_324(e);
var isSessionsMoveParams = (e) => check_341(e);
//#endregion
//#region packages/normalization-core/src/json-schema.ts
/** Remove complete false-schema child groups immediately preceding their aggregate. */
function normalizeTypeBoxValidationErrors(e) {
	const t = [];
	let n = 0;
	for (const r of e) {
		if (r.keyword === "boolean") {
			t.push(r);
			n += 1;
			continue;
		}
		const e = r.params?.additionalProperties;
		if (r.keyword === "additionalProperties" && typeof r.schemaPath === "string" && typeof r.instancePath === "string" && Array.isArray(e) && e.length > 0 && e.length <= n) {
			if (t.slice(-e.length).every((t, n) => {
				const i = e[n];
				return typeof i === "string" && t.schemaPath === `${r.schemaPath}/additionalProperties` && t.instancePath === `${r.instancePath}/${i.replace(/~/g, "~0").replace(/\//g, "~1")}`;
			})) t.length -= e.length;
		}
		t.push(r);
		n = 0;
	}
	return t;
}
//#endregion
//#region packages/gateway-protocol/src/protocol-validator.ts
/* @__NO_SIDE_EFFECTS__ */
function createProtocolValidator(e, t, n, r) {
	let i = null;
	const a = Object.assign((a) => {
		const o = n?.(a);
		if (o) {
			i = [o];
			return false;
		}
		const s = t(a);
		if (s) i = null;
		else {
			const t = Errors(e, a)[1];
			i = normalizeTypeBoxValidationErrors((r?.(a) ?? t).slice(0, t.length));
		}
		return s;
	}, {
		errors: null,
		schema: e
	});
	Object.defineProperties(a, {
		errors: {
			configurable: true,
			enumerable: true,
			get: () => i,
			set: (e) => {
				i = e ?? null;
			}
		},
		schema: {
			configurable: true,
			enumerable: true,
			get: () => e
		}
	});
	return a;
}
//#endregion
//#region packages/gateway-protocol/src/worker-capacity.ts
const NODE_WORKER_CAPACITY_MAX = 1024;
//#endregion
//#region packages/gateway-protocol/src/secret-ref-contract.ts
/** Canonical id for file secret providers that expose exactly one value. */
const SINGLE_VALUE_FILE_REF_ID = "value";
/** Shared alias grammar for env/file/exec/store secret provider names. */
const SECRET_PROVIDER_ALIAS_PATTERN = /^[a-z][a-z0-9_-]{0,63}$/;
/** JSON-schema fragment that rejects invalid JSON-pointer escape sequences. */
const FILE_SECRET_REF_ID_INVALID_ESCAPE_JSON_SCHEMA_PATTERN = "~(?:[^01]|$)";
/** JSON-schema pattern for exec secret ref ids, excluding dot-path traversal. */
const EXEC_SECRET_REF_ID_JSON_SCHEMA_PATTERN = "^(?!.*(?:^|/)\\.{1,2}(?:/|$))[A-Za-z0-9][A-Za-z0-9._:/#-]{0,255}$";
//#endregion
//#region packages/gateway-protocol/src/schema/primitives.ts
/**
* Shared schema primitives reused by gateway protocol request/result schemas.
*
* Keep these schemas small and transport-oriented; feature-specific validation
* belongs in the owning schema module or runtime handler.
*/
const ENV_SECRET_REF_ID_RE = /^[A-Z][A-Z0-9_]{0,127}$/;
const INPUT_PROVENANCE_KIND_VALUES = [
	"external_user",
	"inter_session",
	"internal_system"
];
const SESSION_LABEL_MAX_LENGTH = 512;
/** Non-empty string primitive for protocol fields that reject blank values. */
const NonEmptyString = Type.String({ minLength: 1 });
/** SHA-256 hex content version accepted by workspace and skill file operations. */
const Sha256String = Type.String({
	minLength: 64,
	maxLength: 64,
	pattern: "^[a-fA-F0-9]{64}$"
});
const UserProfileIdSchema = Type.String({
	minLength: 1,
	maxLength: 128
});
/** Chat-send session key string primitive with bounded length. */
const ChatSendSessionKeyString = Type.String({
	minLength: 1,
	maxLength: 512
});
/** Human-readable session label primitive with bounded display length. */
const SessionLabelString = Type.String({
	minLength: 1,
	maxLength: SESSION_LABEL_MAX_LENGTH
});
/** Provenance marker for content copied from another user/session/system source. */
const InputProvenanceSchema = closedObject({
	kind: Type.String({ enum: [...INPUT_PROVENANCE_KIND_VALUES] }),
	originSessionId: Type.Optional(Type.String()),
	sourceSessionKey: Type.Optional(Type.String()),
	sourceChannel: Type.Optional(Type.String()),
	sourceTool: Type.Optional(Type.String()),
	sourceRole: Type.Optional(Type.Literal("subagent")),
	sourcePromptPrefix: Type.Optional(Type.String()),
	jobId: Type.Optional(Type.String()),
	runId: Type.Optional(Type.String())
});
/** Closed gateway client id schema aligned with `GATEWAY_CLIENT_IDS`. */
const GatewayClientIdSchema = Type.Enum(GATEWAY_CLIENT_IDS);
/** Closed gateway client mode schema aligned with `GATEWAY_CLIENT_MODES`. */
const GatewayClientModeSchema = Type.Enum(GATEWAY_CLIENT_MODES);
const SecretProviderAliasString = Type.String({ pattern: SECRET_PROVIDER_ALIAS_PATTERN.source });
const EnvSecretRefSchema = closedObject({
	source: Type.Literal("env"),
	provider: SecretProviderAliasString,
	id: Type.String({ pattern: ENV_SECRET_REF_ID_RE.source })
});
const FileSecretRefIdSchema = Type.Unsafe({
	type: "string",
	anyOf: [{ const: SINGLE_VALUE_FILE_REF_ID }, { allOf: [{ pattern: "^/" }, { not: { pattern: FILE_SECRET_REF_ID_INVALID_ESCAPE_JSON_SCHEMA_PATTERN } }] }]
});
const FileSecretRefSchema = closedObject({
	source: Type.Literal("file"),
	provider: SecretProviderAliasString,
	id: FileSecretRefIdSchema
});
const ExecSecretRefSchema = closedObject({
	source: Type.Literal("exec"),
	provider: SecretProviderAliasString,
	id: Type.String({ pattern: EXEC_SECRET_REF_ID_JSON_SCHEMA_PATTERN })
});
const StoreSecretRefSchema = closedObject({
	source: Type.Literal("store"),
	provider: SecretProviderAliasString,
	id: Type.String({ pattern: ENV_SECRET_REF_ID_RE.source })
});
/** Structured secret reference accepted by config and channel protocol payloads. */
const SecretRefSchema = Type.Union([
	EnvSecretRefSchema,
	FileSecretRefSchema,
	ExecSecretRefSchema,
	StoreSecretRefSchema
]);
/** Secret input value: either an inline string or a structured SecretRef. */
const SecretInputSchema = Type.Union([Type.String(), SecretRefSchema]);
//#endregion
//#region packages/gateway-protocol/src/schema/environments.ts
/**
* Environment inventory protocol schemas.
*
* Environments are runtime targets such as local hosts, VMs, or remote workers;
* this schema layer only describes their gateway-visible status summary.
*/
/** Runtime availability state for an environment target. */
const EnvironmentStatusSchema = Type.String({ enum: [
	"available",
	"unavailable",
	"starting",
	"stopping",
	"error"
] });
const EnvironmentTrustSchema = Type.String({ enum: ["persistent", "disposable"] });
/** Operational desktop state reported by the current native node connection. */
const DesktopAvailabilitySchema = closedObject({ state: Type.Union([
	Type.Literal("locked"),
	Type.Literal("unlocked"),
	Type.Literal("unknown")
]) });
/** Durable lifecycle states for plugin-provisioned worker environments. */
const WorkerEnvironmentStateSchema = Type.Union([
	Type.Literal("requested"),
	Type.Literal("provisioning"),
	Type.Literal("bootstrapping"),
	Type.Literal("ready"),
	Type.Literal("attached"),
	Type.Literal("idle"),
	Type.Literal("draining"),
	Type.Literal("destroying"),
	Type.Literal("destroyed"),
	Type.Literal("failed"),
	Type.Literal("orphaned")
]);
/** Process-local SSH tunnel connectivity for a worker environment. */
const WorkerTunnelStatusSchema = Type.Union([
	Type.Literal("stopped"),
	Type.Literal("connecting"),
	Type.Literal("connected"),
	Type.Literal("reconnecting")
]);
/** Closed app ids a worker desktop may advertise and launch. */
const WorkerDesktopAppIdSchema = Type.Union([Type.Literal("browser"), Type.Literal("terminal")]);
/** Actionable issue attached only to runtime targets that need operator intervention. */
const RuntimeTargetIssueSchema = Type.Union([closedObject({
	code: Type.Literal("update-required"),
	action: Type.Literal("update-and-reconnect"),
	updateCommand: Type.Literal("openclaw update"),
	headlessReconnectCommand: Type.Literal("openclaw node restart")
}), closedObject({
	code: Type.Literal("worker-host-unavailable"),
	message: Type.String({
		minLength: 1,
		maxLength: 1024
	})
})]);
const NodeWorkerBundleStatusSchema = Type.Union([closedObject({
	status: Type.Literal("installed"),
	version: NonEmptyString
}), closedObject({ status: Type.Literal("missing") })]);
/** Bounded live worker slots advertised by a connected node host. */
const WorkerSlotSummarySchema = Type.Refine(closedObject({
	total: Type.Integer({
		minimum: 1,
		maximum: NODE_WORKER_CAPACITY_MAX
	}),
	available: Type.Integer({
		minimum: 0,
		maximum: NODE_WORKER_CAPACITY_MAX
	}),
	reclaimableIdle: Type.Optional(Type.Integer({
		minimum: 0,
		maximum: 2
	}))
}), (e) => e.available + (e.reclaimableIdle ?? 0) <= e.total, (e) => `available worker slots ${e.available} exceed total ${e.total}`);
/** Gateway-owned authority state for one runtime-required node command. */
const RequiredNodeCommandStateSchema = Type.Union([
	Type.Literal("invocable"),
	Type.Literal("pending-approval"),
	Type.Literal("undeclared"),
	Type.Literal("unauthorized")
]);
const RequiredNodeCommandSchema = closedObject({
	command: Type.String({
		minLength: 1,
		maxLength: 128
	}),
	state: RequiredNodeCommandStateSchema,
	message: Type.Optional(NonEmptyString)
});
/** Worker-only lifecycle metadata layered onto the existing environment projection. */
const WorkerEnvironmentStartStatusSchema = Type.Union([closedObject({
	mode: Type.Literal("snapshot"),
	phase: Type.Optional(Type.Literal("saving"))
}), closedObject({
	mode: Type.Literal("cold"),
	reason: Type.Union([
		Type.Literal("no-snapshot-yet"),
		Type.Literal("setup-changed"),
		Type.Literal("snapshot-retiring"),
		Type.Literal("snapshot-unavailable"),
		Type.Literal("os-unsupported"),
		Type.Literal("warm-images-off"),
		Type.Literal("capture-paused"),
		Type.Literal("backend-cannot-snapshot"),
		Type.Literal("class-unknown")
	]),
	phase: Type.Union([
		Type.Literal("provisioning"),
		Type.Literal("preparing"),
		Type.Literal("saving")
	])
})]);
const WorkerEnvironmentMetadataSchema = closedObject({
	profileId: Type.Optional(NonEmptyString),
	providerId: NonEmptyString,
	leaseId: Type.Optional(NonEmptyString),
	state: WorkerEnvironmentStateSchema,
	startStatus: Type.Optional(WorkerEnvironmentStartStatusSchema),
	ageMs: Type.Integer({ minimum: 0 }),
	idleMs: Type.Optional(Type.Integer({ minimum: 0 })),
	destroyRequestedAtMs: Type.Optional(Type.Integer({ minimum: 0 })),
	attachedSessionIds: Type.Array(NonEmptyString),
	tunnelStatus: WorkerTunnelStatusSchema,
	error: Type.Optional(NonEmptyString),
	desktop: Type.Optional(Type.Boolean()),
	desktopApps: Type.Optional(Type.Array(WorkerDesktopAppIdSchema, {
		maxItems: 8,
		uniqueItems: true
	}))
});
function createEnvironmentSummaryProperties() {
	return {
		id: NonEmptyString,
		type: NonEmptyString,
		label: Type.Optional(NonEmptyString),
		status: EnvironmentStatusSchema,
		platform: Type.Optional(NonEmptyString),
		sessionHost: Type.Optional(Type.Boolean()),
		workerSlots: Type.Optional(WorkerSlotSummarySchema),
		workerHost: Type.Optional(closedObject({ deviceFolders: Type.Optional(Type.Literal(true)) })),
		workerBundle: Type.Optional(NodeWorkerBundleStatusSchema),
		lastConnectedAtMs: Type.Optional(Type.Integer({ minimum: 0 })),
		lastDisconnectedAtMs: Type.Optional(Type.Integer({ minimum: 0 })),
		lastSeenAtMs: Type.Optional(Type.Integer({ minimum: 0 })),
		lastSeenReason: Type.Optional(NonEmptyString),
		trust: Type.Optional(EnvironmentTrustSchema),
		capabilities: Type.Optional(Type.Array(NonEmptyString)),
		invocableCommands: Type.Optional(Type.Array(Type.String({
			minLength: 1,
			maxLength: 128
		}), {
			maxItems: 128,
			uniqueItems: true
		})),
		desktop: Type.Optional(Type.Boolean()),
		desktopAvailability: Type.Optional(DesktopAvailabilitySchema),
		issues: Type.Optional(Type.Array(RuntimeTargetIssueSchema, {
			minItems: 1,
			maxItems: 8
		})),
		worker: Type.Optional(WorkerEnvironmentMetadataSchema),
		preparation: Type.Optional(closedObject({
			purpose: Type.Union([Type.Literal("reserve"), Type.Literal("build")]),
			key: NonEmptyString,
			details: Type.Optional(closedObject({
				demandAtMs: Type.Integer({ minimum: 0 }),
				expiresAtMs: Type.Integer({ minimum: 0 }),
				consumedAtMs: Type.Union([Type.Integer({ minimum: 0 }), Type.Null()]),
				project: Type.Optional(closedObject({
					label: Type.Optional(NonEmptyString),
					baseCommit: NonEmptyString
				}))
			}))
		}))
	};
}
/** Public environment summary shown in listings and status responses. */
const EnvironmentSummarySchema = closedObject({
	...createEnvironmentSummaryProperties(),
	requiredNodeCommand: Type.Optional(RequiredNodeCommandSchema),
	desktopSetup: Type.Optional(closedObject({
		state: Type.Union([
			Type.Literal("ready"),
			Type.Literal("needs-server"),
			Type.Literal("unsupported"),
			Type.Literal("managed")
		]),
		detail: Type.Optional(NonEmptyString)
	}))
});
/** Optional runtime scope or profile-only projection for environment discovery. */
const EnvironmentsListParamsSchema = closedObject({
	runtimeId: Type.Optional(Type.String({
		minLength: 1,
		maxLength: 128
	})),
	projection: Type.Optional(Type.Literal("profiles")),
	includeDesktopSetup: Type.Optional(Type.Boolean()),
	includePreparedDetails: Type.Optional(Type.Boolean())
});
/** Provider-authored machine choice for one configured worker profile. */
const WorkerMachineOptionSchema = closedObject({
	id: Type.String({
		minLength: 1,
		maxLength: 128
	}),
	label: Type.String({
		minLength: 1,
		maxLength: 128
	}),
	cpu: Type.Optional(Type.Integer({
		minimum: 1,
		maximum: 65536
	})),
	memoryGb: Type.Optional(Type.Integer({
		minimum: 1,
		maximum: 65536
	})),
	default: Type.Optional(Type.Boolean()),
	os: Type.Optional(Type.String({
		minLength: 1,
		maxLength: 64
	}))
});
const WorkerMachineOptionsSchema = Type.Array(WorkerMachineOptionSchema, {
	minItems: 1,
	maxItems: 64
});
/** Provider-authored operating system choice for one configured worker profile. */
const WorkerOperatingSystemSchema = closedObject({
	id: Type.String({
		minLength: 1,
		maxLength: 64
	}),
	label: Type.String({
		minLength: 1,
		maxLength: 64
	}),
	default: Type.Optional(Type.Boolean()),
	disabledReason: Type.Optional(Type.String({
		minLength: 1,
		maxLength: 256
	}))
});
/** Placement execution modes shared by runtime requirements and worker providers. */
const WorkerExecutionModeSchema = Type.Union([Type.Literal("worker-turn"), Type.Literal("remote-exec")]);
/** Configured worker target exposed without provider settings or credentials. */
const WorkerEnvironmentProfileSummarySchema = closedObject({
	id: NonEmptyString,
	providerId: NonEmptyString,
	inference: Type.Optional(Type.Literal("worker")),
	readyWorkers: Type.Optional(Type.Integer({ minimum: 0 })),
	providerDisplayId: Type.Optional(Type.String({
		pattern: "^[a-z][a-z0-9-]{0,63}(?![\\s\\S])",
		maxLength: 64
	})),
	trust: Type.Optional(EnvironmentTrustSchema),
	executionMode: Type.Optional(WorkerExecutionModeSchema),
	executionModes: Type.Optional(Type.Union([Type.Tuple([WorkerExecutionModeSchema]), Type.Tuple([Type.Literal("worker-turn"), Type.Literal("remote-exec")])])),
	machines: Type.Optional(WorkerMachineOptionsSchema),
	operatingSystems: Type.Optional(Type.Array(WorkerOperatingSystemSchema, {
		minItems: 1,
		maxItems: 8
	}))
});
/** A discoverable config proposal, never an admitted placement destination. */
const SuggestedWorkerProfileSummarySchema = closedObject({
	id: NonEmptyString,
	providerId: NonEmptyString,
	providerDisplayId: Type.Optional(Type.String({
		pattern: "^[a-z][a-z0-9-]{0,63}(?![\\s\\S])",
		maxLength: 64
	}))
});
const EnvironmentsAdoptSuggestedProfileParamsSchema = closedObject({});
const EnvironmentsAdoptSuggestedProfileResultSchema = closedObject({ profile: WorkerEnvironmentProfileSummarySchema });
/** Profile-only requests leave environments empty without reading inventory. */
const EnvironmentsListResultSchema = closedObject({
	requiredProfile: Type.Optional(NonEmptyString),
	environments: Type.Array(EnvironmentSummarySchema),
	profiles: Type.Optional(Type.Array(WorkerEnvironmentProfileSummarySchema)),
	dispatchableProfileIds: Type.Optional(Type.Array(NonEmptyString, { uniqueItems: true })),
	suggestedProfile: Type.Optional(SuggestedWorkerProfileSummarySchema),
	preparedPool: Type.Optional(closedObject({
		maxTotal: Type.Integer({ minimum: 0 }),
		reservedEnvironmentIds: Type.Array(NonEmptyString, { uniqueItems: true })
	}))
});
/** Status lookup request for one environment id. */
const EnvironmentsStatusParamsSchema = closedObject({
	environmentId: NonEmptyString,
	includePreparedDetails: Type.Optional(Type.Boolean())
});
/** Status lookup result for one environment id. */
const EnvironmentsStatusResultSchema = closedObject(createEnvironmentSummaryProperties());
/** Creates a worker environment from one configured provider profile. */
const EnvironmentsCreateParamsSchema = closedObject({
	profileId: NonEmptyString,
	idempotencyKey: NonEmptyString
});
/** Create result uses the same public summary shape as list and status. */
const EnvironmentsCreateResultSchema = closedObject(createEnvironmentSummaryProperties());
/** Prepares a configured profile's local Git project without dispatching a session. */
const EnvironmentsPrepareParamsSchema = closedObject({
	profileId: NonEmptyString,
	projectPath: NonEmptyString
});
const EnvironmentsPrepareResultSchema = closedObject({
	environmentId: NonEmptyString,
	preparationKey: NonEmptyString,
	reused: Type.Boolean()
});
/** Destroys one durable worker environment by its gateway-owned id. */
const EnvironmentsDestroyParamsSchema = closedObject({
	environmentId: NonEmptyString,
	force: Type.Optional(Type.Boolean())
});
/** Destroy result exposes the terminal worker lifecycle state. */
const EnvironmentsDestroyResultSchema = closedObject(createEnvironmentSummaryProperties());
const WorkerDesktopObserveParamsSchema = closedObject({
	environmentId: NonEmptyString,
	control: Type.Optional(Type.Boolean())
});
const WorkerDesktopObserveResultSchema = closedObject({
	transport: Type.String({ enum: ["rfb"] }),
	wsPath: NonEmptyString,
	expiresAtMs: Type.Integer({ minimum: 0 }),
	control: Type.Boolean(),
	canResize: Type.Optional(Type.Boolean()),
	vncPassword: Type.Optional(NonEmptyString)
});
const WorkerDesktopLaunchParamsSchema = closedObject({
	environmentId: NonEmptyString,
	app: WorkerDesktopAppIdSchema
});
const WorkerDesktopLaunchResultSchema = closedObject({
	app: WorkerDesktopAppIdSchema,
	status: Type.Literal("ready")
});
//#endregion
//#region packages/gateway-protocol/src/schema/session-placement-state.ts
const SESSION_PLACEMENT_STATES = [
	"local",
	"requested",
	"provisioning",
	"syncing",
	"starting",
	"active",
	"draining",
	"reconciling",
	"reclaimed",
	"failed"
];
//#endregion
//#region packages/gateway-protocol/src/schema/worker-protocol-primitives.ts
const WORKER_PROTOCOL_MAX_FRAME_ID_LENGTH = 128;
const WORKER_PROTOCOL_MAX_PAYLOAD_BYTES = 65536;
const WorkerIdentifierSchema = Type.String({
	minLength: 1,
	maxLength: 256,
	pattern: "^\\S(?:.*\\S)?$"
});
const WorkerFrameIdSchema = Type.String({
	minLength: 1,
	maxLength: 128
});
const WorkerAdmissionFailureReasonSchema = Type.Union([
	Type.Literal("invalid-credential"),
	Type.Literal("credential-expired"),
	Type.Literal("environment-mismatch"),
	Type.Literal("environment-unavailable"),
	Type.Literal("bundle-mismatch"),
	Type.Literal("version-mismatch"),
	Type.Literal("session-mismatch"),
	Type.Literal("placement-mismatch"),
	Type.Literal("owner-epoch-mismatch"),
	Type.Literal("rpc-set-mismatch"),
	Type.Literal("protocol-features-mismatch")
]);
const WorkerProtocolCloseReasonSchema = Type.Union([
	WorkerAdmissionFailureReasonSchema,
	Type.Literal("admission-rejected"),
	Type.Literal("invalid-handshake"),
	Type.Literal("protocol-mismatch"),
	Type.Literal("gateway-unavailable"),
	Type.Literal("invalid-frame"),
	Type.Literal("slow-consumer"),
	Type.Literal("method-not-allowed"),
	Type.Literal("invalid-heartbeat"),
	Type.Literal("credential-replaced"),
	Type.Literal("gateway-shutdown")
]);
const WorkerErrorShapeSchema = closedObject({
	code: Type.Union([Type.Literal("INVALID_REQUEST"), Type.Literal("UNAVAILABLE")]),
	message: Type.String({
		minLength: 1,
		maxLength: 256
	}),
	details: closedObject({ reason: WorkerProtocolCloseReasonSchema }),
	retryable: Type.Optional(Type.Boolean()),
	retryAfterMs: Type.Optional(Type.Integer({ minimum: 0 }))
});
function workerErrorResponseSchema(e) {
	return closedObject({
		type: Type.Literal("res"),
		id: WorkerFrameIdSchema,
		ok: Type.Literal(false),
		error: e
	});
}
const WorkerErrorResponseFrameSchema = workerErrorResponseSchema(WorkerErrorShapeSchema);
const WorkerInferenceUsageSchema = closedObject({
	input: Type.Number({ minimum: 0 }),
	output: Type.Number({ minimum: 0 }),
	cacheRead: Type.Number({ minimum: 0 }),
	cacheWrite: Type.Number({ minimum: 0 }),
	usageReport: Type.Optional(closedObject({ state: Type.Union([Type.Literal("available"), Type.Literal("unavailable")]) })),
	contextUsage: Type.Optional(Type.Union([closedObject({
		state: Type.Literal("available"),
		promptTokens: Type.Number({ minimum: 0 }),
		totalTokens: Type.Number({ minimum: 0 })
	}), closedObject({ state: Type.Literal("unavailable") })])),
	totalTokens: Type.Number({ minimum: 0 }),
	cost: closedObject({
		input: Type.Number({ minimum: 0 }),
		output: Type.Number({ minimum: 0 }),
		cacheRead: Type.Number({ minimum: 0 }),
		cacheWrite: Type.Number({ minimum: 0 }),
		total: Type.Number({ minimum: 0 }),
		totalOrigin: Type.Optional(Type.Literal("provider-billed"))
	})
});
const WorkerTranscriptUsageSchema = closedObject({
	...WorkerInferenceUsageSchema.properties,
	cost: Type.Optional(WorkerInferenceUsageSchema.properties.cost)
});
const WorkerTranscriptAssistantDiagnosticSchema = closedObject({
	type: WorkerIdentifierSchema,
	timestamp: Type.Integer({ minimum: 0 }),
	error: Type.Optional(closedObject({
		name: Type.Optional(Type.String({ maxLength: 256 })),
		message: Type.String({ maxLength: WORKER_PROTOCOL_MAX_PAYLOAD_BYTES }),
		stack: Type.Optional(Type.String({ maxLength: WORKER_PROTOCOL_MAX_PAYLOAD_BYTES })),
		code: Type.Optional(Type.Union([Type.String({ maxLength: 256 }), Type.Number()]))
	})),
	details: Type.Optional(Type.Record(Type.String({
		minLength: 1,
		maxLength: 256
	}), Type.Unknown()))
});
const LiveTextSchema = Type.String({ maxLength: WORKER_PROTOCOL_MAX_PAYLOAD_BYTES });
const LiveIntegerSchema = Type.Integer({
	minimum: 0,
	maximum: Number.MAX_SAFE_INTEGER
});
const LiveSequenceSchema = Type.Integer({
	minimum: 1,
	maximum: Number.MAX_SAFE_INTEGER
});
const WORKER_PROVIDER_REPLAY_MAX_DATA_BYTES = WORKER_PROTOCOL_MAX_PAYLOAD_BYTES;
const WorkerReplayHashSchema = Type.String({
	minLength: 2,
	maxLength: 16,
	pattern: "^[a-z0-9]+$"
});
const WorkerProviderReplayStateSchema = closedObject({
	v: Type.Literal(1),
	type: WorkerIdentifierSchema,
	id: Type.Optional(Type.String({
		minLength: 1,
		maxLength: WORKER_PROTOCOL_MAX_PAYLOAD_BYTES
	})),
	data: Type.String({
		minLength: 1,
		maxLength: WORKER_PROVIDER_REPLAY_MAX_DATA_BYTES
	}),
	replayIndex: Type.Optional(Type.Integer({
		minimum: 0,
		maximum: Number.MAX_SAFE_INTEGER
	})),
	provider: WorkerIdentifierSchema,
	api: WorkerIdentifierSchema,
	model: WorkerIdentifierSchema,
	baseUrlHash: Type.Optional(WorkerReplayHashSchema),
	sessionHash: Type.Optional(WorkerReplayHashSchema),
	authProfileHash: Type.Optional(WorkerReplayHashSchema)
});
//#endregion
//#region packages/gateway-protocol/src/schema/session-placement.ts
/** Durable gateway ownership states for one session execution placement. */
const SessionPlacementStateSchema = stringLiteralUnion(SESSION_PLACEMENT_STATES);
const SessionPlacementTimingProperties = {
	generation: Type.Integer({
		minimum: 0,
		maximum: Number.MAX_SAFE_INTEGER
	}),
	createdAtMs: Type.Integer({
		minimum: 0,
		maximum: Number.MAX_SAFE_INTEGER
	}),
	updatedAtMs: Type.Integer({
		minimum: 0,
		maximum: Number.MAX_SAFE_INTEGER
	}),
	stateChangedAtMs: Type.Integer({
		minimum: 0,
		maximum: Number.MAX_SAFE_INTEGER
	})
};
const SessionPlacementOwnerEpochSchema = Type.Integer({
	minimum: 1,
	maximum: Number.MAX_SAFE_INTEGER
});
const WorkerBundleHashSchema = Type.String({
	minLength: 64,
	maxLength: 64,
	pattern: "^[a-f0-9]{64}$"
});
const SessionPlacementWorkspaceProperties = {
	workspaceBaseManifestRef: NonEmptyString,
	remoteWorkspaceDir: NonEmptyString
};
const SessionPlacementAckProperties = {
	lastTranscriptAckCursor: Type.Optional(Type.Integer({
		minimum: 0,
		maximum: Number.MAX_SAFE_INTEGER
	})),
	lastLiveEventAckCursor: Type.Optional(Type.Integer({
		minimum: 0,
		maximum: Number.MAX_SAFE_INTEGER
	}))
};
const SessionPlacementDiskSpaceSchema = closedObject({
	status: stringLiteralUnion([
		"ok",
		"warning",
		"critical"
	]),
	availableBytes: Type.Integer({
		minimum: 0,
		maximum: Number.MAX_SAFE_INTEGER
	}),
	totalBytes: Type.Integer({
		minimum: 0,
		maximum: Number.MAX_SAFE_INTEGER
	}),
	observedAtMs: Type.Integer({
		minimum: 0,
		maximum: Number.MAX_SAFE_INTEGER
	})
});
const SessionPlacementWorkerRuntimeInstallSchema = closedObject({
	phase: stringLiteralUnion(["transferring", "installing"]),
	transferredBytes: Type.Integer({
		minimum: 0,
		maximum: Number.MAX_SAFE_INTEGER
	}),
	totalBytes: Type.Integer({
		minimum: 1,
		maximum: Number.MAX_SAFE_INTEGER
	}),
	startedAtMs: Type.Integer({
		minimum: 0,
		maximum: Number.MAX_SAFE_INTEGER
	}),
	updatedAtMs: Type.Integer({
		minimum: 0,
		maximum: Number.MAX_SAFE_INTEGER
	})
});
const SessionPlacementRunnerSchema = closedObject({
	kind: Type.Literal("device"),
	status: stringLiteralUnion(["available", "offline"]),
	deviceId: Type.Optional(WorkerIdentifierSchema)
});
const SessionPlacementDiskSpaceProperties = { diskSpace: Type.Optional(SessionPlacementDiskSpaceSchema) };
const WORKER_MACHINE_CLASS_MAX_LENGTH = 128;
const WORKER_OPERATING_SYSTEM_MAX_LENGTH = 64;
const WorkerMachineClassSchema = Type.String({
	minLength: 1,
	maxLength: WORKER_MACHINE_CLASS_MAX_LENGTH
});
const WorkerOperatingSystemIdSchema = Type.String({
	minLength: 1,
	maxLength: WORKER_OPERATING_SYSTEM_MAX_LENGTH
});
const SessionPlacementMachineSchema = closedObject({
	class: Type.Optional(WorkerMachineClassSchema),
	os: Type.Optional(WorkerOperatingSystemIdSchema),
	osLabel: Type.Optional(Type.String({
		minLength: 1,
		maxLength: WORKER_OPERATING_SYSTEM_MAX_LENGTH
	})),
	cpu: Type.Optional(Type.Integer({
		minimum: 1,
		maximum: 65536
	})),
	memoryGb: Type.Optional(Type.Integer({
		minimum: 1,
		maximum: 65536
	}))
});
const SessionPlacementIdentityProperties = {
	providerId: Type.Optional(NonEmptyString),
	profileId: Type.Optional(NonEmptyString),
	machine: Type.Optional(SessionPlacementMachineSchema)
};
const WorkspaceResultConflictSchema = closedObject({
	paths: Type.Array(NonEmptyString, {
		minItems: 1,
		maxItems: 256
	}),
	stagedResultRef: NonEmptyString,
	totalCount: Type.Optional(Type.Integer({
		minimum: 1,
		maximum: Number.MAX_SAFE_INTEGER
	}))
});
const SessionPlacementConflictProperties = { workspaceResultConflict: Type.Optional(WorkspaceResultConflictSchema) };
const SessionPlacementWorkspaceReconciliationProperties = { workspaceResultReconciling: Type.Optional(Type.Literal(true)) };
const TerminalSessionPlacementProperties = {
	...SessionPlacementIdentityProperties,
	environmentId: Type.Optional(NonEmptyString),
	activeOwnerEpoch: Type.Optional(SessionPlacementOwnerEpochSchema),
	workspaceBaseManifestRef: Type.Optional(NonEmptyString),
	remoteWorkspaceDir: Type.Optional(NonEmptyString),
	workerBundleHash: Type.Optional(WorkerBundleHashSchema),
	...SessionPlacementAckProperties,
	...SessionPlacementConflictProperties,
	terminalReason: Type.Optional(NonEmptyString),
	terminalAtMs: Type.Optional(Type.Integer({
		minimum: 0,
		maximum: Number.MAX_SAFE_INTEGER
	}))
};
function createUnownedSessionPlacementSchema(e) {
	return closedObject({
		state: Type.Literal(e),
		...SessionPlacementTimingProperties
	});
}
function workerOwnedSessionPlacementProperties(e) {
	return {
		state: Type.Literal(e),
		...SessionPlacementTimingProperties,
		...SessionPlacementIdentityProperties,
		environmentId: NonEmptyString,
		activeOwnerEpoch: SessionPlacementOwnerEpochSchema,
		workerBundleHash: WorkerBundleHashSchema,
		...SessionPlacementWorkspaceProperties,
		...SessionPlacementAckProperties,
		...SessionPlacementConflictProperties,
		...SessionPlacementDiskSpaceProperties
	};
}
const LocalSessionPlacementSchema = createUnownedSessionPlacementSchema("local");
const RequestedSessionPlacementSchema = createUnownedSessionPlacementSchema("requested");
const ProvisioningSessionPlacementSchema = closedObject({
	state: Type.Literal("provisioning"),
	...SessionPlacementTimingProperties,
	...SessionPlacementIdentityProperties,
	environmentId: Type.Optional(NonEmptyString),
	workerRuntimeInstall: Type.Optional(SessionPlacementWorkerRuntimeInstallSchema),
	startStatus: Type.Optional(WorkerEnvironmentStartStatusSchema)
});
const SyncingSessionPlacementSchema = closedObject({
	state: Type.Literal("syncing"),
	...SessionPlacementTimingProperties,
	...SessionPlacementIdentityProperties,
	environmentId: NonEmptyString,
	workerBundleHash: WorkerBundleHashSchema
});
const StartingSessionPlacementSchema = closedObject({
	state: Type.Literal("starting"),
	...SessionPlacementTimingProperties,
	...SessionPlacementIdentityProperties,
	environmentId: NonEmptyString,
	workerBundleHash: WorkerBundleHashSchema,
	...SessionPlacementWorkspaceProperties
});
const ActiveWorkerSessionPlacementSchema = closedObject({
	...workerOwnedSessionPlacementProperties("active"),
	inference: Type.Optional(Type.Literal("worker")),
	...SessionPlacementWorkspaceReconciliationProperties,
	runner: Type.Optional(SessionPlacementRunnerSchema),
	workerRuntimeInstall: Type.Optional(SessionPlacementWorkerRuntimeInstallSchema)
});
const DrainingSessionPlacementSchema = closedObject({
	...workerOwnedSessionPlacementProperties("draining"),
	...SessionPlacementWorkspaceReconciliationProperties
});
const ReconcilingSessionPlacementSchema = closedObject({ ...workerOwnedSessionPlacementProperties("reconciling") });
const ReclaimedSessionPlacementSchema = closedObject({
	state: Type.Literal("reclaimed"),
	...SessionPlacementTimingProperties,
	...TerminalSessionPlacementProperties
});
const FailedSessionPlacementSchema = closedObject({
	state: Type.Literal("failed"),
	...SessionPlacementTimingProperties,
	...TerminalSessionPlacementProperties,
	recoveryError: NonEmptyString,
	recoveryAction: Type.Optional(Type.Enum(["restart", "stop-first"], { type: "string" })),
	retryOnSend: Type.Optional(Type.Literal(true))
});
/** Gateway-visible placement projection; `state` remains the closed discriminator. */
const SessionPlacementSchema = Type.Union([
	LocalSessionPlacementSchema,
	RequestedSessionPlacementSchema,
	ProvisioningSessionPlacementSchema,
	SyncingSessionPlacementSchema,
	StartingSessionPlacementSchema,
	ActiveWorkerSessionPlacementSchema,
	DrainingSessionPlacementSchema,
	ReconcilingSessionPlacementSchema,
	ReclaimedSessionPlacementSchema,
	FailedSessionPlacementSchema
]);
/**
* Requests one-way dispatch to an explicit or automatically selected device (`operator.write`),
* an explicit profile (`operator.write` plus administrator authority or a current role grant
* for the session's verified creator), or an `operator.admin`-only
* `cloudWorkers.projectProfiles` lookup when no target is supplied. Target modes are exclusive.
* An absent, unmatched, or invalid mapping is rejected with `INVALID_REQUEST` instead of
* provisioning or falling back to another target. Setup remains administrator-only.
*/
const SessionsDispatchParamsSchema = Type.Object({
	key: NonEmptyString,
	agentId: Type.Optional(NonEmptyString),
	profileId: Type.Optional(NonEmptyString),
	deviceId: Type.Optional(NonEmptyString),
	autoDevice: Type.Optional(Type.Literal(true)),
	machineClass: Type.Optional(WorkerMachineClassSchema),
	os: Type.Optional(WorkerOperatingSystemIdSchema)
}, {
	additionalProperties: false,
	oneOf: [
		{
			required: ["profileId"],
			not: { anyOf: [{ required: ["deviceId"] }, { required: ["autoDevice"] }] }
		},
		{
			required: ["deviceId"],
			not: { anyOf: [
				{ required: ["profileId"] },
				{ required: ["autoDevice"] },
				{ required: ["machineClass"] },
				{ required: ["os"] }
			] }
		},
		{
			required: ["autoDevice"],
			not: { anyOf: [
				{ required: ["profileId"] },
				{ required: ["deviceId"] },
				{ required: ["machineClass"] },
				{ required: ["os"] }
			] }
		},
		{ not: { anyOf: [
			{ required: ["profileId"] },
			{ required: ["deviceId"] },
			{ required: ["autoDevice"] },
			{ required: ["machineClass"] },
			{ required: ["os"] }
		] } }
	]
});
/** Result returned once session dispatch reaches durable worker ownership. */
const SessionsDispatchResultSchema = closedObject({
	ok: Type.Literal(true),
	key: NonEmptyString,
	sessionId: NonEmptyString,
	placement: ActiveWorkerSessionPlacementSchema
});
/** Stops a worker or explicitly recovers one failed placement onto the Gateway. */
const SessionsReclaimParamsSchema = closedObject({
	key: NonEmptyString,
	agentId: Type.Optional(NonEmptyString),
	recoverToGateway: Type.Optional(closedObject({ expectedGeneration: Type.Integer({
		minimum: 0,
		maximum: Number.MAX_SAFE_INTEGER
	}) }))
});
/** Terminal placement returned after a worker reclaim operation. */
const SessionsReclaimResultPlacementSchema = Type.Union([LocalSessionPlacementSchema, ReclaimedSessionPlacementSchema]);
/** Result returned once worker ownership is reclaimed or a failed placement is cleared. */
const SessionsReclaimResultSchema = closedObject({
	ok: Type.Literal(true),
	key: NonEmptyString,
	sessionId: NonEmptyString,
	placement: SessionsReclaimResultPlacementSchema
});
/** Exact active source observed before a session placement move. */
const SessionMoveExpectedSourceSchema = closedObject({
	generation: Type.Integer({
		minimum: 0,
		maximum: Number.MAX_SAFE_INTEGER
	}),
	environmentId: WorkerIdentifierSchema,
	ownerEpoch: SessionPlacementOwnerEpochSchema
});
/** Moves the session back to the Gateway without redispatching it. */
const SessionMoveGatewayTargetSchema = closedObject({ kind: Type.Literal("gateway") });
/** Moves the session to one configured cloud worker profile. */
const SessionMoveProfileTargetSchema = closedObject({
	kind: Type.Literal("profile"),
	profileId: WorkerIdentifierSchema,
	machineClass: Type.Optional(WorkerMachineClassSchema),
	os: Type.Optional(WorkerOperatingSystemIdSchema)
});
/** Moves the session to one paired device worker. */
const SessionMoveDeviceTargetSchema = closedObject({
	kind: Type.Literal("device"),
	deviceId: WorkerIdentifierSchema
});
/** Closed destination union for session placement moves. */
const SessionMoveTargetSchema = Type.Union([
	SessionMoveGatewayTargetSchema,
	SessionMoveProfileTargetSchema,
	SessionMoveDeviceTargetSchema
]);
const SessionsMoveTargetCorrelationSchema = Type.Union([Type.Object({ target: SessionMoveGatewayTargetSchema }), Type.Object({ target: Type.Union([SessionMoveProfileTargetSchema, SessionMoveDeviceTargetSchema]) }, { not: { required: ["abandonSource"] } })]);
const SessionMoveRequestProperties = {
	expected: SessionMoveExpectedSourceSchema,
	target: SessionMoveTargetSchema,
	abandonSource: Type.Optional(Type.Literal(true))
};
/** Durable progress and the original request facts needed after a failed move. */
const SessionPlacementMoveSchema = closedObject({
	target: SessionMoveTargetSchema,
	updatedAtMs: Type.Integer({
		minimum: 0,
		maximum: Number.MAX_SAFE_INTEGER
	}),
	error: Type.Optional(Type.String({
		minLength: 1,
		maxLength: 1024
	})),
	retry: Type.Optional(Type.Object(SessionMoveRequestProperties, {
		additionalProperties: false,
		allOf: [SessionsMoveTargetCorrelationSchema]
	}))
});
/** Requests one exact-source placement move without replaying active work. */
const SessionsMoveParamsSchema = Type.Object({
	key: NonEmptyString,
	agentId: Type.Optional(NonEmptyString),
	...SessionMoveRequestProperties
}, {
	additionalProperties: false,
	allOf: [SessionsMoveTargetCorrelationSchema]
});
/** Successful terminal states returned by sessions.move. */
const SessionMovePlacementStateSchema = stringLiteralUnion(["local", "active"]);
/** Bounded placement state returned by sessions.move. */
const SessionMovePlacementSchema = closedObject({
	state: SessionMovePlacementStateSchema,
	generation: Type.Integer({
		minimum: 0,
		maximum: Number.MAX_SAFE_INTEGER
	})
});
/** Result returned after the requested placement move reaches its destination. */
const SessionsMoveResultSchema = closedObject({
	ok: Type.Literal(true),
	key: NonEmptyString,
	sessionId: NonEmptyString,
	placement: SessionMovePlacementSchema
});
//#endregion
//#region packages/gateway-protocol/src/session-placement-validators.ts
const validateSessionsDispatchParams = /* @__PURE__ */ createProtocolValidator(SessionsDispatchParamsSchema, isSessionsDispatchParams);
const validateSessionsMoveParams = /* @__PURE__ */ createProtocolValidator(SessionsMoveParamsSchema, isSessionsMoveParams);
//#endregion
//#region src/shared/session-method-scopes.ts
/** Returns the exact Gateway/CLI scope for params-aware session mutations. */
function resolveDynamicSessionMutationRequiredScope(e, t) {
	if (e === "sessions.dispatch") {
		if (!validateSessionsDispatchParams(t)) return "operator.write";
		return t.profileId !== void 0 || t.deviceId !== void 0 || t.autoDevice === true ? "operator.write" : "operator.admin";
	}
	if (e === "sessions.move") return validateSessionsMoveParams(t) && t.target.kind === "profile" ? "operator.admin" : "operator.write";
	return resolveBaseSessionMutationRequiredScope(e, t);
}
//#endregion
//#region src/gateway/agent-command-policy.ts
/** Commands routed through `agent` that mutate session lifecycle state. */
const AGENT_SESSION_RESET_COMMAND_RE = /^\/(new|reset)(?:\s+([\s\S]*))?$/i;
function isAgentSessionResetCommand(e) {
	return typeof e === "string" && AGENT_SESSION_RESET_COMMAND_RE.test(e);
}
//#endregion
//#region src/gateway/methods/read-share-keys.ts
function operatorReadShareKey(...[e, t]) {
	const { client: n } = e;
	if (!n?.authenticatedUserProfile || n.connect.role !== "operator" || n.internal?.syntheticClient || n.internal?.agentToolCaller || n.internal?.agentRuntimeIdentity || n.internal?.operatorRunAuthority || n.internal?.pluginSubagentRequester || n.internal?.nodeInvokeStream) return null;
	return JSON.stringify([
		n.authenticatedUserProfile.profileId,
		n.authenticatedUserId,
		n.internal?.operatorRoleActor,
		(n.connect.scopes ?? []).toSorted(),
		(n.connect.caps ?? []).toSorted(),
		n.connect.client.id,
		n.connect.client.mode,
		t
	], (e, t) => t && typeof t === "object" && !Array.isArray(t) ? Object.fromEntries(Object.entries(t).sort(([e], [t]) => e.localeCompare(t))) : t);
}
const cronListShareKey = (e, t) => e.read?.shareable === true ? operatorReadShareKey(e, t) : null;
const modelsListShareKey = (e, t) => t.refresh === true ? null : operatorReadShareKey(e, t);
//#endregion
//#region src/gateway/methods/core-descriptors.ts
const CONTROL_PLANE_WRITE = { controlPlaneWrite: true };
const SIDECAR_CONTROL_PLANE_WRITE = {
	startup: true,
	controlPlaneWrite: true
};
const UNADVERTISED = { advertise: false };
const PROFILE_DEPENDENT = { profileAccess: "required" };
const PROFILE_STARTUP = {
	startup: true,
	...PROFILE_DEPENDENT
};
const SESSION_METADATA_READ = {
	shareKey: operatorReadShareKey,
	shareMaxAgeMs: 1e3,
	shareInvalidationEvents: ["sessions.changed", "chat.metadata.changed"]
};
const OBSERVATION = { lifetime: "observation" };
const UNADVERTISED_OBSERVATION = {
	...UNADVERTISED,
	...OBSERVATION
};
const SESSION_WRITE = { sessionAccess: { mode: "write" } };
const OWN_SESSION_WRITE = { sessionAccess: {
	mode: "write",
	allowOwnSessionScope: true
} };
const PORTAL_SESSION_WRITE = { sessionAccess: {
	mode: "write",
	allowOwnSessionScope: true,
	requiredTool: "portal"
} };
const CORE_GATEWAY_METHOD_SPECS = [
	[
		"health",
		"health",
		"operator.read",
		"<=2026.7"
	],
	[
		"diagnostics.stability",
		"diagnostics",
		"operator.read",
		"<=2026.7"
	],
	[
		"doctor.memory.status",
		"doctor",
		"operator.read",
		"<=2026.7"
	],
	[
		"doctor.memory.dreamDiary",
		"doctor",
		"operator.read",
		"<=2026.7"
	],
	[
		"doctor.memory.backfillDreamDiary",
		"doctor",
		"operator.write",
		"<=2026.7"
	],
	[
		"doctor.memory.resetDreamDiary",
		"doctor",
		"operator.write",
		"<=2026.7"
	],
	[
		"doctor.memory.resetGroundedShortTerm",
		"doctor",
		"operator.write",
		"<=2026.7"
	],
	[
		"doctor.memory.repairDreamingArtifacts",
		"doctor",
		"operator.write",
		"<=2026.7"
	],
	[
		"doctor.memory.dedupeDreamDiary",
		"doctor",
		"operator.write",
		"<=2026.7"
	],
	[
		"logs.tail",
		"logs",
		"operator.read",
		"<=2026.7"
	],
	[
		"channels.status",
		"channels",
		"operator.read",
		"<=2026.7"
	],
	[
		"channels.start",
		"channels",
		"operator.admin",
		"<=2026.7"
	],
	[
		"channels.stop",
		"channels",
		"operator.admin",
		"<=2026.7"
	],
	[
		"channels.logout",
		"channels",
		"operator.admin",
		"<=2026.7"
	],
	[
		"status",
		"health",
		"operator.read",
		"<=2026.7"
	],
	[
		"usage.status",
		"usage",
		"operator.read",
		"<=2026.7"
	],
	[
		"usage.cost",
		"usage",
		"operator.read",
		"<=2026.7"
	],
	[
		"tts.status",
		"tts",
		"operator.read",
		"<=2026.7"
	],
	[
		"tts.providers",
		"tts",
		"operator.read",
		"<=2026.7"
	],
	[
		"tts.personas",
		"tts",
		"operator.read",
		"<=2026.7"
	],
	[
		"tts.enable",
		"tts",
		"operator.write",
		"<=2026.7"
	],
	[
		"tts.disable",
		"tts",
		"operator.write",
		"<=2026.7"
	],
	[
		"tts.convert",
		"tts",
		"operator.write",
		"<=2026.7"
	],
	[
		"tts.setProvider",
		"tts",
		"operator.write",
		"<=2026.7"
	],
	[
		"tts.setPersona",
		"tts",
		"operator.write",
		"<=2026.7"
	],
	[
		"config.get",
		"config",
		"operator.read",
		"<=2026.7"
	],
	[
		"config.set",
		"config",
		"operator.admin",
		"<=2026.7"
	],
	[
		"config.apply",
		"config",
		"operator.admin",
		"<=2026.7",
		CONTROL_PLANE_WRITE
	],
	[
		"config.patch",
		"config",
		"operator.admin",
		"<=2026.7",
		CONTROL_PLANE_WRITE
	],
	[
		"config.schema",
		"config",
		"operator.read",
		"<=2026.7"
	],
	[
		"config.schema.lookup",
		"config",
		"operator.read",
		"<=2026.7"
	],
	[
		"exec.approvals.get",
		"exec-approvals",
		"operator.admin",
		"<=2026.7"
	],
	[
		"exec.approvals.set",
		"exec-approvals",
		"operator.admin",
		"<=2026.7"
	],
	[
		"exec.approvals.node.get",
		"exec-approvals",
		"operator.admin",
		"<=2026.7"
	],
	[
		"exec.approvals.node.set",
		"exec-approvals",
		"operator.admin",
		"<=2026.7"
	],
	[
		"exec.approval.get",
		null,
		"operator.approvals",
		"<=2026.7"
	],
	[
		"exec.approval.list",
		null,
		"operator.approvals",
		"<=2026.7"
	],
	[
		"exec.approval.request",
		null,
		"operator.approvals",
		"<=2026.7"
	],
	[
		"exec.approval.waitDecision",
		null,
		"operator.approvals",
		"<=2026.7",
		OBSERVATION
	],
	[
		"exec.approval.resolve",
		null,
		"operator.approvals",
		"<=2026.7"
	],
	[
		"exec.approval.grants.list",
		null,
		"operator.approvals",
		"2026.8"
	],
	[
		"exec.approval.grants.revoke",
		null,
		"operator.approvals",
		"2026.8"
	],
	[
		"question.request",
		null,
		"operator.questions",
		"2026.7"
	],
	[
		"question.waitAnswer",
		null,
		"operator.questions",
		"2026.7",
		OBSERVATION
	],
	[
		"question.resolve",
		null,
		"operator.questions",
		"2026.7"
	],
	[
		"question.get",
		null,
		"operator.questions",
		"2026.7"
	],
	[
		"question.list",
		null,
		"operator.questions",
		"2026.7"
	],
	[
		"plugin.approval.list",
		null,
		"operator.approvals",
		"<=2026.7"
	],
	[
		"plugin.approval.request",
		null,
		"operator.approvals",
		"<=2026.7"
	],
	[
		"plugin.approval.waitDecision",
		null,
		"operator.approvals",
		"<=2026.7",
		OBSERVATION
	],
	[
		"plugin.approval.resolve",
		null,
		"operator.approvals",
		"<=2026.7"
	],
	[
		"plugins.uiDescriptors",
		"plugin-host-hooks",
		"operator.read",
		"<=2026.7"
	],
	[
		"plugins.sessionAction",
		"plugin-host-hooks",
		"dynamic",
		"<=2026.7"
	],
	[
		"openclaw.chat",
		"system-agent",
		"operator.admin",
		"<=2026.7"
	],
	[
		"openclaw.chat.history",
		"system-agent",
		"operator.admin",
		"2026.7"
	],
	[
		"openclaw.changes.list",
		"system-changes",
		"operator.admin",
		"<=2026.7"
	],
	[
		"openclaw.approval.list",
		"system-agent-approvals",
		"operator.approvals",
		"<=2026.7"
	],
	[
		"openclaw.setup.detect",
		"system-agent",
		"operator.admin",
		"<=2026.7"
	],
	[
		"openclaw.setup.activate",
		"system-agent",
		"operator.admin",
		"<=2026.7"
	],
	[
		"openclaw.setup.activate.start",
		"system-agent",
		"operator.admin",
		"2026.8"
	],
	[
		"openclaw.setup.auth.start",
		"system-agent",
		"operator.admin",
		"<=2026.7"
	],
	[
		"openclaw.setup.prepare.start",
		"system-agent",
		"operator.admin",
		"<=2026.7"
	],
	[
		"wizard.start",
		"wizard",
		"operator.admin",
		"<=2026.7"
	],
	[
		"wizard.next",
		"wizard",
		"operator.admin",
		"<=2026.7"
	],
	[
		"wizard.cancel",
		"wizard",
		"operator.admin",
		"<=2026.7"
	],
	[
		"wizard.status",
		"wizard",
		"operator.admin",
		"<=2026.7"
	],
	[
		"talk.catalog",
		"talk",
		"operator.read",
		"<=2026.7"
	],
	[
		"talk.config",
		"talk",
		"dynamic",
		"<=2026.7",
		PROFILE_DEPENDENT
	],
	[
		"talk.client.create",
		"talk",
		"operator.talk",
		"<=2026.7"
	],
	[
		"talk.client.transcript",
		"talk",
		"operator.talk",
		"<=2026.7"
	],
	[
		"talk.client.close",
		"talk",
		"operator.talk",
		"<=2026.7"
	],
	[
		"talk.client.toolCall",
		"talk",
		"operator.talk",
		"<=2026.7"
	],
	[
		"talk.client.steer",
		"talk",
		"operator.talk",
		"<=2026.7"
	],
	[
		"talk.session.create",
		"talk",
		"operator.talk",
		"<=2026.7"
	],
	[
		"talk.session.appendAudio",
		"talk",
		"operator.talk",
		"<=2026.7"
	],
	[
		"talk.session.cancelOutput",
		"talk",
		"operator.talk",
		"<=2026.7"
	],
	[
		"talk.session.acknowledgeMark",
		"talk",
		"operator.talk",
		"<=2026.7"
	],
	[
		"talk.session.submitToolResult",
		"talk",
		"operator.talk",
		"<=2026.7"
	],
	[
		"talk.session.steer",
		"talk",
		"operator.talk",
		"<=2026.7"
	],
	[
		"talk.session.close",
		"talk",
		"operator.talk",
		"<=2026.7"
	],
	[
		"talk.speak",
		"talk",
		"operator.talk",
		"<=2026.7"
	],
	[
		"talk.mode",
		"talk-mode",
		"operator.talk",
		"<=2026.7"
	],
	[
		"commands.list",
		"commands",
		"operator.read",
		"<=2026.7"
	],
	[
		"models.list",
		"models",
		"operator.read",
		"<=2026.7",
		{
			...PROFILE_STARTUP,
			shareKey: modelsListShareKey,
			shareMaxAgeMs: 1e3,
			shareInvalidationEvents: ["chat.metadata.changed", "sessions.changed"]
		}
	],
	[
		"models.authStatus",
		"models-auth-status",
		"operator.read",
		"<=2026.7"
	],
	[
		"models.authLogout",
		"models-auth-status",
		"operator.admin",
		"<=2026.7",
		CONTROL_PLANE_WRITE
	],
	[
		"tools.catalog",
		"tools-catalog",
		"operator.read",
		"<=2026.7"
	],
	[
		"tools.effective",
		"tools-effective",
		"operator.read",
		"<=2026.7",
		{ startup: true }
	],
	[
		"tools.invoke",
		"tools-invoke",
		"operator.write",
		"<=2026.7"
	],
	[
		"mcp.app.view",
		"mcp-app",
		"operator.read",
		"<=2026.7"
	],
	[
		"mcp.app.listTools",
		"mcp-app",
		"operator.read",
		"<=2026.7"
	],
	[
		"mcp.app.listResources",
		"mcp-app",
		"operator.read",
		"<=2026.7"
	],
	[
		"mcp.app.listResourceTemplates",
		"mcp-app",
		"operator.read",
		"<=2026.7"
	],
	[
		"mcp.app.readResource",
		"mcp-app",
		"operator.read",
		"<=2026.7"
	],
	[
		"mcp.app.callTool",
		"mcp-app",
		"operator.write",
		"<=2026.7"
	],
	[
		"mcp.app.updateModelContext",
		"mcp-app",
		"operator.write",
		"<=2026.7"
	],
	[
		"board.get",
		"board",
		"operator.read",
		"<=2026.7"
	],
	[
		"board.update",
		"board",
		"operator.write",
		"<=2026.7"
	],
	[
		"board.widget.put",
		"board",
		"operator.write",
		"<=2026.7"
	],
	[
		"board.widget.grant",
		"board",
		"operator.approvals",
		"<=2026.7"
	],
	[
		"board.widget.appView",
		"board",
		"operator.read",
		"2026.7"
	],
	[
		"board.event",
		"board",
		"operator.write",
		"<=2026.7"
	],
	[
		"audit.list",
		"audit",
		"operator.read",
		"2026.7"
	],
	[
		"audit.activity.list",
		"audit",
		"operator.read",
		"2026.7"
	],
	[
		"users.list",
		"users",
		"operator.read",
		"<=2026.7"
	],
	[
		"users.self",
		"users",
		"operator.read",
		"<=2026.7",
		PROFILE_DEPENDENT
	],
	[
		"users.linkEmail",
		"users",
		"operator.admin",
		"<=2026.7",
		PROFILE_DEPENDENT
	],
	[
		"users.setDisplayName",
		"users",
		"operator.read",
		"<=2026.7",
		PROFILE_DEPENDENT
	],
	[
		"users.setAvatar",
		"users",
		"operator.read",
		"<=2026.7",
		PROFILE_DEPENDENT
	],
	[
		"users.setRole",
		"users",
		"operator.admin",
		"2026.8",
		PROFILE_DEPENDENT
	],
	[
		"users.listAuthLinks",
		"users",
		"operator.read",
		"2026.8",
		PROFILE_DEPENDENT
	],
	[
		"users.listModelAccounts",
		"users",
		"operator.read",
		"2026.8",
		PROFILE_DEPENDENT
	],
	[
		"users.selectModelAccount",
		"users",
		"operator.write",
		"2026.8",
		PROFILE_DEPENDENT
	],
	[
		"users.linkAuthProfile",
		"users",
		"operator.admin",
		"2026.8",
		PROFILE_DEPENDENT
	],
	[
		"users.unlinkAuthProfile",
		"users",
		"operator.write",
		"2026.8",
		PROFILE_DEPENDENT
	],
	[
		"users.authConnect.start",
		"users",
		"operator.write",
		"2026.8"
	],
	[
		"users.authConnect.answer",
		"users",
		"operator.write",
		"2026.8"
	],
	[
		"users.authConnect.status",
		"users",
		"operator.write",
		"2026.8"
	],
	[
		"users.authConnect.cancel",
		"users",
		"operator.write",
		"2026.8"
	],
	[
		"users.authConnect.catalog",
		"users",
		"operator.write",
		"2026.8"
	],
	[
		"taskSuggestions.list",
		"task-suggestions",
		"operator.read",
		"<=2026.7"
	],
	[
		"taskSuggestions.create",
		"task-suggestions",
		"operator.write",
		"<=2026.7"
	],
	[
		"taskSuggestions.accept",
		"task-suggestions",
		"operator.admin",
		"<=2026.7"
	],
	[
		"taskSuggestions.dismiss",
		"task-suggestions",
		"operator.write",
		"<=2026.7"
	],
	[
		"environments.list",
		"environments",
		"dynamic",
		"2026.7"
	],
	[
		"environments.status",
		"environments",
		"operator.read",
		"2026.7"
	],
	[
		"worktrees.list",
		"worktrees",
		"operator.write",
		"2026.7"
	],
	[
		"worktrees.branches",
		"worktrees",
		"operator.write",
		"2026.7"
	],
	[
		"fs.listDir",
		"fs",
		"dynamic",
		"<=2026.7"
	],
	[
		"worktrees.create",
		"worktrees",
		"operator.write",
		"2026.7",
		CONTROL_PLANE_WRITE
	],
	[
		"worktrees.remove",
		"worktrees",
		"operator.admin",
		"2026.7",
		CONTROL_PLANE_WRITE
	],
	[
		"worktrees.restore",
		"worktrees",
		"operator.admin",
		"2026.7",
		CONTROL_PLANE_WRITE
	],
	[
		"worktrees.gc",
		"worktrees",
		"operator.admin",
		"2026.7",
		CONTROL_PLANE_WRITE
	],
	[
		"agents.list",
		"agents",
		"operator.read",
		"<=2026.7"
	],
	[
		"agents.create",
		"agents",
		"operator.admin",
		"<=2026.7"
	],
	[
		"agents.update",
		"agents",
		"operator.admin",
		"<=2026.7"
	],
	[
		"agents.delete",
		"agents",
		"operator.admin",
		"<=2026.7"
	],
	[
		"agents.files.list",
		"agents",
		"operator.read",
		"<=2026.7"
	],
	[
		"agents.files.get",
		"agents",
		"operator.read",
		"<=2026.7"
	],
	[
		"agents.files.set",
		"agents",
		"operator.admin",
		"<=2026.7"
	],
	[
		"sessions.files.list",
		"sessions-files",
		"operator.read",
		"<=2026.7"
	],
	[
		"sessions.files.get",
		"sessions-files",
		"operator.read",
		"<=2026.7"
	],
	[
		"sessions.files.download",
		"sessions-files",
		"operator.read",
		"2026.10"
	],
	[
		"sessions.files.set",
		"sessions-files",
		"operator.admin",
		"<=2026.7"
	],
	[
		"sessions.files.reveal",
		"sessions-files",
		"operator.admin",
		"<=2026.7"
	],
	[
		"artifacts.list",
		"artifacts",
		"operator.read",
		"<=2026.7"
	],
	[
		"artifacts.get",
		"artifacts",
		"operator.read",
		"<=2026.7"
	],
	[
		"artifacts.download",
		"artifacts",
		"operator.read",
		"<=2026.7"
	],
	[
		"skills.status",
		"skills",
		"operator.read",
		"<=2026.7"
	],
	[
		"skills.library.list",
		"skills",
		"operator.read",
		"2026.8"
	],
	[
		"skills.library.read",
		"skills",
		"operator.read",
		"2026.8"
	],
	[
		"skills.library.save",
		"skills",
		"operator.write",
		"2026.8"
	],
	[
		"skills.library.mutate",
		"skills",
		"operator.write",
		"2026.8"
	],
	[
		"skills.library.activate",
		"skills",
		"operator.write",
		"2026.8"
	],
	[
		"skills.library.import",
		"skills",
		"operator.write",
		"2026.8"
	],
	[
		"skills.library.upload",
		"skills",
		"operator.write",
		"2026.8"
	],
	[
		"skills.search",
		"skills",
		"operator.read",
		"<=2026.7"
	],
	[
		"skills.detail",
		"skills",
		"operator.read",
		"<=2026.7"
	],
	[
		"skills.securityVerdicts",
		"skills",
		"operator.read",
		"<=2026.7"
	],
	[
		"skills.skillCard",
		"skills",
		"operator.read",
		"<=2026.7"
	],
	[
		"skills.bins",
		"skills",
		"node",
		"<=2026.7"
	],
	[
		"skills.upload.begin",
		"skills",
		"operator.admin",
		"<=2026.7"
	],
	[
		"skills.upload.chunk",
		"skills",
		"operator.admin",
		"<=2026.7"
	],
	[
		"skills.upload.commit",
		"skills",
		"operator.admin",
		"<=2026.7"
	],
	[
		"skills.install",
		"skills",
		"operator.admin",
		"<=2026.7"
	],
	[
		"skills.update",
		"skills",
		"operator.admin",
		"<=2026.7"
	],
	[
		"skills.curator.status",
		"skills",
		"operator.read",
		"<=2026.7"
	],
	[
		"skills.curator.pin",
		"skills",
		"operator.admin",
		"<=2026.7"
	],
	[
		"skills.curator.unpin",
		"skills",
		"operator.admin",
		"<=2026.7"
	],
	[
		"skills.curator.restore",
		"skills",
		"operator.admin",
		"<=2026.7"
	],
	[
		"skills.proposals.list",
		"skills",
		"operator.read",
		"<=2026.7"
	],
	[
		"skills.proposals.inspect",
		"skills",
		"operator.read",
		"<=2026.7"
	],
	[
		"skills.proposals.historyStatus",
		"skills",
		"operator.read",
		"<=2026.7"
	],
	[
		"skills.proposals.historyScan",
		"skills",
		"operator.admin",
		"<=2026.7"
	],
	[
		"skills.proposals.create",
		"skills",
		"operator.admin",
		"<=2026.7"
	],
	[
		"skills.proposals.update",
		"skills",
		"operator.admin",
		"<=2026.7"
	],
	[
		"skills.proposals.revise",
		"skills",
		"operator.admin",
		"<=2026.7"
	],
	[
		"skills.proposals.requestRevision",
		"skills",
		"operator.admin",
		"<=2026.7"
	],
	[
		"skills.proposals.apply",
		"skills",
		"operator.admin",
		"<=2026.7"
	],
	[
		"skills.proposals.reject",
		"skills",
		"operator.admin",
		"<=2026.7"
	],
	[
		"skills.proposals.quarantine",
		"skills",
		"operator.admin",
		"<=2026.7"
	],
	[
		"update.status",
		"update",
		"operator.admin",
		"<=2026.7"
	],
	[
		"update.run",
		"update",
		"operator.admin",
		"<=2026.7",
		CONTROL_PLANE_WRITE
	],
	[
		"voicewake.get",
		"voicewake",
		"operator.read",
		"<=2026.7"
	],
	[
		"voicewake.set",
		"voicewake",
		"operator.write",
		"<=2026.7"
	],
	[
		"secrets.reload",
		null,
		"operator.admin",
		"<=2026.7"
	],
	[
		"secrets.resolve",
		null,
		"operator.admin",
		"<=2026.7"
	],
	[
		"voicewake.routing.get",
		"voicewake-routing",
		"operator.read",
		"<=2026.7"
	],
	[
		"sessions.list",
		"sessions-read",
		"operator.read",
		"<=2026.7",
		SESSION_METADATA_READ
	],
	[
		"sessions.subscribe",
		"sessions-subscriptions",
		"operator.read",
		"<=2026.7"
	],
	[
		"sessions.messages.subscribe",
		"sessions-subscriptions",
		"operator.read",
		"<=2026.7"
	],
	[
		"sessions.messages.unsubscribe",
		"sessions-subscriptions",
		"operator.read",
		"<=2026.7"
	],
	[
		"sessions.viewers.set",
		"sessions-subscriptions",
		"operator.read",
		"2026.7"
	],
	[
		"sessions.preview",
		"sessions-read",
		"operator.read",
		"<=2026.7"
	],
	[
		"sessions.describe",
		"sessions-read",
		"operator.read",
		"<=2026.7",
		{ lifetime: "observation" }
	],
	[
		"sessions.branches.list",
		"sessions-rewind",
		"operator.read",
		"<=2026.7",
		OBSERVATION
	],
	[
		"sessions.branches.switch",
		"sessions-rewind",
		"operator.admin",
		"<=2026.7"
	],
	[
		"sessions.rewind",
		"sessions-rewind",
		"operator.admin",
		"<=2026.7"
	],
	[
		"sessions.fork",
		"sessions-rewind",
		"operator.write",
		"<=2026.7"
	],
	[
		"sessions.create",
		"sessions-create",
		"dynamic",
		"<=2026.7",
		{ startup: true }
	],
	[
		"sessions.send",
		"sessions-messaging",
		"operator.write",
		"<=2026.7",
		{ startup: true }
	],
	[
		"sessions.abort",
		"sessions-abort",
		"operator.write",
		"<=2026.7",
		{ startup: true }
	],
	[
		"sessions.patch",
		"sessions-mutations",
		"dynamic",
		"<=2026.7"
	],
	[
		"sessions.goal.update",
		"sessions-goal",
		"operator.write",
		"2026.8"
	],
	[
		"sessions.goal.clear",
		"sessions-goal",
		"operator.write",
		"2026.8"
	],
	[
		"sessions.pluginPatch",
		"sessions-mutations",
		"operator.admin",
		"<=2026.7"
	],
	[
		"sessions.cleanup",
		"sessions-read",
		"operator.admin",
		"<=2026.7"
	],
	[
		"sessions.reset",
		"sessions-mutations",
		"operator.admin",
		"<=2026.7"
	],
	[
		"sessions.delete",
		"sessions-delete",
		"dynamic",
		"<=2026.7"
	],
	[
		"sessions.compact",
		"sessions-compact",
		"operator.admin",
		"<=2026.7"
	],
	[
		"sessions.groups.list",
		"sessions-groups",
		"operator.read",
		"<=2026.7"
	],
	[
		"sessions.groups.defaults",
		"sessions-groups",
		"operator.write",
		"2026.8"
	],
	[
		"sessions.groups.put",
		"sessions-groups",
		"operator.write",
		"<=2026.7"
	],
	[
		"sessions.groups.rename",
		"sessions-groups",
		"operator.write",
		"<=2026.7"
	],
	[
		"sessions.groups.update",
		"sessions-groups",
		"operator.write",
		"2026.8"
	],
	[
		"sessions.groups.delete",
		"sessions-groups",
		"operator.write",
		"<=2026.7"
	],
	[
		"last-heartbeat",
		"system",
		"operator.read",
		"<=2026.7"
	],
	[
		"set-heartbeats",
		"system",
		"operator.admin",
		"<=2026.7"
	],
	[
		"wake",
		"cron",
		"operator.write",
		"<=2026.7"
	],
	[
		"node.pair.list",
		"nodes",
		"operator.pairing",
		"<=2026.7"
	],
	[
		"node.pair.approve",
		"nodes",
		"operator.pairing",
		"<=2026.7"
	],
	[
		"node.pair.reject",
		"nodes",
		"operator.pairing",
		"<=2026.7"
	],
	[
		"node.pair.remove",
		"nodes",
		"operator.pairing",
		"<=2026.7"
	],
	[
		"device.pair.list",
		"devices",
		"operator.pairing",
		"<=2026.7"
	],
	[
		"device.pair.approve",
		"devices",
		"operator.pairing",
		"<=2026.7"
	],
	[
		"device.pair.reject",
		"devices",
		"operator.pairing",
		"<=2026.7"
	],
	[
		"device.pair.remove",
		"devices",
		"operator.pairing",
		"<=2026.7"
	],
	[
		"device.pair.rename",
		"devices",
		"operator.pairing",
		"2026.7"
	],
	[
		"device.token.rotate",
		"devices",
		"operator.pairing",
		"<=2026.7"
	],
	[
		"device.token.revoke",
		"devices",
		"operator.pairing",
		"<=2026.7"
	],
	[
		"device.pair.setupCode",
		"device-pair-setup",
		"operator.admin",
		"<=2026.7",
		UNADVERTISED
	],
	[
		"device.pair.setupStatus",
		"device-pair-setup",
		"operator.admin",
		"2026.8",
		UNADVERTISED
	],
	[
		"node.rename",
		"nodes",
		"operator.pairing",
		"<=2026.7"
	],
	[
		"node.list",
		"nodes",
		"operator.read",
		"<=2026.7"
	],
	[
		"node.describe",
		"nodes",
		"operator.read",
		"<=2026.7"
	],
	[
		"node.pluginSurface.refresh",
		"nodes",
		"node",
		"<=2026.7"
	],
	[
		"node.pluginTools.update",
		"nodes",
		"node",
		"<=2026.7"
	],
	[
		"node.skills.update",
		"nodes",
		"node",
		"<=2026.7"
	],
	[
		"node.runnerInventory.update",
		"nodes",
		"node",
		"2026.8",
		UNADVERTISED
	],
	[
		"node.pending.drain",
		"nodes-pending",
		"node",
		"<=2026.7"
	],
	[
		"node.pending.enqueue",
		"nodes-pending",
		"operator.write",
		"<=2026.7"
	],
	[
		"node.invoke",
		"nodes",
		"dynamic",
		"<=2026.7"
	],
	[
		"node.pending.pull",
		"nodes",
		"node",
		"<=2026.7"
	],
	[
		"node.pending.ack",
		"nodes",
		"node",
		"<=2026.7"
	],
	[
		"node.invoke.progress",
		"nodes",
		"node",
		"<=2026.7"
	],
	[
		"node.invoke.result",
		"nodes",
		"node",
		"<=2026.7"
	],
	[
		"node.event",
		"nodes",
		"node",
		"<=2026.7"
	],
	[
		"cron.get",
		"cron",
		"operator.read",
		"<=2026.7"
	],
	[
		"cron.list",
		"cron",
		"operator.read",
		"<=2026.7",
		{
			shareKey: cronListShareKey,
			shareMaxAgeMs: 1e3,
			shareInvalidationEvents: ["cron", "sessions.changed"]
		}
	],
	[
		"cron.status",
		"cron",
		"operator.read",
		"<=2026.7",
		{
			shareKey: operatorReadShareKey,
			shareMaxAgeMs: 1e3,
			shareInvalidationEvents: ["cron"]
		}
	],
	[
		"cron.scratch.get",
		"cron",
		"operator.admin",
		"2026.7"
	],
	[
		"cron.scratch.set",
		"cron",
		"operator.admin",
		"2026.7"
	],
	[
		"cron.add",
		"cron",
		"operator.admin",
		"<=2026.7",
		CONTROL_PLANE_WRITE
	],
	[
		"cron.update",
		"cron",
		"operator.admin",
		"<=2026.7",
		CONTROL_PLANE_WRITE
	],
	[
		"cron.remove",
		"cron",
		"operator.admin",
		"<=2026.7",
		CONTROL_PLANE_WRITE
	],
	[
		"cron.run",
		"cron",
		"operator.admin",
		"<=2026.7",
		CONTROL_PLANE_WRITE
	],
	[
		"cron.runs",
		"cron",
		"operator.read",
		"<=2026.7"
	],
	[
		"gateway.identity.get",
		"system",
		"operator.read",
		"<=2026.7"
	],
	[
		"gateway.restart.preflight",
		"restart",
		"operator.read",
		"<=2026.7",
		{ compatibilityRestored: true }
	],
	[
		"gateway.restart.request",
		"restart",
		"operator.admin",
		"<=2026.7",
		CONTROL_PLANE_WRITE
	],
	[
		"system-presence",
		"system",
		"operator.read",
		"<=2026.7"
	],
	[
		"system-event",
		"system",
		"operator.admin",
		"<=2026.7"
	],
	[
		"message.action",
		"send",
		"operator.write",
		"<=2026.7"
	],
	[
		"conversations.send",
		"conversations",
		"operator.admin",
		"<=2026.7"
	],
	[
		"conversations.turn",
		"conversations",
		"operator.admin",
		"<=2026.7"
	],
	[
		"conversations.turn.cancel",
		"conversations",
		"operator.admin",
		"<=2026.7"
	],
	[
		"send",
		"send",
		"operator.write",
		"<=2026.7"
	],
	[
		"agent",
		"agent",
		"dynamic",
		"<=2026.7",
		{ startup: true }
	],
	[
		"agent.identity.get",
		"agent-identity",
		"operator.read",
		"<=2026.7"
	],
	[
		"agent.wait",
		"agent",
		"operator.write",
		"<=2026.7",
		{
			...PROFILE_STARTUP,
			...OBSERVATION
		}
	],
	[
		"chat.history",
		"chat",
		"operator.read",
		"<=2026.7"
	],
	[
		"chat.startup",
		"chat",
		"operator.read",
		"<=2026.7"
	],
	[
		"chat.metadata",
		"chat",
		"operator.read",
		"<=2026.7",
		SESSION_METADATA_READ
	],
	[
		"chat.message.get",
		"chat",
		"operator.read",
		"<=2026.7"
	],
	[
		"chat.abort",
		"chat-abort",
		"operator.write",
		"<=2026.7"
	],
	[
		"chat.send",
		"chat-send",
		"operator.write",
		"<=2026.7",
		{ startup: true }
	],
	[
		"terminal.open",
		"terminal",
		"operator.admin",
		"2026.7"
	],
	[
		"terminal.input",
		"terminal",
		"operator.admin",
		"2026.7"
	],
	[
		"terminal.resize",
		"terminal",
		"operator.admin",
		"2026.7"
	],
	[
		"terminal.close",
		"terminal",
		"operator.admin",
		"2026.7"
	],
	[
		"channels.pairing.list",
		"channel-pairing",
		"operator.pairing",
		"2026.7"
	],
	[
		"channels.pairing.approve",
		"channel-pairing",
		"dynamic",
		"2026.7"
	],
	[
		"channels.pairing.dismiss",
		"channel-pairing",
		"operator.pairing",
		"2026.7"
	],
	[
		"assistant.media.get",
		null,
		"operator.read",
		"<=2026.7",
		UNADVERTISED
	],
	[
		"sessions.get",
		"sessions-read",
		"operator.read",
		"<=2026.7",
		UNADVERTISED_OBSERVATION
	],
	[
		"sessions.resolve",
		"sessions-read",
		"operator.read",
		"<=2026.7",
		UNADVERTISED
	],
	[
		"sessions.usage",
		"usage",
		"operator.read",
		"<=2026.7",
		UNADVERTISED
	],
	[
		"sessions.usage.timeseries",
		"usage",
		"operator.read",
		"<=2026.7",
		UNADVERTISED
	],
	[
		"sessions.usage.logs",
		"usage",
		"operator.read",
		"<=2026.7",
		UNADVERTISED
	],
	[
		"poll",
		"send",
		"operator.write",
		"<=2026.7",
		UNADVERTISED
	],
	[
		"sessions.steer",
		"sessions-messaging",
		"operator.write",
		"<=2026.7",
		{
			advertise: false,
			description: "Deprecated alias for chat.send queueMode interrupt; removal per protocol deprecation policy."
		}
	],
	[
		"push.test",
		"push",
		"operator.write",
		"<=2026.7",
		UNADVERTISED
	],
	[
		"attach.grant",
		"attach",
		"operator.admin",
		"<=2026.7",
		CONTROL_PLANE_WRITE
	],
	[
		"attach.revoke",
		"attach",
		"operator.admin",
		"<=2026.7"
	],
	[
		"push.web.vapidPublicKey",
		"push",
		"operator.write",
		"<=2026.7",
		UNADVERTISED
	],
	[
		"push.web.subscribe",
		"push",
		"operator.write",
		"<=2026.7",
		UNADVERTISED
	],
	[
		"push.web.unsubscribe",
		"push",
		"operator.write",
		"<=2026.7",
		UNADVERTISED
	],
	[
		"push.web.test",
		"push",
		"operator.write",
		"<=2026.7",
		UNADVERTISED
	],
	[
		"push.web.preferences.get",
		"push",
		"operator.read",
		"2026.8"
	],
	[
		"push.web.preferences.set",
		"push",
		"operator.write",
		"2026.8"
	],
	[
		"config.openFile",
		"config",
		"operator.admin",
		"<=2026.7",
		UNADVERTISED
	],
	[
		"connect",
		"connect",
		"operator.admin",
		"<=2026.7",
		UNADVERTISED
	],
	[
		"chat.inject",
		"chat",
		"operator.admin",
		"<=2026.7",
		UNADVERTISED
	],
	[
		"nativeHook.invoke",
		"native-hook-relay",
		"operator.admin",
		"<=2026.7",
		UNADVERTISED
	],
	[
		"web.login.start",
		"web",
		"operator.admin",
		"<=2026.7",
		UNADVERTISED
	],
	[
		"web.login.wait",
		"web",
		"operator.admin",
		"<=2026.7",
		UNADVERTISED
	],
	[
		"terminal.attach",
		"terminal",
		"operator.admin",
		"2026.7"
	],
	[
		"terminal.list",
		"terminal",
		"operator.admin",
		"2026.7"
	],
	[
		"controlUi.githubPreview",
		"control-ui",
		"operator.read",
		"<=2026.7"
	],
	[
		"system.info",
		"system",
		"operator.read",
		"<=2026.7"
	],
	[
		"agents.workspace.list",
		"agents-workspace",
		"operator.read",
		"2026.7"
	],
	[
		"agents.workspace.get",
		"agents-workspace",
		"operator.read",
		"2026.7"
	],
	[
		"tts.speak",
		"tts",
		"operator.write",
		"2026.7"
	],
	[
		"plugins.list",
		"plugins",
		"operator.read",
		"<=2026.7"
	],
	[
		"plugins.search",
		"plugins",
		"operator.read",
		"<=2026.7"
	],
	[
		"plugins.install",
		"plugins-mutations",
		"operator.admin",
		"<=2026.7",
		CONTROL_PLANE_WRITE
	],
	[
		"plugins.setEnabled",
		"plugins-mutations",
		"operator.admin",
		"<=2026.7",
		CONTROL_PLANE_WRITE
	],
	[
		"plugins.uninstall",
		"plugins-mutations",
		"operator.admin",
		"<=2026.7",
		CONTROL_PLANE_WRITE
	],
	[
		"plugins.refresh",
		"plugins-mutations",
		"operator.admin",
		"<=2026.7",
		CONTROL_PLANE_WRITE
	],
	[
		"controlUi.sessionPullRequests.subscribe",
		"control-ui",
		"operator.read",
		"2026.7"
	],
	[
		"controlUi.sessionPreview",
		"control-ui",
		"operator.read",
		"2026.8"
	],
	[
		"gateway.suspend.prepare",
		"suspend",
		"operator.admin",
		"2026.7",
		SIDECAR_CONTROL_PLANE_WRITE
	],
	[
		"gateway.suspend.status",
		"suspend",
		"operator.read",
		"2026.7"
	],
	[
		"gateway.suspend.resume",
		"suspend",
		"operator.admin",
		"2026.7"
	],
	[
		"chat.toolTitles",
		"chat",
		"operator.write",
		"<=2026.7"
	],
	[
		"sessions.diff",
		"sessions-diff",
		"operator.read",
		"<=2026.7"
	],
	[
		"openclaw.setup.verify",
		"system-agent",
		"operator.admin",
		"<=2026.7"
	],
	[
		"environments.create",
		"environments",
		"operator.admin",
		"2026.7",
		SIDECAR_CONTROL_PLANE_WRITE
	],
	[
		"environments.destroy",
		"environments",
		"operator.admin",
		"2026.7",
		SIDECAR_CONTROL_PLANE_WRITE
	],
	[
		"sessions.catalog.list",
		"session-catalog",
		"operator.read",
		"2026.7"
	],
	[
		"sessions.catalog.read",
		"session-catalog",
		"operator.read",
		"2026.7"
	],
	[
		"terminal.upload",
		"terminal",
		"operator.admin",
		"2026.7"
	],
	[
		"sessions.catalog.continue",
		"session-catalog",
		"operator.write",
		"2026.7"
	],
	[
		"sessions.catalog.archive",
		"session-catalog",
		"operator.write",
		"2026.7"
	],
	[
		"approval.get",
		null,
		"operator.approvals",
		"2026.7"
	],
	[
		"approval.resolve",
		null,
		"operator.approvals",
		"2026.7"
	],
	[
		"sessions.search",
		"sessions-read",
		"operator.read",
		"<=2026.7"
	],
	[
		"sessions.dispatch",
		"sessions-dispatch",
		"dynamic",
		"2026.7",
		SIDECAR_CONTROL_PLANE_WRITE
	],
	[
		"sessions.reclaim",
		"sessions-dispatch",
		"operator.write",
		"2026.7",
		SIDECAR_CONTROL_PLANE_WRITE
	],
	[
		"models.probe",
		"models-probe",
		"operator.admin",
		"<=2026.7"
	],
	[
		"migrations.memory.plan",
		"migrations",
		"operator.admin",
		"2026.7"
	],
	[
		"migrations.memory.apply",
		"migrations",
		"operator.admin",
		"2026.7",
		CONTROL_PLANE_WRITE
	],
	[
		"ui.command",
		"ui-command",
		"operator.write",
		"2026.7",
		PROFILE_DEPENDENT
	],
	[
		"approval.history",
		null,
		"operator.approvals",
		"2026.7"
	],
	[
		"plugin.surface.refresh",
		"nodes",
		"operator.read",
		"<=2026.7"
	],
	[
		"conversations.list",
		"conversations",
		"operator.admin",
		"<=2026.7"
	],
	[
		"session.discussion.info",
		"session-discussion",
		"operator.read",
		"2026.7"
	],
	[
		"session.discussion.open",
		"session-discussion",
		"operator.write",
		"2026.7"
	],
	[
		"board.prompt.authorize",
		"board",
		"operator.read",
		"2026.7"
	],
	[
		"board.data.read",
		"board",
		"operator.read",
		"2026.7"
	],
	[
		"board.action",
		"board",
		"operator.write",
		"2026.7"
	],
	[
		"sessions.observer.visibility",
		"session-observer-rpc",
		"operator.read",
		"2026.7"
	],
	[
		"session.visibility.set",
		"sessions-sharing",
		"operator.write",
		"2026.7"
	],
	[
		"session.members.list",
		"sessions-sharing",
		"operator.read",
		"2026.7"
	],
	[
		"session.members.add",
		"sessions-sharing",
		"operator.write",
		"2026.7"
	],
	[
		"session.members.remove",
		"sessions-sharing",
		"operator.write",
		"2026.7"
	],
	[
		"session.suggestions.add",
		"sessions-suggestions",
		"operator.write",
		"2026.7"
	],
	[
		"session.suggestions.list",
		"sessions-suggestions",
		"operator.read",
		"2026.7"
	],
	[
		"session.suggestions.resolve",
		"sessions-suggestions",
		"operator.write",
		"2026.7"
	],
	[
		"session.reactions.set",
		"sessions-reactions",
		"operator.write",
		"2026.9"
	],
	[
		"session.reactions.list",
		"sessions-reactions",
		"operator.read",
		"2026.9"
	],
	[
		"session.typing",
		"sessions-suggestions",
		"operator.write",
		"2026.7"
	],
	[
		"sessions.companion.ask",
		"session-companion-rpc",
		"operator.read",
		"2026.7"
	],
	[
		"sessions.companion.state",
		"session-companion-rpc",
		"operator.read",
		"2026.7"
	],
	[
		"sessions.companion.reset",
		"session-companion-rpc",
		"operator.write",
		"2026.7",
		CONTROL_PLANE_WRITE
	],
	[
		"memory.search",
		"memory-search",
		"operator.read",
		"2026.7"
	],
	[
		"skills.proposals.events.list",
		"skills",
		"operator.read",
		"2026.7"
	],
	[
		"skills.proposals.evaluate",
		"skills",
		"operator.admin",
		"2026.7",
		CONTROL_PLANE_WRITE
	],
	[
		"hooks.status",
		"hooks-status",
		"operator.read",
		"2026.7"
	],
	[
		"audit.run.inspect",
		"audit",
		"operator.read",
		"2026.7"
	],
	[
		"sessions.patchMany",
		"sessions-mutations",
		"dynamic",
		"2026.8"
	],
	[
		"update.hold",
		"update",
		"operator.admin",
		"2026.8",
		CONTROL_PLANE_WRITE
	],
	[
		"sessions.catalog.startTerminal",
		"session-catalog",
		"operator.admin",
		"2026.8"
	],
	[
		"worker.desktop.observe",
		"environments",
		"operator.admin",
		"2026.8",
		{ startup: true }
	],
	[
		"projects.list",
		"projects",
		"operator.read",
		"2026.8"
	],
	[
		"projects.register",
		"projects",
		"operator.admin",
		"2026.8"
	],
	[
		"projects.remove",
		"projects",
		"operator.admin",
		"2026.8"
	],
	[
		"worker.desktop.launch",
		"environments",
		"operator.admin",
		"2026.8",
		{ startup: true }
	],
	[
		"secrets.store.list",
		null,
		"operator.admin",
		"2026.8"
	],
	[
		"secrets.store.set",
		null,
		"operator.admin",
		"2026.8",
		CONTROL_PLANE_WRITE
	],
	[
		"secrets.store.delete",
		null,
		"operator.admin",
		"2026.8",
		CONTROL_PLANE_WRITE
	],
	[
		"users.prefs.get",
		"users",
		"operator.read",
		"2026.8"
	],
	[
		"users.prefs.set",
		"users",
		"operator.read",
		"2026.8"
	],
	[
		"projects.add",
		"projects",
		"operator.write",
		"2026.8",
		CONTROL_PLANE_WRITE
	],
	[
		"projects.searchRemote",
		"projects",
		"operator.write",
		"2026.8",
		{ description: "Search GitHub repositories that can be cloned as managed projects." }
	],
	[
		"desktop.observe",
		"environments",
		"operator.admin",
		"2026.8",
		{ startup: true }
	],
	[
		"desktop.launch",
		"environments",
		"operator.admin",
		"2026.8",
		{ startup: true }
	],
	[
		"device.scopes.requestUpgrade",
		"devices",
		"operator.read",
		"2026.8"
	],
	[
		"device.scopes.waitUpgrade",
		"devices",
		"operator.read",
		"2026.8",
		OBSERVATION
	],
	[
		"portal.list",
		"portals",
		"operator.read",
		"2026.8"
	],
	[
		"portal.open",
		"portals",
		"operator.write",
		"2026.8",
		CONTROL_PLANE_WRITE
	],
	[
		"portal.close",
		"portals",
		"operator.write",
		"2026.8",
		CONTROL_PLANE_WRITE
	],
	[
		"sessions.move",
		"sessions-dispatch",
		"dynamic",
		"2026.8",
		SIDECAR_CONTROL_PLANE_WRITE
	],
	[
		"sessions.assignOwner",
		"sessions-mutations",
		"operator.write",
		"2026.8"
	],
	[
		"progressCard.get",
		"progress-card",
		"operator.read",
		"2026.8"
	],
	[
		"progressCard.put",
		"progress-card",
		"operator.write",
		"2026.8"
	],
	[
		"tools.github.status",
		"tools-github",
		"operator.read",
		"2026.8"
	],
	[
		"tools.github.configure",
		"tools-github",
		"operator.admin",
		"2026.8",
		CONTROL_PLANE_WRITE
	],
	[
		"tools.github.authorize.start",
		"tools-github",
		"operator.admin",
		"2026.8",
		CONTROL_PLANE_WRITE
	],
	[
		"tools.github.authorize.poll",
		"tools-github",
		"operator.admin",
		"2026.8",
		CONTROL_PLANE_WRITE
	],
	[
		"tools.github.authorize.cancel",
		"tools-github",
		"operator.admin",
		"2026.8",
		CONTROL_PLANE_WRITE
	],
	[
		"sessions.github.publish",
		"sessions-github",
		"operator.sessions.write",
		"2026.8",
		CONTROL_PLANE_WRITE
	],
	[
		"factory.githubPublication.redeem",
		"factory-github-proof",
		"operator.admin",
		"2026.10",
		{ advertise: false }
	],
	[
		"diagnostics.lanes",
		"diagnostics",
		"operator.read",
		"2026.8"
	],
	[
		"session.members.listEvidence",
		"sessions-sharing",
		"operator.read",
		"2026.8"
	],
	[
		"plugins.inspect",
		"plugins",
		"operator.read",
		"2026.8"
	],
	[
		"users.github.status",
		"users",
		"operator.read",
		"2026.8",
		{ startup: true }
	],
	[
		"users.github.authorize.start",
		"users",
		"operator.read",
		"2026.8",
		SIDECAR_CONTROL_PLANE_WRITE
	],
	[
		"users.github.authorize.poll",
		"users",
		"operator.read",
		"2026.8",
		SIDECAR_CONTROL_PLANE_WRITE
	],
	[
		"users.github.authorize.cancel",
		"users",
		"operator.read",
		"2026.8",
		SIDECAR_CONTROL_PLANE_WRITE
	],
	[
		"users.github.disconnect",
		"users",
		"operator.read",
		"2026.8",
		SIDECAR_CONTROL_PLANE_WRITE
	],
	[
		"sessions.github.options",
		"sessions-github",
		"operator.read",
		"2026.8",
		{ startup: true }
	],
	[
		"sessions.github.status",
		"sessions-github",
		"operator.read",
		"2026.8",
		{ startup: true }
	],
	[
		"sessions.github.confirm",
		"sessions-github",
		"operator.write",
		"2026.8",
		SIDECAR_CONTROL_PLANE_WRITE
	],
	[
		"sessions.title.prepare",
		"sessions-title",
		"operator.write",
		"2026.8",
		CONTROL_PLANE_WRITE
	],
	[
		"users.mentionable",
		"users-mentionable",
		"operator.read",
		"2026.8",
		PROFILE_STARTUP
	],
	[
		"mentions.list",
		"mentions",
		"operator.read",
		"2026.8",
		{ startup: true }
	],
	[
		"mentions.dismiss",
		"mentions",
		"operator.read",
		"2026.8",
		{ startup: true }
	],
	[
		"transcripts.list",
		"transcripts",
		"operator.read",
		"2026.8"
	],
	[
		"transcripts.get",
		"transcripts",
		"operator.read",
		"2026.8"
	],
	[
		"models.authOrderSet",
		"models-auth-order",
		"operator.admin",
		"2026.8",
		CONTROL_PLANE_WRITE
	],
	[
		"canvas.document.view",
		"canvas",
		"operator.read",
		"2026.9"
	],
	[
		"plugins.controlUi.list",
		"plugins-control-ui",
		"operator.read",
		"2026.9"
	],
	[
		"plugins.controlUi.reload",
		"plugins-control-ui",
		"operator.admin",
		"2026.9",
		CONTROL_PLANE_WRITE
	],
	[
		"plugins.controlUi.report",
		"plugins-control-ui",
		"operator.read",
		"2026.9"
	],
	[
		"plugins.controlUi.status",
		"plugins-control-ui",
		"operator.admin",
		"2026.9"
	],
	[
		"update.runs.get",
		"update",
		"operator.admin",
		"2026.9"
	],
	[
		"update.runs.list",
		"update",
		"operator.admin",
		"2026.9"
	],
	[
		"gateway.suspend.handoff",
		"suspend",
		"operator.admin",
		"2026.9",
		CONTROL_PLANE_WRITE
	],
	[
		"transcripts.export",
		"transcripts",
		"operator.read",
		"2026.9"
	],
	[
		"transcripts.status",
		"transcripts",
		"operator.read",
		"2026.9"
	],
	[
		"update.report",
		"update",
		"operator.admin",
		"2026.9",
		CONTROL_PLANE_WRITE
	],
	[
		"skills.workshop.read",
		"skills",
		"operator.read",
		"2026.9"
	],
	[
		"session.publicShare.set",
		"sessions-sharing",
		"operator.write",
		"2026.9"
	],
	[
		"plugins.catalog.browse",
		"plugins",
		"operator.read",
		"2026.9"
	],
	[
		"plugins.catalog.categories",
		"plugins",
		"operator.read",
		"2026.9"
	],
	[
		"plugins.catalog.get",
		"plugins",
		"operator.read",
		"2026.9"
	],
	[
		"environments.prepare",
		"environments",
		"operator.admin",
		"2026.9",
		SIDECAR_CONTROL_PLANE_WRITE
	],
	[
		"models.authRefresh",
		"models-auth-status",
		"operator.admin",
		"2026.9",
		CONTROL_PLANE_WRITE
	],
	[
		"models.authLogin",
		"models-auth-login",
		"operator.admin",
		"2026.9",
		CONTROL_PLANE_WRITE
	],
	[
		"models.authSetApiKey",
		"models-auth-status",
		"operator.admin",
		"2026.9",
		CONTROL_PLANE_WRITE
	],
	[
		"sessions.storage.status",
		"sessions-read",
		"operator.admin",
		"2026.9"
	],
	[
		"sessions.storage.run",
		"sessions-read",
		"operator.admin",
		"2026.9"
	],
	[
		"plugins.reload",
		"plugins-mutations",
		"operator.admin",
		"2026.9",
		CONTROL_PLANE_WRITE
	],
	[
		"canvas.document.preview",
		"canvas",
		"operator.read",
		"2026.9"
	],
	[
		"computer.status",
		"computer",
		"operator.read",
		"2026.9"
	],
	[
		"computer.invoke",
		"computer",
		"operator.write",
		"2026.9"
	],
	[
		"sessions.activitySummary.ensure",
		"session-activity-summary",
		"operator.write",
		"2026.9"
	],
	[
		"controlUi.sessionPullRequests.checks",
		"control-ui",
		"operator.read",
		"2026.9"
	],
	[
		"diagnostics.cpuProfile",
		"diagnostics",
		"operator.admin",
		"2026.9"
	],
	[
		"talk.voice.get",
		"talk",
		"operator.talk",
		"2026.9",
		PROFILE_DEPENDENT
	],
	[
		"talk.voice.set",
		"talk",
		"operator.talk",
		"2026.9"
	],
	[
		"talk.voice.complete",
		"talk",
		"operator.talk",
		"2026.9"
	],
	[
		"plugins.credentials.inspect",
		"plugins",
		"operator.admin",
		"2026.9"
	],
	[
		"plugins.skills.read",
		"plugins",
		"operator.read",
		"2026.9"
	],
	[
		"diagnostics.heapProfile",
		"diagnostics",
		"operator.admin",
		"2026.9"
	],
	[
		"desktop.release",
		"environments",
		"operator.admin",
		"2026.9",
		{ startup: true }
	],
	[
		"mcp.authLogin",
		"mcp-auth-login",
		"operator.admin",
		"2026.9",
		CONTROL_PLANE_WRITE
	],
	[
		"environments.session.status",
		"environments",
		"operator.read",
		"2026.9"
	],
	[
		"environments.session.create",
		"environments",
		"operator.admin",
		"2026.9",
		CONTROL_PLANE_WRITE
	],
	[
		"environments.session.destroy",
		"environments",
		"operator.admin",
		"2026.9",
		CONTROL_PLANE_WRITE
	],
	[
		"environments.session.exec",
		"environments",
		"operator.admin",
		"2026.9"
	],
	[
		"sessions.setInvolvement",
		"sessions-mutations",
		"operator.read",
		"2026.9"
	],
	[
		"transcripts.summarize",
		"transcripts",
		"operator.write",
		"2026.9"
	],
	[
		"controlUi.linkPreview",
		"control-ui",
		"operator.read",
		"2026.9"
	],
	[
		"themes.list",
		"themes",
		"operator.read",
		"2026.9"
	],
	[
		"themes.get",
		"themes",
		"operator.read",
		"2026.9"
	],
	[
		"themes.set",
		"themes",
		"operator.write",
		"2026.9"
	],
	[
		"themes.import",
		"themes",
		"operator.write",
		"2026.9"
	],
	[
		"controlUi.githubDetail",
		"control-ui",
		"operator.read",
		"2026.9"
	],
	[
		"progressCard.refresh",
		"progress-card",
		"operator.write",
		"2026.9"
	],
	[
		"webSearch.status",
		"web-search",
		"operator.read",
		"2026.9",
		PROFILE_DEPENDENT
	],
	[
		"webSearch.test",
		"web-search",
		"operator.admin",
		"2026.9",
		PROFILE_DEPENDENT
	],
	[
		"sessions.providerReview.continue",
		"sessions-provider-review",
		"operator.write",
		"2026.9"
	],
	[
		"users.linkChannelIdentity",
		"users",
		"operator.admin",
		"2026.9",
		PROFILE_DEPENDENT
	],
	[
		"users.unlinkChannelIdentity",
		"users",
		"operator.admin",
		"2026.9",
		PROFILE_DEPENDENT
	],
	[
		"users.listChannelIdentities",
		"users",
		"operator.admin",
		"2026.9",
		PROFILE_DEPENDENT
	],
	[
		"users.personalFile.get",
		"users",
		"operator.read",
		"2026.9"
	],
	[
		"users.personalFile.set",
		"users",
		"operator.read",
		"2026.9"
	],
	[
		"portal.session.list",
		"portals",
		"operator.write",
		"2026.9",
		PORTAL_SESSION_WRITE
	],
	[
		"portal.session.open",
		"portals",
		"operator.write",
		"2026.9",
		PORTAL_SESSION_WRITE
	],
	[
		"portal.session.close",
		"portals",
		"operator.write",
		"2026.9",
		PORTAL_SESSION_WRITE
	],
	[
		"cron.history",
		"cron",
		"operator.read",
		"2026.9"
	],
	[
		"presence.activity",
		"system",
		"operator.read",
		"2026.9",
		PROFILE_DEPENDENT
	],
	[
		"presence.query",
		"presence",
		"operator.read",
		"2026.9",
		PROFILE_DEPENDENT
	],
	[
		"users.merge",
		"users",
		"operator.admin",
		"2026.9",
		PROFILE_DEPENDENT
	],
	[
		"gateway.stop.request",
		"restart",
		"operator.admin",
		"2026.9",
		CONTROL_PLANE_WRITE
	],
	[
		"diagnostics.heapSnapshot",
		"diagnostics",
		"operator.admin",
		"2026.9"
	],
	[
		"sessions.catalog.import",
		"session-catalog",
		"operator.write",
		"2026.9"
	],
	[
		"backup.status",
		"backup",
		"operator.read",
		"2026.9"
	],
	[
		"backup.recordOutcome",
		"backup",
		"operator.admin",
		"2026.9",
		CONTROL_PLANE_WRITE
	],
	[
		"storage.locations.list",
		"storage",
		"operator.read",
		"2026.9"
	],
	[
		"storage.locations.probe",
		"storage",
		"operator.read",
		"2026.9"
	],
	[
		"mcp.app.onboard",
		"mcp-app-onboarding",
		"operator.write",
		"2026.9",
		SESSION_WRITE
	],
	[
		"mcp.app.discover",
		"mcp-app-extensions",
		"operator.write",
		"2026.9",
		SESSION_WRITE
	],
	[
		"mcp.app.launch",
		"mcp-app-extensions",
		"operator.write",
		"2026.9",
		SESSION_WRITE
	],
	[
		"mcp.app.settings",
		"mcp-app-extensions",
		"operator.write",
		"2026.9",
		SESSION_WRITE
	],
	[
		"mcp.app.mention",
		"mcp-app-extensions",
		"operator.write",
		"2026.9",
		SESSION_WRITE
	],
	[
		"mcp.app.formResource",
		"mcp-app",
		"operator.write",
		"2026.9"
	],
	[
		"mcp.app.modelContext",
		"mcp-app",
		"operator.read",
		"2026.9"
	],
	[
		"mcp.app.removeModelContext",
		"mcp-app",
		"operator.write",
		"2026.9"
	],
	[
		"mcp.app.writeResource",
		"mcp-app",
		"operator.write",
		"2026.9"
	],
	[
		"mcp.app.subscribeResource",
		"mcp-app",
		"operator.read",
		"2026.9"
	],
	[
		"mcp.app.unsubscribeResource",
		"mcp-app",
		"operator.read",
		"2026.9"
	],
	[
		"mcp.app.openFile",
		"mcp-app",
		"operator.read",
		"2026.9"
	],
	[
		"memory.get",
		"memory-search",
		"operator.read",
		"2026.9"
	],
	[
		"memory.status",
		"memory-search",
		"operator.read",
		"2026.9"
	],
	[
		"sessions.files.assets",
		"sessions-files",
		"operator.read",
		"2026.9"
	],
	[
		"templates.catalog.search",
		"templates",
		"operator.read",
		"2026.10"
	],
	[
		"templates.catalog.detail",
		"templates",
		"operator.read",
		"2026.10"
	],
	[
		"templates.catalog.preview",
		"templates",
		"operator.read",
		"2026.10"
	],
	[
		"templates.drafts.create",
		"templates-drafts",
		"operator.admin",
		"2026.10",
		CONTROL_PLANE_WRITE
	],
	[
		"templates.drafts.read",
		"templates-drafts",
		"operator.admin",
		"2026.10"
	],
	[
		"templates.drafts.save",
		"templates-drafts",
		"operator.admin",
		"2026.10",
		CONTROL_PLANE_WRITE
	],
	[
		"templates.drafts.review",
		"templates-drafts",
		"operator.admin",
		"2026.10"
	],
	[
		"templates.drafts.publish",
		"templates-drafts",
		"operator.admin",
		"2026.10",
		CONTROL_PLANE_WRITE
	],
	[
		"templates.add.plan",
		"templates-add",
		"operator.read",
		"2026.10"
	],
	[
		"templates.add.apply",
		"templates-add",
		"operator.admin",
		"2026.10",
		CONTROL_PLANE_WRITE
	],
	[
		"worktrees.recoverFile",
		"worktrees",
		"operator.admin",
		"2026.10",
		CONTROL_PLANE_WRITE
	],
	[
		"worktrees.recoverRemoval",
		"worktrees",
		"operator.admin",
		"2026.9",
		CONTROL_PLANE_WRITE
	],
	[
		"worktrees.retireSnapshot",
		"worktrees",
		"operator.admin",
		"2026.9",
		CONTROL_PLANE_WRITE
	],
	[
		"sessions.processes.list",
		"session-processes",
		"operator.read",
		"2026.9",
		OBSERVATION
	],
	[
		"sessions.processes.stop",
		"session-processes",
		"operator.write",
		"2026.9"
	],
	[
		"catalog.browse",
		"plugins",
		"operator.read",
		"2026.9"
	],
	[
		"catalog.searchKeywords",
		"plugins",
		"operator.read",
		"2026.9"
	],
	[
		"skills.workshop.list",
		"skills",
		"operator.read",
		"2026.9"
	],
	[
		"skills.workshop.changes",
		"skills",
		"operator.read",
		"2026.9"
	],
	[
		"skills.workshop.archive",
		"skills",
		"operator.admin",
		"2026.9"
	],
	[
		"skills.workshop.restore",
		"skills",
		"operator.admin",
		"2026.9"
	],
	[
		"skills.workshop.undo",
		"skills",
		"operator.admin",
		"2026.9"
	],
	[
		"skills.workshop.applyDraft",
		"skills",
		"operator.admin",
		"2026.10"
	],
	[
		"skills.workshop.discardDraft",
		"skills",
		"operator.admin",
		"2026.10"
	],
	[
		"memory.search.owner",
		"memory-search",
		"operator.admin",
		"2026.9"
	],
	[
		"secrets.store.import",
		null,
		"operator.admin",
		"2026.9",
		CONTROL_PLANE_WRITE
	],
	[
		"secrets.store.allowedHosts",
		null,
		"operator.admin",
		"2026.9",
		CONTROL_PLANE_WRITE
	],
	[
		"users.background.get",
		"users",
		"operator.read",
		"2026.9"
	],
	[
		"users.background.upload",
		"users",
		"operator.write",
		"2026.9"
	],
	[
		"users.background.remove",
		"users",
		"operator.write",
		"2026.9"
	],
	[
		"debugProxy.capture",
		"debug-proxy",
		"operator.admin",
		"2026.9"
	],
	[
		"openclaw.setup.auto",
		"system-agent",
		"operator.admin",
		"2026.10"
	],
	[
		"environments.adoptSuggestedProfile",
		"environments",
		"operator.admin",
		"2026.10",
		CONTROL_PLANE_WRITE
	],
	[
		"ui.command.result",
		"ui-command",
		"operator.read",
		"2026.10",
		PROFILE_DEPENDENT
	],
	[
		"mcp.events.list",
		"mcp-events",
		"operator.read",
		"2026.10",
		PROFILE_DEPENDENT
	],
	[
		"projects.checkoutOptions",
		"projects",
		"operator.read",
		"2026.10"
	],
	[
		"chat.predict",
		"chat",
		"operator.write",
		"2026.10",
		OWN_SESSION_WRITE
	],
	[
		"tools.github.read",
		"tools-github",
		"operator.sessions.read",
		"2026.10",
		UNADVERTISED
	],
	[
		"tools.github.search",
		"tools-github",
		"operator.sessions.read",
		"2026.10",
		UNADVERTISED
	],
	[
		"openclaw.setup.runtime.start",
		"system-agent",
		"operator.admin",
		"2026.10"
	],
	[
		"sessions.github.action",
		"sessions-github",
		"dynamic",
		"2026.10",
		CONTROL_PLANE_WRITE
	],
	[
		"update.handoffSentinel",
		"update-handoff-sentinel",
		"operator.admin",
		"2026.10",
		UNADVERTISED
	],
	[
		"skills.files.get",
		"skills",
		"operator.read",
		"2026.10"
	],
	[
		"agents.avatar.generate",
		"agents",
		"operator.admin",
		"2026.10",
		CONTROL_PLANE_WRITE
	],
	[
		"exec.approvals.native.commit",
		"exec-approvals",
		"operator.admin",
		"2026.10"
	],
	[
		"chat.pendingInputs.dismiss",
		"chat",
		"operator.write",
		"2026.10",
		OWN_SESSION_WRITE
	],
	[
		"update.recovery.cleanup",
		"update",
		"operator.admin",
		"2026.10",
		CONTROL_PLANE_WRITE
	],
	[
		"diagnostics.capabilities",
		"diagnostics",
		"operator.read",
		"2026.10"
	],
	[
		"cron.bind",
		"cron",
		"operator.admin",
		"2026.10",
		CONTROL_PLANE_WRITE
	],
	[
		"talk.client.say",
		"talk",
		"operator.talk",
		"2026.10"
	],
	[
		"sessions.github.readiness",
		"sessions-github",
		"operator.read",
		"2026.10",
		{
			startup: true,
			...OBSERVATION
		}
	]
];
//#endregion
//#region src/gateway/methods/descriptor.ts
/** Scope marker for methods that only authenticated node clients may call. */
const NODE_GATEWAY_METHOD_SCOPE = "node";
/** Scope marker for methods whose handler derives the required operator scope at runtime. */
const DYNAMIC_GATEWAY_METHOD_SCOPE = "dynamic";
//#endregion
//#region src/gateway/methods/core-method-policy.ts
const CORE_GATEWAY_METHOD_SPEC_LIST = CORE_GATEWAY_METHOD_SPECS.map(([e, t, n, r, i]) => Object.assign({
	name: e,
	scope: n,
	since: r,
	...t ? { family: t } : {}
}, i));
const CORE_GATEWAY_METHOD_SPEC_BY_NAME = new Map(CORE_GATEWAY_METHOD_SPEC_LIST.map((e) => [e.name, e]));
/** Core methods that are listed early but return retryable unavailable until sidecars are ready. */
const STARTUP_UNAVAILABLE_GATEWAY_METHODS = CORE_GATEWAY_METHOD_SPEC_LIST.filter((e) => e.startup === true).map((e) => e.name);
/** Looks up an operator-only core method scope, excluding node and dynamic methods. */
function resolveCoreOperatorGatewayMethodScope(e) {
	const t = CORE_GATEWAY_METHOD_SPEC_BY_NAME.get(e)?.scope;
	return t === "node" || t === "dynamic" ? void 0 : t;
}
function isDynamicOperatorGatewayMethod(e) {
	return CORE_GATEWAY_METHOD_SPEC_BY_NAME.get(e)?.scope === DYNAMIC_GATEWAY_METHOD_SCOPE;
}
function isCoreGatewayMethodClassified(e) {
	return CORE_GATEWAY_METHOD_SPEC_BY_NAME.has(e);
}
//#endregion
//#region src/gateway/node-browser-proxy-policy.ts
function isForbiddenBrowserProxyMutation(e) {
	if (!e || typeof e !== "object") return false;
	const t = e;
	const n = normalizeOptionalString(t.method)?.toUpperCase();
	const r = normalizeOptionalString(t.path);
	if (!n || !r) return false;
	const i = r.startsWith("/") ? r : `/${r}`;
	const a = i.length <= 1 ? i : i.replace(/\/+$/, "");
	if (n === "POST" && (a === "/profiles/create" || a === "/reset-profile")) return true;
	return n === "DELETE" && /^\/profiles\/[^/]+$/.test(a);
}
//#endregion
//#region src/gateway/method-scopes.ts
/** Default scopes granted to CLI/operator clients when no narrower local policy is known. */
const CLI_DEFAULT_OPERATOR_SCOPES = [
	ADMIN_SCOPE,
	READ_SCOPE,
	WRITE_SCOPE,
	APPROVALS_SCOPE,
	QUESTIONS_SCOPE,
	PAIRING_SCOPE,
	TALK_SECRETS_SCOPE
];
function resolveScopedMethod(e) {
	const t = resolveCoreOperatorGatewayMethodScope(e);
	if (t) return t;
	const n = resolveReservedGatewayMethodScope(e);
	if (n) return n;
	const r = (getPluginRegistryForContext()?.gatewayMethodDescriptors?.find((t) => t.name === e))?.scope;
	return r === "node" || r === "dynamic" ? void 0 : r;
}
function resolveSessionActionRegisteredScopes(e) {
	const t = asOptionalRecord(e);
	if (!t) return;
	const n = normalizeOptionalString(t.pluginId);
	const r = normalizeOptionalString(t.actionId);
	if (!n || !r) return;
	const i = getPluginRegistryForContext()?.sessionActions?.find((e) => e.pluginId === n && e.action.id === r);
	if (!i) return;
	const a = i.action.requiredScopes;
	return a && a.length > 0 ? [...a] : [WRITE_SCOPE];
}
function resolveSessionActionLeastPrivilegeScopes(e) {
	const t = resolveSessionActionRegisteredScopes(e);
	if (t) return t;
	const n = asOptionalRecord(e);
	if (n) {
		const e = normalizeOptionalString(n.pluginId);
		const t = normalizeOptionalString(n.actionId);
		if (e && t) return [...CLI_DEFAULT_OPERATOR_SCOPES];
	}
	return [WRITE_SCOPE];
}
function resolveDynamicLeastPrivilegeOperatorScopesForMethod(e, t) {
	if (e === "plugins.sessionAction") return resolveSessionActionLeastPrivilegeScopes(t);
	const n = asOptionalRecord(t);
	if (e === "sessions.github.action") return [n?.action === "inspect_pr" || n?.action === "prepare_pr" || n?.action === "refresh_base" || n?.action === "edit" || n?.action === "request_review" || n?.action === "upload_evidence" || n?.action === "ready" && n.publishingSessionKey === void 0 ? SESSION_WRITE_SCOPE : WRITE_SCOPE];
	if (e === "agent") return isAgentSessionResetCommand(n?.message) ? [ADMIN_SCOPE] : [WRITE_SCOPE];
	if (e === "node.invoke") {
		const e = n?.command;
		if (isBrowserProxyNodeInvokeCommand(e) && isForbiddenBrowserProxyMutation(n?.params)) return [WRITE_SCOPE];
		return isAdminOnlyNodeInvokeCommand(e) ? [ADMIN_SCOPE] : [WRITE_SCOPE];
	}
	if (e === "talk.config") return n?.includeSecrets === true ? [READ_SCOPE, TALK_SECRETS_SCOPE] : [READ_SCOPE];
	if (e === "environments.list") {
		const e = n && "runtimeId" in n ? n.runtimeId : void 0;
		return typeof e === "string" && e ? [WRITE_SCOPE] : [READ_SCOPE];
	}
	if (e === "channels.pairing.approve") return n?.bootstrapCommandOwner === true ? [PAIRING_SCOPE, ADMIN_SCOPE] : [PAIRING_SCOPE];
	if (e === "fs.listDir") return [n && Object.hasOwn(n, "nodeId") ? ADMIN_SCOPE : WRITE_SCOPE];
	if (e === "sessions.patch" || e === "sessions.patchMany" || e === "sessions.create" || e === "sessions.dispatch" || e === "sessions.move") return [resolveDynamicSessionMutationRequiredScope(e, t) ?? "operator.write"];
	if (e === "sessions.delete") return [resolveDynamicSessionMutationRequiredScope(e, t) ?? "operator.admin"];
	return [WRITE_SCOPE];
}
function resolveLeastPrivilegeOperatorScopesForMethod(e, t) {
	if (isDynamicOperatorGatewayMethod(e)) return resolveDynamicLeastPrivilegeOperatorScopesForMethod(e, t);
	const n = resolveScopedMethod(e);
	if (n) return [n];
	return [];
}
function isGatewayMethodClassified(e) {
	return isCoreGatewayMethodClassified(e) || resolveScopedMethod(e) !== void 0;
}
//#endregion
//#region src/gateway/operator-cli-message-input.ts
/** Operator message RPCs cannot preserve the source of an agent's shell report. */
function assertGatewayCliMessageContext(e, t) {
	const n = process.env.OPENCLAW_SHELL === "exec";
	const r = process.env[SUBAGENT_EXEC_ENV_VAR] === "1";
	if (!n && !r) return;
	const i = [
		"sessions.send",
		"sessions.steer",
		"chat.send"
	].includes(e);
	if (r && i) throw new Error("Subagent session messages must use the task completion path. Return your result or blocker in the child turn; do not use the CLI to contact other sessions.");
	if (!n) return;
	const a = e === "sessions.create" ? asNullableRecord(t) : null;
	if (a && ([a.message, a.task].some((e) => typeof e === "string" && e.trim()) || Array.isArray(a.attachments) && a.attachments.length > 0) || i || e === "agent") throw new Error(`Gateway ${e} from agent exec would lose inter-session attribution. Use the attributed session-messaging tool available to this run, or return the result through normal subagent completion. Do not retry through another CLI route or remove the exec marker.`);
}
//#endregion
//#region src/gateway/transport-error.ts
var GatewayTransportError = class extends Error {
	constructor(e) {
		super(e.message);
		this.name = "GatewayTransportError";
		this.kind = e.kind;
		this.connectionDetails = e.connectionDetails;
		if (e.code !== void 0) this.code = e.code;
		if (e.reason !== void 0) this.reason = e.reason;
		if (e.timeoutMs !== void 0) this.timeoutMs = e.timeoutMs;
		if (e.requestDispatched !== void 0) this.requestDispatched = e.requestDispatched;
	}
};
const DISPATCHED_REQUEST_OUTCOME_GUIDANCE = "The request was already sent to the gateway, so the operation may have been applied even though no response arrived; its outcome is unknown. Verify the current state (for example, re-run the equivalent read-only command) before retrying, especially for write actions.";
function createGatewayCloseTransportError(e) {
	const { code: t, connectionDetails: n, requestDispatched: r } = e;
	const i = normalizeOptionalString(e.reason) || "no close reason";
	const a = t === 1006 ? "abnormal closure (no close frame)" : t === 1e3 ? "normal closure" : "";
	let o = `gateway closed (${t}${a ? ` ${a}` : ""}): ${i}\n${n.message}`;
	if (t === 1006) o += `\n\nPossible causes:\n${r ? "- Connection dropped without a close frame (check network and gateway load)" : "- Connection dropped without a close frame (retry; check network and gateway load)\n- Gateway not yet ready to accept connections (retry after a moment)\n- TLS mismatch (connecting with ws:// to a wss:// gateway, or vice versa)"}
- Gateway process stopped or became unreachable (confirm it is still running)
Run \`openclaw doctor\` for diagnostics.`;
	return new GatewayTransportError({
		kind: "closed",
		code: t,
		reason: i,
		connectionDetails: n,
		requestDispatched: r,
		message: r ? `${o}\n\n${DISPATCHED_REQUEST_OUTCOME_GUIDANCE}` : o
	});
}
function createGatewayTimeoutTransportError(e) {
	const { timeoutMs: t, connectionDetails: n, requestDispatched: r } = e;
	const i = `gateway timeout after ${t}ms\n${n.message}`;
	return new GatewayTransportError({
		kind: "timeout",
		timeoutMs: t,
		connectionDetails: n,
		requestDispatched: r,
		message: r ? `${i}\n\n${DISPATCHED_REQUEST_OUTCOME_GUIDANCE}` : i
	});
}
function firstGatewayErrorLine(e) {
	return e.split("\n", 1)[0]?.trim() || e;
}
const GATEWAY_UNREACHABLE_SOCKET_CODES = /* @__PURE__ */ new Set([
	"ECONNREFUSED",
	"ECONNRESET",
	"EHOSTUNREACH",
	"ENETUNREACH",
	"ENOTFOUND",
	"ETIMEDOUT"
]);
function isGatewayUnreachableSocketError(e) {
	const t = extractErrorCodeOrErrno(e);
	return t !== void 0 && GATEWAY_UNREACHABLE_SOCKET_CODES.has(t);
}
/** Wrap raw socket-level connect failures (ECONNREFUSED etc.) into one actionable message. */
function createGatewayUnreachableTransportError(e) {
	const t = extractErrorCodeOrErrno(e.cause);
	return new GatewayTransportError({
		kind: "closed",
		reason: firstGatewayErrorLine(e.cause.message),
		connectionDetails: e.connectionDetails,
		message: [
			`Gateway not reachable at ${projectGatewayUrlForDiagnostics(e.connectionDetails.url)}${t ? ` (${t})` : ""}.`,
			"Start it with `openclaw gateway run` or check `openclaw gateway status`.",
			e.connectionDetails.message
		].join("\n")
	});
}
//#endregion
//#region src/gateway/call.ts
async function loadGatewayConfig() {
	return getRuntimeConfigSnapshot() ?? await readGatewayDispatchConfigWithShellEnvFallback();
}
async function stopGatewayClient(e) {
	try {
		await e.stopAndWait({ timeoutMs: 1e3 });
	} catch {
		e.stop();
	}
}
function resolveGatewayClientDisplayName(e) {
	if (e.clientDisplayName) return e.clientDisplayName;
	const t = e.clientName ?? GATEWAY_CLIENT_NAMES.CLI;
	if ((e.mode ?? GATEWAY_CLIENT_MODES.CLI) !== GATEWAY_CLIENT_MODES.BACKEND && t !== GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT) return;
	const n = e.method.trim();
	return n ? `gateway:${n}` : "gateway:request";
}
/**
* Load config for a fully flag-addressed connection. Config only supplies
* gateway.remote.edgeAuth here, so an unreadable or invalid config degrades to
* empty rather than blocking a connection the flags already describe.
*/
async function loadGatewayConfigForExplicitConnection() {
	try {
		return await loadGatewayConfig();
	} catch {
		return {};
	}
}
function resolveGatewayConfigPath(e) {
	return resolveConfigPath(e, resolveStateDir(e));
}
function buildGatewayConnectionDetails(e = {}) {
	return buildGatewayConnectionDetailsWithResolvers(e, {
		getRuntimeConfig: readGatewayDispatchConfig,
		resolveConfigPath: resolveGatewayConfigPath,
		resolveGatewayPort
	});
}
function resolveGatewayCallTimeout(e) {
	const t = Boolean(process.env.OPENCLAW_HANDSHAKE_TIMEOUT_MS) || Boolean(isVitestRuntimeEnv() && process.env.OPENCLAW_TEST_HANDSHAKE_TIMEOUT_MS) ? resolvePreauthHandshakeTimeoutMs() : void 0;
	const n = typeof t === "number" && t > 1e4 ? t : 1e4;
	const r = typeof e === "number" && Number.isFinite(e) ? e : void 0;
	const i = r ?? n;
	const a = e === null ? null : r ?? n;
	return {
		timeoutMs: a,
		startupTimeoutMs: i,
		safeTimerTimeoutMs: resolveSafeTimeoutDelayMs(a ?? i)
	};
}
async function resolveGatewayCallContext(e) {
	const t = resolveExplicitGatewayAuth({
		token: e.token,
		password: e.password
	});
	const n = resolveGatewayUrlOverride({
		gatewayUrl: e.url,
		env: process.env,
		ignoreEnvUrlOverride: e.ignoreEnvUrlOverride,
		localPortOverride: e.localPortOverride
	}).url;
	const r = {
		config: e.config,
		urlOverride: n,
		explicitAuth: t
	};
	const i = canSkipGatewayConfigLoad(r);
	const a = isExplicitGatewayConnection(r);
	const o = e.config ?? (i ? {} : a ? await loadGatewayConfigForExplicitConnection() : await loadGatewayConfig());
	return {
		config: o,
		configSkipped: i,
		configPath: e.configPath ?? resolveGatewayConfigPath(process.env),
		isRemoteMode: e.localPortOverride === void 0 && o.gateway?.mode === "remote",
		explicitAuth: t
	};
}
function gatewayCallBootstrapOptions(e, t) {
	return {
		config: t.config,
		gatewayUrl: e.url,
		explicitAuth: t.explicitAuth,
		env: process.env,
		configPath: t.configPath,
		ignoreEnvUrlOverride: e.localPortOverride !== void 0 || e.ignoreEnvUrlOverride === true || e.serviceTargetUrl !== void 0,
		localPortOverride: e.localPortOverride,
		explicitTlsFingerprint: e.tlsFingerprint,
		buildConnectionDetails: buildGatewayConnectionDetails,
		...e.serviceTargetUrl ? { serviceTargetUrl: e.serviceTargetUrl } : {}
	};
}
function ensureRemoteModeUrlConfigured(e) {
	if (!e.context.isRemoteMode || e.urlOverrideSource || trimToUndefined(e.context.config.gateway?.remote?.url)) return;
	throw new Error([
		"gateway remote mode misconfigured: gateway.remote.url missing",
		`Config: ${e.context.configPath}`,
		"Fix: set gateway.remote.url, or set gateway.mode=local."
	].join("\n"));
}
function createGatewayRequestAbortError(e) {
	return createAbortError(`gateway request aborted for ${e}`);
}
function isRequiredAgentRuntimeIdentityConnectError(e) {
	return e.message.includes("gateway rejected required agent runtime identity auth field; refusing to retry without it");
}
function isAllowlistedGatewayConnectRequestError(e) {
	if (e.name !== "GatewayClientRequestError") return false;
	return readConnectErrorDetailCode(e.details) === ConnectErrorDetailCodes.AUTH_RATE_LIMITED;
}
async function callGatewayWithScopes(e, t, n = false) {
	const r = await resolveGatewayCallContext(e);
	const { timeoutMs: i, startupTimeoutMs: a, safeTimerTimeoutMs: o } = resolveGatewayCallTimeout(e.timeoutMs);
	const s = resolveGatewayUrlOverride({
		gatewayUrl: e.url,
		env: process.env,
		ignoreEnvUrlOverride: e.ignoreEnvUrlOverride,
		localPortOverride: e.localPortOverride
	}).source;
	if (e.requireLocalBackendSharedAuth && (s || r.isRemoteMode)) throw new GatewayLocalBackendSharedAuthUnavailableError("local backend shared auth is limited to the configured local gateway");
	const c = e.useStoredDeviceAuth === true;
	const l = Boolean(r.explicitAuth.token || r.explicitAuth.password);
	const u = c && !l;
	const d = await resolveGatewayClientBootstrap({
		...gatewayCallBootstrapOptions(e, r),
		skipImplicitAuth: u || e.skipImplicitAuth === true,
		...u ? {} : { overrideAuthErrorHint: "Fix: pass --token or --password with --url (or gatewayToken in tools)." }
	});
	ensureRemoteModeUrlConfigured({
		context: r,
		urlOverrideSource: d.urlOverrideSource
	});
	const f = d.connectionDetails;
	const p = d.url;
	if (e.expectUrl !== void 0 && p !== e.expectUrl) throw new Error("Gateway destination changed. Refresh the selected Gateway before retrying.");
	const m = d.deviceAuthScope;
	const h = u ? void 0 : d.auth.token;
	const g = u ? void 0 : d.auth.password;
	const _ = resolveGatewayConnectionAuth({
		config: r.config,
		configSkipped: r.configSkipped,
		auth: {
			token: h,
			password: g
		}
	});
	const { clientOptions: v, omitDeviceIdentity: y, deviceIdentity: b } = await resolveGatewayCallDeviceAuth({
		opts: e,
		url: p,
		authMode: _.mode,
		isImplicitLocalTarget: !s && !r.isRemoteMode,
		token: h,
		password: g
	});
	const x = {
		...e,
		...v
	};
	let S = x.preparedDeviceAuth;
	if (u) {
		S ??= await loadStoredOperatorDeviceAuthToken(b, m, x.sharedStateMode);
		if (!S?.token && m) throw new GatewayStoredDeviceAuthUnavailableError(["No stored device auth for this gateway origin.", `Run \`openclaw tui${d.sshTunnel ? "" : ` --url ${projectGatewayUrlForDiagnostics(p)}`}\` to send a pairing request, approve it in that gateway's Control UI (Settings -> Devices) or run \`openclaw devices approve --latest\` on the gateway host, then retry.`].join("\n"));
	}
	const C = d.tlsFingerprint;
	const w = normalizeEdgeAuthHeadersConfig(gatewayEdgeAuthValueForTarget({
		config: r.config,
		targetUrl: p
	}));
	const T = await resolveEdgeAuthHeaders({
		config: r.config,
		value: w,
		targetUrl: p,
		env: process.env
	});
	if (u) {
		if (!S?.token) throw new GatewayCredentialsRequiredError({
			method: x.method,
			configPath: r.configPath
		});
		if (Array.isArray(x.requiredStoredDeviceAuthScopes) && !roleScopesAllow({
			role: "operator",
			requestedScopes: x.requiredStoredDeviceAuthScopes,
			allowedScopes: S.scopes
		})) throw new GatewayStoredDeviceAuthUnavailableError("stored device auth does not grant the required operator scopes");
	}
	if ((_.mode === "token" || _.mode === "password") && !h && !g && !x.approvalRuntimeToken && !_.allowTailscale) {
		if (!(S === void 0 ? await loadStoredOperatorDeviceAuthToken(b, m, x.sharedStateMode) : S)?.token) throw new GatewayCredentialsRequiredError({
			method: x.method,
			configPath: r.configPath
		});
	}
	const E = c && l && x.requiredStoredDeviceAuthScopes ? x.requiredStoredDeviceAuthScopes : u ? void 0 : n && y && !b ? [ADMIN_SCOPE] : t;
	const D = u || x.requireLocalBackendSharedAuth === true || Boolean(x.agentRuntimeIdentityToken);
	return await new Promise((e, t) => {
		if (x.signal?.aborted) {
			t(createGatewayRequestAbortError(x.method));
			return;
		}
		let n = false;
		let r;
		let s;
		const c = new AbortController();
		let l = false;
		let u = 0;
		let _ = 0;
		const cleanup = () => {
			c.abort();
			x.signal?.removeEventListener("abort", abortHandler);
			clearTimeout(r);
		};
		const stopClientThenSettle = (n, r) => {
			const complete = () => {
				if (n) t(n);
				else e(r);
			};
			const i = s;
			const a = stopGatewayClient(v);
			if (i) Promise.allSettled([a, i]).then(complete);
			else a.then(complete, complete);
		};
		const stop = (e, t) => {
			if (n) return;
			n = true;
			cleanup();
			stopClientThenSettle(e, t);
		};
		const abortHandler = () => {
			if (n) return;
			n = true;
			cleanup();
			const e = createGatewayRequestAbortError(x.method);
			const stopAfterAbortHook = () => stopClientThenSettle(e);
			if (!x.onSignalAbort || !l) {
				stopAfterAbortHook();
				return;
			}
			const t = v.request.bind(v);
			Promise.resolve().then(() => x.onSignalAbort?.(t)).catch(() => {}).finally(stopAfterAbortHook);
		};
		x.signal?.addEventListener("abort", abortHandler, { once: true });
		const v = new GatewayClient({
			url: p,
			sshTunnel: d.sshTunnel,
			token: h,
			password: g,
			edgeAuthHeaders: T,
			tlsFingerprint: C,
			preauthHandshakeTimeoutMs: x.preauthHandshakeTimeoutMs,
			assertConnectionCurrent: x.assertConnectionCurrent,
			instanceId: x.instanceId ?? randomUUID(),
			clientName: x.clientName ?? GATEWAY_CLIENT_NAMES.CLI,
			clientDisplayName: resolveGatewayClientDisplayName(x),
			clientVersion: x.clientVersion ?? VERSION,
			caps: ["ultrafast", ...x.caps ?? []],
			platform: x.platform,
			mode: x.mode ?? GATEWAY_CLIENT_MODES.CLI,
			...x.approvalRuntimeToken ? { approvalRuntimeToken: x.approvalRuntimeToken } : {},
			...x.agentRuntimeIdentityToken ? { agentRuntimeIdentityToken: x.agentRuntimeIdentityToken } : {},
			role: "operator",
			...Array.isArray(E) ? { scopes: E } : {},
			deviceIdentity: b,
			...m ? { deviceAuthScope: m } : {},
			...S ? { preparedDeviceAuth: S } : {},
			...x.sharedStateMode ? { sharedStateMode: x.sharedStateMode } : {},
			minProtocol: x.minProtocol ?? 4,
			maxProtocol: x.maxProtocol ?? 4,
			onHelloOk: (e) => {
				const t = ++_;
				if (i === null && r) {
					clearTimeout(r);
					r = void 0;
				}
				try {
					x.onHelloOk?.(e);
				} catch {}
				if (n) return;
				(async () => {
					try {
						ensureGatewaySupportsRequiredFeatures({
							kind: "method",
							required: Array.isArray(x.requiredMethods) ? x.requiredMethods : [],
							supported: Array.isArray(e.features?.methods) ? e.features.methods : [],
							attemptedMethod: x.method
						});
						ensureGatewaySupportsRequiredFeatures({
							kind: "capability",
							required: x.requiredCapabilities,
							supported: e.features?.capabilities,
							attemptedMethod: x.method
						});
						if (x.prepareDispatchCurrent) await x.prepareDispatchCurrent();
						if (n || x.signal?.aborted || t !== _) return;
						x.assertDispatchCurrent?.();
						l = true;
						const r = await v.request(x.method, x.params, {
							expectFinal: x.expectFinal,
							timeoutMs: x.timeoutMs,
							signal: x.signal,
							onAccepted: x.onAccepted
						});
						if (x.onResponse) {
							const e = x.onResponse;
							s = Promise.resolve().then(() => e(v.request.bind(v), c.signal));
							await s;
						}
						stop(void 0, r);
					} catch (e) {
						if (n || t !== _) return;
						stop(e);
					}
				})();
			},
			onClose: (e, t, r) => {
				_ += 1;
				if (n) return;
				if (r?.connectError) {
					stop(isGatewayUnreachableSocketError(r.connectError) ? createGatewayUnreachableTransportError({
						cause: r.connectError,
						connectionDetails: f
					}) : r.connectError);
					return;
				}
				if (!l && r?.transientPreHelloCleanClose === true && u < 1) {
					u += 1;
					return;
				}
				stop(createGatewayCloseTransportError({
					code: e,
					reason: t,
					connectionDetails: f,
					requestDispatched: l
				}));
			},
			onConnectError: (e) => {
				const t = e.name === "GatewayClientRequestError";
				const r = Boolean(x.agentRuntimeIdentityToken) && isRequiredAgentRuntimeIdentityConnectError(e);
				const i = isGatewayConnectAssemblyError(e) || r || isAllowlistedGatewayConnectRequestError(e) || D && t;
				if (n || !i) return;
				stop(e);
			}
		});
		const y = i ?? a;
		r = setTimeout(() => {
			stop(createGatewayTimeoutTransportError({
				timeoutMs: y,
				connectionDetails: f,
				requestDispatched: l
			}));
		}, o);
		startGatewayClientWhenEventLoopReady(v, {
			timeoutMs: o,
			signal: c.signal
		}).then((e) => {
			if (n || e.ready || e.aborted) return;
			stop(createGatewayTimeoutTransportError({
				timeoutMs: a,
				connectionDetails: f,
				requestDispatched: false
			}));
		}).catch((e) => {
			if (n) return;
			stop(e instanceof Error ? e : new Error(String(e)));
		});
	});
}
function shouldEscalateSessionCreateCwdScope(e) {
	if (e.opts.method !== "sessions.create" || !isRecord(e.opts.params) || !normalizeOptionalString(e.opts.params.cwd) || e.scopes.length !== 1 || e.scopes[0] !== "operator.write") return false;
	const t = isRecord(e.error) ? e.error : void 0;
	const n = readMissingScopeErrorDetails(t?.details);
	return n?.missingScope === "operator.admin" && n.requiredScopes.includes("operator.admin");
}
async function callGatewayWithScopeEscalation(e, t) {
	try {
		return await callGatewayWithScopes(e, t);
	} catch (n) {
		if (!shouldEscalateSessionCreateCwdScope({
			opts: e,
			scopes: t,
			error: n
		})) throw n;
		return await callGatewayWithScopes(e, [ADMIN_SCOPE]);
	}
}
async function callGatewayCli(e) {
	assertGatewayCliMessageContext(e.method, e.params);
	if (Array.isArray(e.scopes)) return await callGatewayWithScopes(e, e.scopes);
	const t = isGatewayMethodClassified(e.method) ? resolveLeastPrivilegeOperatorScopesForMethod(e.method, e.params) : CLI_DEFAULT_OPERATOR_SCOPES;
	if (e.method === "chat.abort" || e.method === "sessions.abort") return await callGatewayWithScopes(e, t, true);
	return await callGatewayWithScopeEscalation(e, t);
}
async function callGatewayLeastPrivilege(e) {
	return await callGatewayWithScopeEscalation(e, resolveLeastPrivilegeOperatorScopesForMethod(e.method, e.params));
}
async function callGateway(e) {
	const t = e.mode ?? GATEWAY_CLIENT_MODES.BACKEND;
	const n = e.clientName ?? GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT;
	if (t === GATEWAY_CLIENT_MODES.CLI || n === GATEWAY_CLIENT_NAMES.CLI) return await callGatewayCli(e);
	const r = {
		...e,
		mode: t,
		clientName: n
	};
	return Array.isArray(e.scopes) ? await callGatewayWithScopes(r, e.scopes) : await callGatewayLeastPrivilege(r);
}
//#endregion
export { callGateway };