UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,398 lines • 53 kB
import { o as asDateTimestampMs, z as resolveTimestampMsToIsoString } from "./number-coercion-D6u-4YD8.mjs";
import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs";
import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs";
import { r as isPathInside$1 } from "./path-guards-TIjxtj6H.mjs";
import "./utils-C8YECn2Q.mjs";
import { t as escapeRegExp } from "./regexp-dj3rRPbj.mjs";
import { S as resolveIsConfigReadOnly } from "./paths-DAcAg5aV.mjs";
import { t as FsSafeError, u as openLocalFileSafely } from "./fs-safe-BbWvmdVn.mjs";
import { r as isIncognitoSessionKey } from "./session-key-DW1jcHbM.mjs";
import { t as isControlUiFocusPath } from "./focus-DDcKuIiJ.mjs";
import { k as normalizeSessionKeyPreservingOpaquePeerIds } from "./session-key-CqAyZeVk.mjs";
import { n as createQueuedDiagnosticPhaseEmitter } from "./diagnostic-events-BjAH1Kbx.mjs";
import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs";
import { n as resolveOpenClawPackageRoot } from "./openclaw-root-C-ayo09z.mjs";
import { l as resolveRuntimeServiceVersion, o as resolveRuntimeServiceBuildId } from "./version-GlxUMdxI.mjs";
import { r as createLazyRuntimeModule } from "./lazy-runtime-zGjszCtt.mjs";
import { n as startsWithSvgRootElement } from "./svg-image-ClSksOzI.mjs";
import { h as readRuntimeConfig } from "./runtime-snapshot-WbwbY5b7.mjs";
import { t as GATEWAY_OWNER_PROFILE_ID } from "./user-profile-constants-Bj3FwpfE.mjs";
import { c as resolveAvatarMime } from "./avatar-policy-C1iXc49e.mjs";
import { a as CONTROL_UI_BASE_PATH_ATTRIBUTE, c as CONTROL_UI_ENVIRONMENT_ATTRIBUTE, d as matchesControlUiBootstrapConfigPath, o as CONTROL_UI_BOOTSTRAP_CONFIG_ATTRIBUTE, u as CONTROL_UI_TERMINAL_ENABLED_ATTRIBUTE } from "./zod-schema.gateway-BfjwVYdf.mjs";
import "./io-4QsrsWTJ.mjs";
import { n as runCommandWithTimeout } from "./exec-runner-Br73vG-X.mjs";
import "./exec-aRIvS9s4.mjs";
import { t as safeEqualSecret } from "./secret-equal-BogABOFr.mjs";
import { n as authorizeOperatorScopesForMethod } from "./method-scopes-Dpyb0Ck-.mjs";
import { n as isCloudWorkerPlacementState } from "./session-placement-state-Bu2J_cK7.mjs";
import { t as captureResidentUserProfileAccess } from "./user-profile-list-D7DDbqt5.mjs";
import { i as resolveSessionPermissionCoreToolPolicy } from "./session-permission-exec-mode-vqqWNPSg.mjs";
import { l as kindFromMime, n as detectMime } from "./mime-D2wVBzpa.mjs";
import { t as sameTranscriptEntryAnchor } from "./transcript-entry-anchor-D4uSx3rE.mjs";
import { f as extractCanvasShortcodes } from "./chat-display-projection.canvas-XAAIxHM8.mjs";
import { t as ASSISTANT_DISPLAY_CONTENT_FIELD } from "./assistant-display-content-CBuMU4m5.mjs";
import { p as readPersistedMediaFacts } from "./media-facts-B-0Dpo5L.mjs";
import { r as parseInboundMediaUri } from "./inbound-media-uri-DpK4_BLW.mjs";
import { t as buildInboundMediaUriFromPath } from "./inbound-media-path-C6oH727p.mjs";
import { R as readSessionPendingInput } from "./session-accessor-CizTbDQj.mjs";
import { t as MAX_PAYLOAD_BYTES } from "./payload-limits-ChDi8AHf.mjs";
import { t as escapeHtml } from "./html-escape-BB_nPhWX.mjs";
import { r as CHAT_PENDING_INPUT_MESSAGE_PREFIX } from "./chat-history-constants-BGgHv5E_.mjs";
import { r as resolveRequestedSessionAgentId } from "./session-request-agent-tfwWH53J.mjs";
import { n as readSessionTranscriptAnchorsAsync } from "./session-transcript-anchor-read-BUt-Wh3r.mjs";
import { a as getRemoteControlUiIngressContext, r as assertRemoteControlUiIngressCurrent } from "./ingress-attribution-DAAQgd6y.mjs";
import { t as resolveGatewayPublicOrigin } from "./gateway-public-origin-SLjx6A2a.mjs";
import { i as resolveSandboxConfigForAgent } from "./config-WbZbWrF1.mjs";
import { n as resolvePreparedSandboxRuntimeStatus } from "./runtime-status-C5ZOG7YR.mjs";
import { n as createProfileSessionEntryFilter } from "./session-sharing-read-BqjuH16A.mjs";
import "./session-sharing-BIP3raq1.mjs";
import { t as captureSessionEntryMetadataRead } from "./session-entry-source-authority-Bxiv7qVT.mjs";
import { l as createHttpRequestAbortSignal } from "./http-body-B9w7rzPz.mjs";
import { t as normalizeControlUiBasePath } from "./control-ui-shared-_tUmz6W8.mjs";
import { i as parseControlUiResourcePath, o as resolveAssistantMediaRoutePath } from "./control-ui-resource-routes-DgXN5Axb.mjs";
import { a as isControlUiVersionedPublicAsset, i as isControlUiRootPublicAsset, n as CONTROL_UI_ROOT_PUBLIC_ASSETS, r as buildControlUiRootAssetPath, t as CONTROL_UI_BUILD_ID_ATTRIBUTE } from "./control-ui-root-assets-DCkhn9fm.mjs";
import "./control-ui-contract-DTmt_Jww.mjs";
import { n as resolveEffectiveToolFsWorkspaceOnly } from "./tool-fs-policy-dDd9W7xo.mjs";
import { a as DEFAULT_ASSISTANT_IDENTITY, c as resolveAssistantIdentityAvatar, i as resolveGatewayAssistantAvatar, n as gatewayAssistantAvatarUrl, r as prepareGatewayAssistantAvatar, s as resolveAssistantIdentity, t as controlUiAvatarResolutionMeta } from "./assistant-avatar-DjDH3za_.mjs";
import { t as resolveSessionWorkspaceRoots } from "./session-workspace-roots-BBOKk2gF.mjs";
import { d as selectControlUiRoutePreloads, u as controlUiPreloadLinks } from "./control-ui-assets-DgSDpYwf.mjs";
import { i as respondPlainText, n as isReadHttpMethod, r as respondNotFound } from "./control-ui-http-utils-DH5C3tE0.mjs";
import { a as resolveControlUiAssetEncodings, c as respondControlUiNotAcceptable, d as sendControlUiHtmlBody, f as serveControlUiAsset, i as isControlUiStaticAssetExtension, l as respondControlUiNotModified, n as readControlUiRootAsset, o as resolveControlUiHtmlEncoding, r as isControlUiFileUnmodified, s as resolveControlUiRepresentation, u as respondHeadForControlUiFile } from "./server-control-ui-root-DHOn05WY.mjs";
import { n as isControlUiApprovalDocumentPath, t as classifyControlUiRequest } from "./control-ui-routing-X6jysl9I.mjs";
import { r as serveControlUiShareDocument, t as isControlUiSharePath } from "./control-ui-share-V2WSYnX0.mjs";
import { t as isTerminalConfigEnabled } from "./enabled-B07Lihbx.mjs";
import { t as sendJson$1 } from "./http-json-ddGJz5CA.mjs";
import { o as resolveSandboxPathMapping, r as relativePathInsideSandboxRoot } from "./path-policy-CyYRyWre.mjs";
import { t as splitMediaFromOutput } from "./parse-CBUOvLUG.mjs";
import { i as getDefaultMediaLocalRoots, n as getAgentScopedMediaLocalRoots } from "./local-roots-BTz6ULME.mjs";
import { o as extractOriginalFilename } from "./store-zsTAVy24.mjs";
import { i as resolveMediaReferenceLocalPathInfo } from "./media-reference-DDon-yG0.mjs";
import { n as LocalMediaAccessError, r as assertLocalMediaAllowed } from "./local-media-access-D6Qr0fZd.mjs";
import { l as readSessionWorkerPlacementAsync } from "./session-placement-lifecycle-3XCQYoeM.mjs";
import { o as readSessionMessageByIdAsync } from "./session-transcript-readers-D1WqgwbF.mjs";
import { i as resolvePlaybackTranscode, n as replacePlaybackFileExtension, r as resolvePlaybackMetadataForSource, t as PlaybackInspectionBusyError } from "./playback-transcode-bt6dS8Ae.mjs";
import { n as normalizeChatImageRenditionWidth } from "./chat-image-renditions-swq0mtjT.mjs";
import { r as resolveAssistantMediaFilename, t as buildAssistantMediaContentDisposition } from "./assistant-media-content-disposition-y--dAvCz.mjs";
import { i as writeByteHeaders, r as resolveByteResponse, t as createGatewayByteStream } from "./http-byte-range-D1yrfDRK.mjs";
import { _ as resolveHttpProfile, g as prepareHttpUserProfileCatalog, h as applyHttpOperatorRoleScopeCeiling, t as authorizeControlUiReadRequestOrReply } from "./http-auth-utils-B0FI4CE4.mjs";
import "./http-utils-B5V9Okzh.mjs";
import { r as applyHttpImageContentSecurityPolicy, s as sendHttpImageResponse } from "./http-image-response-BMmTktPR.mjs";
import { t as resolveSessionWorkerPlacementContext } from "./session-worker-placement-context-CQyX2P4h.mjs";
import { n as projectPendingInputMessage } from "./chat-pending-inputs-Dxwqhxeq.mjs";
import { n as buildControlUiCspHeader, r as computeInlineScriptHashes, t as applyControlUiSecurityHeaders } from "./control-ui-csp-CRnas4cD.mjs";
import fs from "node:fs";
import path from "node:path";
import { createHmac, randomBytes } from "node:crypto";
import fs$1 from "node:fs/promises";
import { performance } from "node:perf_hooks";
import { readFileWindowFully, safeFileURLToPath } from "@openclaw/fs-safe/advanced";
import { isWithinDir } from "@openclaw/fs-safe/path";
//#region src/gateway/assistant-media-policy.ts
function assertAssistantMediaPolicyCurrent(e, t, n, r) {
	t.assertCurrent?.();
	const i = resolvePreparedAssistantMediaPolicy({
		...e,
		reader: t.reader
	}, t.readSession(), t.readSession, t.assertCurrent);
	if (i?.session) {
		const e = t.placementRead ? t.placementRead.current() : resolveSessionWorkerPlacementContext().workerSessionPlacementService?.getMany([i.session.sessionId]).get(i.session.sessionId);
		i.remote ||= isCloudWorkerPlacementState(e?.state);
	}
	if (r?.hasCurrentClientAuthority?.() === false || !i || i.session?.sessionKey !== t.session?.sessionKey || i.session?.agentId !== t.session?.agentId || i.session?.sessionId !== t.session?.sessionId || i.messageId !== t.messageId || i.remote !== t.remote || i.executionCwd !== t.executionCwd || i.sandboxWorkspace?.hostRoot !== t.sandboxWorkspace?.hostRoot || i.sandboxWorkspace?.containerRoot !== t.sandboxWorkspace?.containerRoot || i.sandboxWorkspace?.worktreeId !== t.sandboxWorkspace?.worktreeId || i.sandboxWorkspace?.lifecycleRevision !== t.sandboxWorkspace?.lifecycleRevision || i.workspaceOnly !== t.workspaceOnly || i.localRoots.length !== t.localRoots.length || i.localRoots.some((e, n) => e !== t.localRoots[n]) || n && t.workspaceOnly && !i.canAllow) throw new FsSafeError("path-mismatch", "Media access changed");
	return i;
}
function resolveAssistantMediaReaderAuth(e, t, n) {
	try {
		const r = e.profileId ? resolveHttpProfile(captureResidentUserProfileAccess(e.profileId).assertCurrent().id, t) : void 0;
		const i = applyHttpOperatorRoleScopeCeiling(e.operatorScopes, r);
		if (!authorizeOperatorScopesForMethod(n ? "chat.message.get" : "assistant.media.get", i).allowed) return;
		return {
			authMethod: e.authMethod,
			operatorScopes: i,
			...r
		};
	} catch {
		return;
	}
}
async function resolveAssistantMediaSessionPolicy(e) {
	let t;
	let readSession = () => t;
	let assertCurrent;
	let n;
	let r;
	try {
		if (e.sessionKey) {
			const r = resolveRequestedSessionAgentId(e.config, e.sessionKey, e.agentId);
			if (!r.ok) return;
			const i = normalizeSessionKeyPreservingOpaquePeerIds(e.sessionKey);
			const a = captureSessionEntryMetadataRead({
				sessionKey: i,
				agentId: r.agentId
			}, () => {
				if (e.requestAuth?.hasCurrentClientAuthority?.() === false) throw new FsSafeError("path-mismatch", "Media access changed");
			});
			if (a) {
				assertCurrent = a.assertCurrent;
				readSession = () => ({
					cfg: readRuntimeConfig(),
					agentId: r.agentId,
					canonicalKey: i,
					entry: a.readCurrent()
				});
				t = readSession();
			} else {
				const { retainGatewaySessionEntryReadOnly: i } = await import("./session-utils-read-lifetime-D91327b1.mjs");
				const a = await i(e.sessionKey, r.agentId, () => true, readRuntimeConfig(), { exactRead: true });
				n = a.release;
				assertCurrent = () => {
					if (!a.isCurrentAtResponse()) throw new FsSafeError("path-mismatch", "Media access changed");
				};
				readSession = () => {
					assertCurrent?.();
					return {
						...a,
						cfg: readRuntimeConfig(),
						entry: a.readRetainedEntry()
					};
				};
				t = readSession();
			}
			if (!t?.entry?.sessionId) return;
		}
		r = resolvePreparedAssistantMediaPolicy(e, t, readSession, assertCurrent);
		return r && {
			...r,
			releaseSession: n
		};
	} finally {
		if (!r) n?.();
	}
}
function resolvePreparedAssistantMediaPolicy(e, t, n, r) {
	if (e.sessionKey && !t?.entry?.sessionId) return;
	const i = t?.cfg ?? e.config;
	const a = e.reader ?? (e.requestAuth ? {
		authMethod: e.requestAuth.authMethod,
		operatorScopes: e.requestAuth.operatorScopes,
		...e.requestAuth.authenticatedUserProfile ? { profileId: e.requestAuth.authenticatedUserProfile.profileId } : {}
	} : void 0);
	const o = e.requestAuth ?? (a ? resolveAssistantMediaReaderAuth(a, i, Boolean(e.sessionKey && e.messageId)) : void 0);
	if (!o || !a) return;
	const s = authorizeOperatorScopesForMethod("assistant.media.get", o.operatorScopes).allowed;
	const c = s ? void 0 : e.messageId;
	if (!s && (!c || !t || !authorizeOperatorScopesForMethod("chat.message.get", o.operatorScopes).allowed)) return;
	const l = t?.agentId ?? e.agentId;
	const u = t?.entry;
	const d = Boolean(u?.execNode || u?.repositoryWorkspaceId || u?.deviceFolder);
	let f;
	let p;
	let m;
	let h;
	if (t && u && l) {
		if (!o.operatorScopes.includes("operator.admin")) {
			const e = o.authenticatedUserProfile?.profileId;
			if (e && e !== "gateway-owner") {
				if (u.incognito || isIncognitoSessionKey(t.canonicalKey)) return;
				if ((o.operatorRolePolicy || c) && !createProfileSessionEntryFilter({
					profileId: e,
					sessionCap: o.operatorRolePolicy?.sessions.others
				})(t.canonicalKey, u)) return;
			} else if (!e && i.gateway?.roles) return;
		}
		f = {
			sessionKey: t.canonicalKey,
			agentId: l,
			sessionId: u.sessionId
		};
		if (!d) {
			const e = resolveSessionWorkspaceRoots(i, l, u);
			p = u.sessionRoot ?? e.root;
			m = e.diffCwd;
			if (u.worktree && p) {
				const e = resolvePreparedSandboxRuntimeStatus({
					cfg: i,
					agentId: l,
					sessionKey: t.canonicalKey,
					preparedSessionEntry: u
				});
				const n = resolveSandboxConfigForAgent(i, l);
				if (e.sandboxed && (n.backend === "docker" || n.backend === "podman")) h = {
					hostRoot: p,
					containerRoot: n.docker.workdir,
					worktreeId: u.worktree.id,
					lifecycleRevision: u.lifecycleRevision
				};
			}
		}
	}
	const g = !f || u?.sandbox === "required" || (u?.permissionMode ? resolveSessionPermissionCoreToolPolicy({ mode: u.permissionMode }).workspaceOnly : resolveEffectiveToolFsWorkspaceOnly({
		cfg: i,
		agentId: l
	}));
	const _ = [...d ? getDefaultMediaLocalRoots() : getAgentScopedMediaLocalRoots(i, l, g ? p : void 0)];
	if (p && !_.includes(p)) _.push(p);
	return {
		assertCurrent: r,
		readSession: n,
		messageId: c,
		session: f,
		executionCwd: m,
		sandboxWorkspace: h,
		remote: d,
		localRoots: _,
		workspaceOnly: g,
		reader: a,
		canAllow: o.operatorScopes.includes("operator.admin")
	};
}
async function resolveAssistantMediaPolicy(e) {
	const t = await resolveAssistantMediaSessionPolicy(e);
	if (!t) return;
	let releasePlacement;
	try {
		const e = t.session ? resolveSessionWorkerPlacementContext() : void 0;
		const n = t.session && e?.workerSessionPlacementService?.prepareSessionPlacement ? await e.workerSessionPlacementService.prepareSessionPlacement(t.session.sessionId) : void 0;
		releasePlacement = () => n?.release();
		if (t.session && e) {
			const r = n ? n.current() : await readSessionWorkerPlacementAsync({
				context: e,
				sessionId: t.session.sessionId
			});
			t.remote ||= isCloudWorkerPlacementState(r?.state);
		}
		return {
			...t,
			placementRead: n,
			release() {
				n?.release();
				t.releaseSession?.();
			}
		};
	} catch (e) {
		releasePlacement?.();
		t.releaseSession?.();
		throw e;
	}
}
const CONTROL_UI_ASSISTANT_MEDIA_TICKET_SCOPE = "assistant-media";
const CONTROL_UI_ASSISTANT_MEDIA_TICKET_TTL_MS = 3e5;
const controlUiAssistantMediaTicketSecret = randomBytes(32);
function signAssistantMediaTicketPayload(e) {
	return createHmac("sha256", controlUiAssistantMediaTicketSecret).update(e).digest("base64url");
}
/** Bind virtual paths to their current workspace without exposing its host path. */
function resolveAssistantMediaWorkspaceTicketKey(e, t) {
	const n = t.sandboxWorkspace;
	if (t.remote || !n || !resolveSandboxPathMapping([n], e)) return;
	return signAssistantMediaTicketPayload(JSON.stringify(n));
}
function createAssistantMediaTicket(e, t = Date.now()) {
	const n = asDateTimestampMs(t);
	if (n === void 0) return {};
	const r = asDateTimestampMs(n + CONTROL_UI_ASSISTANT_MEDIA_TICKET_TTL_MS);
	if (r === void 0) return {};
	const i = {
		scope: CONTROL_UI_ASSISTANT_MEDIA_TICKET_SCOPE,
		...e,
		exp: r
	};
	const a = Buffer.from(JSON.stringify(i), "utf8").toString("base64url");
	return {
		mediaTicket: `v1.${a}.${signAssistantMediaTicketPayload(a)}`,
		mediaTicketExpiresAt: resolveTimestampMsToIsoString(r)
	};
}
function verifyAssistantMediaTicket(e, t, n, r = Date.now()) {
	const i = asDateTimestampMs(r);
	if (i === void 0) return;
	const a = e?.split(".");
	if (!a || a.length !== 3 || a[0] !== "v1") return;
	const [, o, s] = a;
	if (!o || !s) return;
	const c = signAssistantMediaTicketPayload(o);
	if (!safeEqualSecret(s, c)) return;
	try {
		const e = Buffer.from(o, "base64url").toString("utf8");
		const r = JSON.parse(e);
		return r.scope === CONTROL_UI_ASSISTANT_MEDIA_TICKET_SCOPE && typeof r.source === "string" && (r.workspaceKey === void 0 || typeof r.workspaceKey === "string") && (t === void 0 || r.source === t) && r.agentId === n && typeof r.reader?.authMethod === "string" && Array.isArray(r.reader.operatorScopes) && (r.file === void 0 || typeof r.file?.realPath === "string" && typeof r.file.dev === "string" && typeof r.file.ino === "string") && typeof r.exp === "number" && Number.isFinite(r.exp) && r.exp >= i ? r : void 0;
	} catch {
		return;
	}
}
//#endregion
//#region src/gateway/control-ui-assistant-media-read.ts
function normalizeAssistantMediaSource(e) {
	const t = e.trim();
	if (!t) return null;
	if (/^file:/iu.test(t)) try {
		return safeFileURLToPath(t);
	} catch {
		return null;
	}
	if (t.startsWith("~")) return resolveUserPath(t);
	return t;
}
/** Keep relative sandbox references in their namespace for reads, association and tickets. */
function resolveAssistantMediaSource(e, t) {
	if (path.isAbsolute(e) || /^[a-z][a-z0-9+.-]*:/iu.test(e)) return e;
	if (t.remote || !t.executionCwd || !path.isAbsolute(t.executionCwd)) return null;
	const n = path.resolve(t.executionCwd, e);
	const r = t.sandboxWorkspace;
	if (!r) return n;
	const i = relativePathInsideSandboxRoot(r.hostRoot, n);
	return i === null ? null : path.posix.join(r.containerRoot, ...i.split(path.sep));
}
function sameAssistantMediaFile(e, t) {
	return e.realPath === t.realPath && e.dev === t.dev && e.ino === t.ino;
}
async function openAssistantMedia(e, t, n, r) {
	const i = t.sandboxWorkspace;
	const a = !t.remote && i ? resolveSandboxPathMapping([i], e) : null;
	const o = await resolveMediaReferenceLocalPathInfo(a?.hostPath ?? e);
	let s = i?.hostRoot;
	let c = r;
	let l = o.path;
	let u = t.localRoots;
	if (t.remote && o.kind === "local") throw new LocalMediaAccessError("invalid-path", "File is on another computer");
	if (i && o.kind === "local" && isPathInside$1(i.hostRoot, o.path)) {
		const { readLocalWorkspacePath: e } = await import("./local-workspace-read-DqKP3J8P.mjs");
		r();
		const n = await e({
			cwd: i.hostRoot,
			worktreeId: i.worktreeId,
			assertCurrent: r
		});
		if (a && n.worktreeId !== i.worktreeId) throw new LocalMediaAccessError("invalid-path", "Sandbox image backing is unavailable");
		s = n.root;
		c = n.assertCurrent;
		l = path.join(s, path.relative(i.hostRoot, o.path));
		u = t.localRoots.map((e) => e === i.hostRoot ? n.root : e);
	}
	let d = false;
	try {
		await assertLocalMediaAllowed(l, u);
	} catch (e) {
		if (!(e instanceof LocalMediaAccessError) || e.code !== "path-not-allowed") throw e;
		d = true;
		if (t.workspaceOnly && !n) throw e;
	}
	const f = await openLocalFileSafely({ filePath: l });
	try {
		let r = c;
		if (a && i && s) {
			if (!isPathInside$1(s, f.realPath)) throw new LocalMediaAccessError("invalid-path", "Sandbox image backing is unavailable");
			const { prepareLocalWorkspaceFileRead: t } = await import("./local-workspace-quiescence-Be30njub.mjs");
			r = await t({
				workspaceDir: s,
				containerRoot: i.containerRoot,
				targets: [e, path.posix.join(i.containerRoot, ...path.relative(s, f.realPath).split(path.sep))],
				assertCurrent: c
			});
		}
		let l;
		if (d && n) {
			const e = await f.handle.stat({ bigint: true });
			const r = {
				realPath: f.realPath,
				dev: e.dev.toString(),
				ino: e.ino.toString()
			};
			if (n === true || sameAssistantMediaFile(r, n)) l = r;
			else if (t.workspaceOnly) throw new LocalMediaAccessError("path-not-allowed", "Outside allowed folders");
		}
		if (!d) await assertLocalMediaAllowed(f.realPath, u);
		const p = Buffer.alloc(Math.min(f.stat.size, 8192));
		const m = p.length ? await readFileWindowFully(f.handle, p, 0) : 0;
		const h = p.subarray(0, m);
		const g = startsWithSvgRootElement(h.toString("utf8")) ? "image/svg+xml" : await detectMime({
			buffer: h,
			...d ? {} : { filePath: o.path }
		});
		if (d && kindFromMime(g) !== "image") throw new LocalMediaAccessError("unsupported-media-type", "Not an image");
		r();
		return {
			opened: f,
			reference: o,
			mimeType: g,
			outsideRoots: d,
			file: l,
			assertSourceCurrent: r
		};
	} catch (e) {
		await f.handle.close().catch(() => {});
		throw e;
	}
}
async function resolveAssistantMediaAvailability(e, t, n, r, i, a) {
	try {
		a();
		const { opened: o, mimeType: s, file: c, assertSourceCurrent: l } = await openAssistantMedia(e, t, n, a);
		await o[Symbol.asyncDispose]();
		const u = kindFromMime(s);
		const d = s && (u === "audio" || u === "video") ? await resolvePlaybackMetadataForSource({
			sourcePath: o.realPath,
			sourceStat: {
				size: o.stat.size,
				mtimeMs: o.stat.mtimeMs,
				ctimeMs: o.stat.ctimeMs,
				exactIdentity: o.exactIdentity
			},
			mimeType: s,
			kind: u,
			signal: i,
			assertCurrent: l
		}) : void 0;
		l();
		return {
			available: true,
			assertSourceCurrent: l,
			...s ? { mimeType: s } : {},
			sizeBytes: o.stat.size,
			...d,
			...createAssistantMediaTicket({
				source: e,
				workspaceKey: resolveAssistantMediaWorkspaceTicketKey(e, t),
				agentId: r,
				session: t.session,
				...t.messageId ? { messageId: t.messageId } : {},
				reader: t.reader,
				...c ? { file: c } : {}
			})
		};
	} catch (e) {
		if (e instanceof PlaybackInspectionBusyError) return {
			available: false,
			code: "attachment-unavailable",
			reason: e.message,
			retryable: true
		};
		if (e instanceof FsSafeError) switch (e.code) {
			case "not-found": return {
				available: false,
				code: "file-not-found",
				reason: "File not found"
			};
			case "not-file": return {
				available: false,
				code: "not-a-file",
				reason: "Not a file"
			};
			case "invalid-path":
			case "path-mismatch":
			case "symlink": return {
				available: false,
				code: "invalid-file",
				reason: "Invalid file"
			};
		}
		else if (e instanceof Error && "code" in e) {
			const t = e.code;
			switch (typeof t === "string" ? t : "") {
				case "unsupported-media-type": return {
					available: false,
					code: "unsupported-media-type",
					reason: "Not an image"
				};
				case "path-not-allowed": return {
					available: false,
					code: "outside-allowed-folders",
					reason: "Outside allowed folders"
				};
				case "invalid-file-url":
				case "invalid-path":
				case "unsafe-bypass":
				case "network-path-not-allowed":
				case "invalid-root": return {
					available: false,
					code: "blocked-local-file",
					reason: "Blocked local file"
				};
				case "not-found": return {
					available: false,
					code: "file-not-found",
					reason: "File not found"
				};
				case "not-file": return {
					available: false,
					code: "not-a-file",
					reason: "Not a file"
				};
			}
		}
		return {
			available: false,
			code: "attachment-unavailable",
			reason: "Attachment unavailable"
		};
	}
}
//#endregion
//#region src/gateway/control-ui-assistant-message-media.ts
function messageMediaSources(e) {
	const t = asOptionalRecord(e);
	if (!t) return [];
	const n = (readPersistedMediaFacts(t) ?? []).flatMap((e) => [e.url, e.path]);
	const r = t[ASSISTANT_DISPLAY_CONTENT_FIELD];
	const i = Array.isArray(r) ? r : t.content ?? t.text;
	const a = t.role === "assistant";
	const addDirectives = (e) => {
		n.push(...splitMediaFromOutput(extractCanvasShortcodes(e).text, { extractAudioDirectives: false }).mediaUrls ?? []);
	};
	if (a && typeof i === "string") addDirectives(i);
	for (const e of Array.isArray(i) ? i : []) {
		const t = asOptionalRecord(e);
		if (!t) continue;
		const r = asOptionalRecord(t.source);
		switch (t.type) {
			case "text":
			case "input_text":
			case "output_text":
				if (a && typeof t.text === "string") addDirectives(t.text);
				break;
			case "attachment":
				n.push(asOptionalRecord(t.attachment)?.url);
				break;
			case "image":
				n.push(t.url, t.openUrl, r?.url);
				break;
			case "image_url":
				n.push(asOptionalRecord(t.image_url)?.url);
				break;
			case "input_image":
				n.push(t.image_url, asOptionalRecord(t.image_url)?.url, r?.url);
				break;
			case "audio":
			case "video": n.push(t.url, r?.type === "url" ? r.url : void 0);
		}
	}
	return n.filter((e) => typeof e === "string");
}
function mediaIdentity(e, t) {
	const n = normalizeAssistantMediaSource(e);
	if (!n) return;
	const r = parseInboundMediaUri(buildInboundMediaUriFromPath(n) ?? n);
	if (r) return `media://inbound/${encodeURIComponent(r.id)}`;
	const i = resolveAssistantMediaSource(n, t);
	return i && path.isAbsolute(i) ? path.resolve(i) : void 0;
}
/** Bind narrow session readers to an existing visible message and its current media references. */
async function prepareAssistantMessageMedia(e, t, n) {
	if (!t.messageId) return async (e) => e();
	const r = t.messageId;
	const i = t.readSession();
	if (!i?.entry?.sessionId) throw new FsSafeError("path-mismatch", "Message attachment unavailable");
	const a = {
		agentId: i.readSource?.agentId ?? i.agentId,
		sessionKey: i.canonicalKey,
		sessionId: i.entry.sessionId,
		storePath: i.readSource?.path ?? i.storePath,
		sessionEntry: i.entry
	};
	const o = mediaIdentity(e, t);
	const assertAssociation = (e) => {
		n.throwIfAborted();
		if (!o || !messageMediaSources(e).some((e) => mediaIdentity(e, t) === o)) throw new FsSafeError("path-mismatch", "Message attachment unavailable");
	};
	if (r.startsWith("pending:")) {
		const e = r.slice(CHAT_PENDING_INPUT_MESSAGE_PREFIX.length);
		const project = (e) => e ? projectPendingInputMessage(e, MAX_PAYLOAD_BYTES, void 0, () => void 0) : void 0;
		assertAssociation(project(await readSessionPendingInput(a, e)));
		return async (t) => {
			let n = false;
			await readSessionPendingInput(a, e, (e) => {
				assertAssociation(project(e));
				t();
				n = true;
			});
			if (!n) throw new FsSafeError("path-mismatch", "Message attachment unavailable");
		};
	}
	const s = { entryIds: [r] };
	const c = (await readSessionTranscriptAnchorsAsync(a, s, n)).anchors[0];
	const l = c && await readSessionMessageByIdAsync(a, r, {
		currentOnly: true,
		maxBytes: 26214400,
		allowResetArchiveFallback: false,
		historyVisibility: {
			sessionStartedAt: i.entry.sessionStartedAt,
			requireVisible: true
		}
	}, n);
	if (!c || !l?.found || l.oversized) throw new FsSafeError("path-mismatch", "Message attachment unavailable");
	assertAssociation(l.message);
	return async (e) => {
		let t = false;
		await readSessionTranscriptAnchorsAsync(a, s, n, (n) => {
			if (!sameTranscriptEntryAnchor(c, n.anchors[0])) throw new FsSafeError("path-mismatch", "Message attachment changed");
			e();
			t = true;
		});
		if (!t) throw new FsSafeError("path-mismatch", "Message attachment changed");
	};
}
//#endregion
//#region src/infra/dev-install-branch.ts
const GIT_TIMEOUT_MS = 3e3;
const HIDDEN_BRANCHES = /* @__PURE__ */ new Set([
	"main",
	"master",
	"HEAD"
]);
async function detectDevInstallGitBranch(e) {
	const t = e ? path.resolve(e) : null;
	if (!t) return null;
	const n = await runCommandWithTimeout([
		"git",
		"-C",
		t,
		"rev-parse",
		"--show-toplevel"
	], {
		timeoutMs: GIT_TIMEOUT_MS,
		env: { GIT_NO_LAZY_FETCH: "1" }
	});
	if (n.code !== 0) return null;
	const r = await fs$1.realpath(t).catch(() => t);
	const i = n.stdout.trim();
	if (!i || path.resolve(i) !== path.resolve(r)) return null;
	const a = await runCommandWithTimeout([
		"git",
		"-C",
		t,
		"rev-parse",
		"--abbrev-ref",
		"HEAD"
	], {
		timeoutMs: GIT_TIMEOUT_MS,
		env: { GIT_NO_LAZY_FETCH: "1" }
	});
	if (a.code !== 0) return null;
	const o = a.stdout.trim();
	return o && !HIDDEN_BRANCHES.has(o) ? o : null;
}
let cached = null;
function resolveDevInstallGitBranch() {
	cached ??= resolveOpenClawPackageRoot({
		argv1: process.argv[1],
		cwd: process.cwd(),
		moduleUrl: import.meta.url
	}).then(detectDevInstallGitBranch).catch(() => null);
	return cached;
}
//#endregion
//#region src/gateway/control-ui-bootstrap-presentation.ts
/** Public presentation settings of the Gateway serving the UI, never model permissions. */
function resolveControlUiBootstrapPresentation(e) {
	const t = resolveIsConfigReadOnly();
	return {
		embedSandbox: e?.gateway?.controlUi?.embedSandbox ?? "scripts",
		allowExternalEmbedUrls: e?.gateway?.controlUi?.allowExternalEmbedUrls === true,
		automaticallyFetchFavicons: e?.gateway?.controlUi?.automaticallyFetchFavicons !== false,
		seamColor: e?.ui?.seamColor,
		environment: e?.gateway?.controlUi?.environment,
		configReadOnly: t,
		configReadOnlyNotice: t ? process.env.OPENCLAW_CONFIG_READONLY_NOTICE?.trim() || void 0 : void 0,
		chatBubblesEnabled: e?.gateway?.controlUi?.experimental?.chatBubbles === true,
		composerPredictionsEnabled: e?.gateway?.controlUi?.experimental?.composerPredictions?.enabled === true,
		communityInvite: e?.gateway?.controlUi?.communityInvite !== false,
		newSessionModelDefaults: e?.gateway?.controlUi?.newSessionModelDefaults ?? "last-used",
		uploadsEnabled: e?.gateway?.uploads?.enabled !== false
	};
}
//#endregion
//#region src/gateway/control-ui-bootstrap.ts
async function prepareControlUiBootstrapConfig(e, t, n, r, i, a = true, o) {
	let s = [];
	const c = await (async () => {
		try {
			var r = _usingCtx();
			r.u(o?.scope("auth_grants"));
			return await authorizeControlUiReadRequestOrReply({
				...n,
				req: e,
				res: t,
				cfg: n?.cfg ?? n?.config,
				replyOnFailure: a,
				requiredOperatorMethod: "sessions.list",
				onPluginFrameGrants: (e) => {
					s = e;
				}
			});
		} catch (e) {
			r.e = e;
		} finally {
			r.d();
		}
	})();
	if (!c) return null;
	c.assertCurrent();
	if (e.method === "HEAD") return {
		config: void 0,
		requestAuth: c
	};
	const l = n?.config;
	const [u, d, f, p] = await Promise.all([
		(async () => {
			try {
				var e = _usingCtx();
				e.u(o?.scope("identity_avatar"));
				const t = l ? await resolveAssistantIdentity({
					cfg: l,
					agentId: n?.agentId
				}) : void 0;
				const i = t ?? DEFAULT_ASSISTANT_IDENTITY;
				const a = l && t ? await resolveGatewayAssistantAvatar({
					cfg: l,
					identity: t,
					httpBasePath: r
				}) : {
					avatar: i.avatar,
					resolution: null
				};
				return {
					identity: i,
					agentId: t?.agentId,
					avatarProjection: a
				};
			} catch (t) {
				e.e = t;
			} finally {
				e.d();
			}
		})(),
		(async () => {
			try {
				var e = _usingCtx();
				e.u(o?.scope("plugin_catalog"));
				return await (authorizeOperatorScopesForMethod("plugins.controlUi.list", c.operatorScopes).allowed ? import("./control-ui-plugin-assets-ZUxE2s-C.mjs").then(({ listControlUiPluginCatalog: e }) => e().then(({ plugins: e }) => e, () => [])) : []);
			} catch (t) {
				e.e = t;
			} finally {
				e.d();
			}
		})(),
		(async () => {
			try {
				var e = _usingCtx();
				e.u(o?.scope("git_branch"));
				return await resolveDevInstallGitBranch();
			} catch (t) {
				e.e = t;
			} finally {
				e.d();
			}
		})(),
		(async () => {
			try {
				var e = _usingCtx();
				e.u(o?.scope("preferences"));
				return await import("./control-ui-bootstrap-preferences-4Zh87407.mjs").then(({ prepareControlUiBootstrapPreferences: e }) => e(l, c));
			} catch (t) {
				e.e = t;
			} finally {
				e.d();
			}
		})()
	]);
	const { identity: m, agentId: h, avatarProjection: g } = u;
	const _ = controlUiAvatarResolutionMeta(g.resolution);
	c.assertCurrent();
	return {
		config: {
			preferences: p,
			basePath: r,
			assistantName: m.name,
			assistantAvatar: g.avatar,
			assistantAvatarSource: _.avatarSource,
			assistantAvatarStatus: _.avatarStatus,
			assistantAvatarReason: _.avatarReason,
			...h ? { assistantAgentId: h } : {},
			serverVersion: resolveRuntimeServiceVersion(process.env),
			serverBuildId: l?.gateway?.controlUi?.root === void 0 ? resolveRuntimeServiceBuildId() ?? void 0 : void 0,
			devGitBranch: f ?? void 0,
			...resolveControlUiBootstrapPresentation(l),
			terminalEnabled: i,
			cliAgentsEnabled: l?.gateway?.cliAgents?.enabled !== false,
			pluginAssetsRequireAuth: n?.auth !== void 0 && n.auth.mode !== "none",
			pluginControlUiModules: d,
			pluginFrameGrants: s.map(({ pluginId: e, path: t, match: n }) => ({
				pluginId: e,
				path: t,
				match: n
			}))
		},
		requestAuth: c
	};
}
//#endregion
//#region src/gateway/control-ui-document-diagnostics.ts
/** Emit after delivery; parallel preparation stages overlap within the total. */
function startControlUiDocumentDiagnostics(e) {
	const t = createQueuedDiagnosticPhaseEmitter();
	if (!t) return;
	const n = [];
	return {
		scope(e) {
			const t = {
				name: `control-ui.document.${e}`,
				startedAt: performance.now()
			};
			n.push(t);
			return { [Symbol.dispose]() {
				t.endedAt ??= performance.now();
			} };
		},
		[Symbol.dispose]() {
			const r = performance.now();
			n.push({
				name: "control-ui.document.total",
				startedAt: e,
				endedAt: r
			});
			for (const e of n) {
				const n = e.endedAt ?? r;
				t({
					name: e.name,
					startedAt: performance.timeOrigin + e.startedAt,
					endedAt: performance.timeOrigin + n,
					durationMs: n - e.startedAt
				});
			}
		}
	};
}
//#endregion
//#region src/gateway/control-ui-index.ts
/** Anchors bundled assets before deep-linked documents begin preloading. */
function rewriteControlUiIndexHtmlAssetHrefs(e, t, n) {
	const r = normalizeControlUiBasePath(t);
	const i = /* @__PURE__ */ new Map([["src=\"./assets/", `src="${r}/assets/`], ["href=\"./assets/", `href="${r}/assets/`]]);
	for (const e of CONTROL_UI_ROOT_PUBLIC_ASSETS) {
		const t = n && isControlUiVersionedPublicAsset(e) ? `?v=${encodeURIComponent(n)}` : "";
		const a = `href="${buildControlUiRootAssetPath(r, e)}${t}"`;
		i.set(`href="./${e}"`, a);
		i.set(`href="/${e}"`, a);
		i.set(`href="${buildControlUiRootAssetPath(r, e)}"`, a);
	}
	const a = new RegExp(Array.from(i.keys(), escapeRegExp).join("|"), "g");
	return e.replace(a, (e) => i.get(e) ?? e);
}
async function serveControlUiIndexHtml(e, t, n, r, i, a, o, s, c, l, u = false, d) {
	const f = getRemoteControlUiIngressContext(e);
	const p = normalizeControlUiBasePath(i);
	const m = r === "/chat" || r.startsWith("/chat/") ? "chat" : r === "/new" || r === "/new/" ? "new" : null;
	const h = rewriteControlUiIndexHtmlAssetHrefs(selectControlUiRoutePreloads(n, m), p, s);
	const g = ` ${CONTROL_UI_BASE_PATH_ATTRIBUTE}="${escapeHtml(p)}"`;
	const _ = d ? ` ${CONTROL_UI_BOOTSTRAP_CONFIG_ATTRIBUTE}="${escapeHtml(JSON.stringify(d))}"` : "";
	const v = o ? ` ${CONTROL_UI_ENVIRONMENT_ATTRIBUTE}="${escapeHtml(JSON.stringify(o))}"` : "";
	const y = s ? ` ${CONTROL_UI_BUILD_ID_ATTRIBUTE}="${escapeHtml(s)}"` : "";
	const b = h.replace(/<html\b[^>]*>/i, (e) => e.replace(new RegExp(`\\s${CONTROL_UI_BUILD_ID_ATTRIBUTE}="[^"]*"`, "g"), "").replace(/<html\b/i, () => `<html${g}${f ? " data-openclaw-remote-ingress=\"true\"" : ""}${u ? " data-openclaw-proxy-session-entry=\"true\"" : ""} ${CONTROL_UI_TERMINAL_ENABLED_ATTRIBUTE}="${a === true}"${v}${y}${_}`));
	const x = c ? b.replace(/<head\b[^>]*>/i, (e) => `${e}<script>history.replaceState(null,"",${JSON.stringify(c).replaceAll("<", "\\u003c")}+location.hash);<\/script>`) : b;
	const S = computeInlineScriptHashes(x);
	if (f) assertRemoteControlUiIngressCurrent(f);
	t.setHeader("Content-Security-Policy", buildControlUiCspHeader({
		inlineScriptHashes: S,
		allowWasm: a,
		portalHost: e.headers.host,
		frameAncestors: f?.frameAncestors
	}));
	t.setHeader("Content-Type", "text/html; charset=utf-8");
	t.setHeader("Cache-Control", d ? "private, no-store" : c ? "no-store" : "no-cache");
	const C = controlUiPreloadLinks(h);
	if (C.length && (!l || l())) t.setHeader("Link", C);
	await sendControlUiHtmlBody(e, t, x, l);
}
//#endregion
//#region src/gateway/control-ui.ts
const ROOT_PREFIX = "/";
const CONTROL_UI_ASSETS_MISSING_MESSAGE = "Control UI assets not found. Build them with `pnpm ui:build` (auto-installs UI deps), or run `pnpm ui:dev` during development.";
const loadAvatarThumbnail = createLazyRuntimeModule(() => import("./assistant-avatar-thumbnail.runtime.js"));
const CONTROL_UI_NAMESPACE_PREFIX = "/__openclaw__/";
function sendJson(e, t, n) {
	e.setHeader("Cache-Control", "no-cache");
	sendJson$1(e, t, n);
}
function respondControlUiAssetsUnavailable(e, t) {
	const n = t?.kind === "preparing" ? "Control UI assets are being prepared. Try again shortly." : t?.kind === "failed" ? "Control UI assets could not be prepared. Check the Gateway logs or run `openclaw doctor --fix`." : t?.kind === "invalid" && t.path ? `Control UI assets not found at ${t.path}. Build them with \`pnpm ui:build\` (auto-installs UI deps), or update gateway.controlUi.root.` : CONTROL_UI_ASSETS_MISSING_MESSAGE;
	if (t?.kind === "preparing") {
		e.setHeader("Cache-Control", "no-store");
		e.setHeader("Retry-After", "1");
	}
	respondPlainText(e, 503, n);
}
function isValidAgentPathSegment(e) {
	return /^[a-z0-9][a-z0-9_-]{0,63}$/i.test(e);
}
async function handleControlUiAssistantMediaRequest(e, t, n) {
	try {
		var r = _usingCtx();
		const i = e.url;
		if (!i) return false;
		const a = new URL(i, "http://localhost");
		if (a.pathname !== resolveAssistantMediaRoutePath(n?.basePath)) return false;
		const o = a.searchParams.get("meta") === "1";
		const s = e.method === "POST" && o && a.searchParams.get("allow") === "1";
		if (!isReadHttpMethod(e.method) && !s) return false;
		applyControlUiSecurityHeaders(t, getRemoteControlUiIngressContext(e));
		let c = normalizeAssistantMediaSource(a.searchParams.get("source") ?? "");
		if (!c) {
			respondNotFound(t);
			return true;
		}
		const l = a.searchParams.get("sessionKey")?.trim() || void 0;
		const u = l ? a.searchParams.get("messageId")?.trim() || void 0 : void 0;
		const d = l ? a.searchParams.get("agentId")?.trim() || void 0 : n?.agentId;
		const f = !path.isAbsolute(c) && !/^[a-z][a-z0-9+.-]*:/iu.test(c);
		const p = verifyAssistantMediaTicket(a.searchParams.get("mediaTicket"), f ? void 0 : c, d);
		const m = getRemoteControlUiIngressContext(e);
		if (p?.reader.authMethod === "remote-ingress" && !m) {
			respondNotFound(t);
			return true;
		}
		const h = Boolean(m) || o || !p;
		const g = h ? await authorizeControlUiReadRequestOrReply({
			...n,
			req: e,
			res: t,
			cfg: n?.cfg ?? n?.config,
			allowQueryToken: !s,
			requiredOperatorMethod: u ? "chat.message.get" : "assistant.media.get"
		}) : void 0;
		if (h && !g) return true;
		if (m && p && p.reader.profileId !== g?.authenticatedUserProfile?.profileId) {
			respondNotFound(t);
			return true;
		}
		if (g?.authenticatedUserProfile?.profileId || !o && p?.reader.profileId) {
			if (!await prepareHttpUserProfileCatalog(t) || g?.hasCurrentClientAuthority?.() === false || !o && p && !verifyAssistantMediaTicket(a.searchParams.get("mediaTicket"), f ? void 0 : c, d)) {
				if (!t.destroyed && !t.writableEnded) respondNotFound(t);
				return true;
			}
		}
		const _ = {
			config: n?.config ?? {},
			sessionKey: l,
			agentId: d,
			messageId: u
		};
		const v = await resolveAssistantMediaPolicy({
			..._,
			requestAuth: g ?? void 0,
			reader: o || m ? void 0 : p?.reader
		});
		if (!v) {
			respondNotFound(t);
			return true;
		}
		const y = r.u({
			...v,
			[Symbol.dispose]: () => v.release()
		});
		const b = resolveAssistantMediaSource(c, v);
		if (!b) {
			respondNotFound(t);
			return true;
		}
		c = b;
		const x = p?.source === c ? p : void 0;
		if (s && !v.canAllow) {
			sendJson(t, 403, { error: "Allowing an outside image requires operator.admin" });
			return true;
		}
		const S = x && x.session?.sessionKey === v.session?.sessionKey && x.session?.agentId === v.session?.agentId && x.session?.sessionId === v.session?.sessionId && x.messageId === v.messageId && x.workspaceKey === resolveAssistantMediaWorkspaceTicketKey(c, v);
		if (!o && a.searchParams.has("mediaTicket") && (!x || !S)) {
			respondNotFound(t);
			return true;
		}
		const C = s ? true : x?.file && S && v.canAllow ? x.file : void 0;
		const assertCurrentPolicy = () => {
			assertRemoteControlUiIngressCurrent(getRemoteControlUiIngressContext(e));
			return assertAssistantMediaPolicyCurrent(_, y, Boolean(C), g ?? void 0);
		};
		const w = createHttpRequestAbortSignal(t.req, t);
		r.u({ [Symbol.dispose]: w.cleanup });
		let T;
		try {
			assertCurrentPolicy();
			T = await prepareAssistantMessageMedia(c, v, w.signal);
			assertCurrentPolicy();
		} catch {
			respondNotFound(t);
			return true;
		}
		const publishResponse = (e) => T(() => {
			assertCurrentPolicy();
			e();
		});
		if (o) {
			const { assertSourceCurrent: e, ...n } = await resolveAssistantMediaAvailability(c, v, C, d, w.signal, assertCurrentPolicy);
			if (w.signal.aborted) return true;
			try {
				await publishResponse(() => {
					e?.();
					sendJson(t, 200, !n.available && n.code === "outside-allowed-folders" ? {
						...n,
						retryable: false,
						...v.canAllow ? { canAllow: true } : {}
					} : n);
				});
			} catch {
				respondNotFound(t);
			}
			return true;
		}
		let E;
		try {
			const n = await openAssistantMedia(c, v, C, assertCurrentPolicy);
			let r = n.opened;
			E = createGatewayByteStream(t, r.handle, () => respondNotFound(t));
			let i = n.mimeType ?? "application/octet-stream";
			let o = n.reference.kind === "inbound" ? resolveAssistantMediaFilename(extractOriginalFilename(n.reference.path), a.searchParams.get("filename")) : path.basename(n.reference.path);
			const s = kindFromMime(i);
			if (n.reference.kind === "inbound" && s === "image" && a.searchParams.get("variant") === "thumbnail") {
				const { readImageThumbnailFromFile: n } = await import("./managed-image-thumbnail-cache-BPyoGIsY.mjs");
				const i = await n(r, void 0, normalizeChatImageRenditionWidth(a.searchParams.get("width")));
				await E.close();
				await publishResponse(() => {
					t.setHeader("Content-Type", "image/webp");
					t.setHeader("Content-Length", String(i.byteLength));
					t.setHeader("Cache-Control", "private, no-cache");
					t.setHeader("Content-Disposition", buildAssistantMediaContentDisposition(`${o}-preview.webp`, "image/webp"));
					t.end(e.method === "HEAD" ? void 0 : i);
				});
				return true;
			}
			if (a.searchParams.get("playback") === "1" && (s === "audio" || s === "video")) {
				const e = await resolvePlaybackTranscode({
					sourcePath: r.realPath,
					sourceStat: {
						size: r.stat.size,
						mtimeMs: r.stat.mtimeMs,
						ctimeMs: r.stat.ctimeMs,
						exactIdentity: r.exactIdentity
					},
					mimeType: i,
					kind: s,
					signal: E.signal,
					assertCurrent: assertCurrentPolicy
				});
				if (e.kind === "preparing") {
					await E.close();
					await publishResponse(() => sendJson(t, 202, { status: "preparing" }));
					return true;
				}
				if (e.kind === "transcoded") {
					const n = await openLocalFileSafely({ filePath: e.path }).catch(() => null);
					if (n) {
						await E.close();
						r = n;
						E = createGatewayByteStream(t, r.handle, () => respondNotFound(t));
						i = e.contentType;
						o = replacePlaybackFileExtension(o, e.extension);
					}
				}
			}
			const l = resolveByteResponse({
				file: { size: r.stat.size },
				method: e.method,
				request: e
			});
			const u = e.method === "HEAD" || l.kind === "not-modified" || l.contentLength === 0;
			if (u) await E.close();
			let d;
			const f = E;
			await publishResponse(() => {
				n.assertSourceCurrent();
				if (s === "image") applyHttpImageContentSecurityPolicy(t);
				t.setHeader("Content-Type", i);
				t.setHeader("Content-Disposition", buildAssistantMediaContentDisposition(o, i));
				t.setHeader("Cache-Control", "no-cache");
				writeByteHeaders(t, l);
				if (u) t.end();
				else d = f.pipe(l, e.method);
			});
			await d;
			return true;
		} catch {
			await E?.close();
			if (!t.destroyed && !t.writableEnded) respondNotFound(t);
			return true;
		}
	} catch (e) {
		r.e = e;
	} finally {
		r.d();
	}
}
async function handleControlUiAvatarRequest(e, t, n) {
	const r = e.url;
	if (!r) return false;
	if (!isReadHttpMethod(e.method)) return false;
	const i = new URL(r, "http://localhost");
	const a = normalizeControlUiBasePath(n.basePath);
	const o = i.pathname;
	const s = parseControlUiResourcePath("agentAvatar", o, a);
	if (!s.matched) return false;
	applyControlUiSecurityHeaders(t, getRemoteControlUiIngressContext(e));
	const c = s.value;
	if (!c || !isValidAgentPathSegment(c)) {
		respondNotFound(t);
		return true;
	}
	const l = await authorizeControlUiReadRequestOrReply({
		...n,
		req: e,
		res: t,
		cfg: n.cfg ?? n.config
	});
	if (!l) return true;
	l.assertCurrent();
	try {
		const r = await resolveAssistantIdentityAvatar({
			cfg: n.config,
			agentId: c
		});
		const o = await prepareGatewayAssistantAvatar({
			cfg: n.config,
			identity: r,
			readBody: i.searchParams.get("meta") !== "1" && (e.method !== "HEAD" || i.searchParams.has("v"))
		});
		l.assertCurrent();
		const s = o.resolution;
		if (i.searchParams.get("meta") === "1") {
			sendJson(t, 200, {
				avatarUrl: gatewayAssistantAvatarUrl(o, a, c) ?? (s?.kind === "remote" ? s.url : null),
				...controlUiAvatarResolutionMeta(s)
			});
			return true;
		}
		if ((i.searchParams.has("v") || s?.kind === "data") && o.image) {
			const n = await (await loadAvatarThumbnail()).readGatewayAvatarThumbnail(o.image);
			l.assertCurrent();
			t.setHeader("vary", "Authorization, Cookie");
			sendHttpImageResponse({
				req: e,
				res: t,
				image: n,
				filename: "avatar",
				cacheControl: i.searchParams.get("v") === o.image.revision ? "private, max-age=31536000, immutable" : "private, no-cache"
			});
			return true;
		}
		if (s?.kind !== "local" || !o.file) {
			t.setHeader("Cache-Control", "private, max-age=60");
			t.setHeader("Vary", "Authorization, Cookie");
			respondNotFound(t);
			return true;
		}
		t.setHeader("Content-Type", resolveAvatarMime(o.file.path));
		t.setHeader("Cache-Control", "no-cache");
		if (e.method === "HEAD") {
			t.statusCode = 200;
			t.setHeader("Content-Length", String(o.file.stat.size));
			t.end();
			return true;
		}
		t.end(o.file.body);
		return true;
	} catch {
		if (!t.writableEnded && !t.destroyed) {
			l.assertCurrent();
			respondNotFound(t);
		}
		return true;
	}
}
function isExpectedSafePathError(e) {
	const t = typeof e === "object" && e !== null && "code" in e ? String(e.code) : "";
	return t === "ENOENT" || t === "ENOTDIR" || t === "ELOOP";
}
function isSafeRelativePath(e) {
	if (!e) return false;
	const t = path.posix.normalize(e);
	return !(path.posix.isAbsolute(t) || path.win32.isAbsolute(t) || t.startsWith("../") || t === ".." || t.includes("\0"));
}
async function handleControlUiHttpRequest(e, t, n) {
	const r = performance.now();
	const i = e.url;
	if (!i) return false;
	const a = new URL(i, "http://localhost");
	const o = normalizeControlUiBasePath(n?.basePath);
	const s = a.pathname;
	const c = n?.terminalEnabled ?? isTerminalConfigEnabled(n?.config);
	const l = classifyControlUiRequest({
		basePath: o,
		pathname: s,
		search: a.search,
		method: e.method,
		accept: e.headers?.accept
	});
	if (l.kind === "not-control-ui") return false;
	if (l.kind === "not-found") {
		applyControlUiSecurityHeaders(t, getRemoteControlUiIngressContext(e));
		respondNotFound(t);
		return true;
	}
	if (l.kind === "redirect") {
		applyControlUiSecurityHeaders(t, getRemoteControlUiIngressContext(e));
		t.statusCode = 302;
		t.setHeader("Location", l.location);
		t.end();
		return true;
	}
	applyControlUiSecurityHeaders(t, getRemoteControlUiIngressContext(e));
	if (isControlUiSharePath(s, o) && s !== `${o}/share/card.png` && s !== `${o}/share/preview-v1.mp4`) {
		serveControlUiShareDocument(e, t, a, o, resolveGatewayPublicOrigin(n?.config));
		return true;
	}
	if (matchesControlUiBootstrapConfigPath(s, o)) {
		const r = await prepareControlUiBootstrapConfig(e, t, n, o, c);
		if (r) {
			r.requestAuth.assertCurrent();
			sendJson(t, 200, r.config);
		}
		return true;
	}
	const u = n?.root;
	if (!u || u.kind !== "bundled" && u.kind !== "resolved") {
		respondControlUiAssetsUnavailable(t, u);
		return true;
	}
	const d = u.path;
	if (!(u.realPath || await fs.promises.realpath(d).catch((e) => {
		if (isExpectedSafePathError(e)) return null;
		throw e;
	}))) {
		respondControlUiAssetsUnavailable(t);
		return true;
	}
	const f = o && s.startsWith(`${o}/`) ? s.slice(o.length) : s;
	const p = isControlUiApprovalDocumentPath({
		basePath: o,
		pathname: s
	}) || isControlUiFocusPath(s, o);
	const m = (() => {
		if (f === "/share/card.png") return "social-card.png";
		if (f === "/share/preview-v1.mp4") return "social-preview-v1.mp4";
		if (f === ROOT_PREFIX) return "";
		if (f.startsWith(CONTROL_UI_NAMESPACE_PREFIX)) {
			const e = f.slice(14);
			if (isControlUiRootPublicAsset(e)) return e;
		}
		const e = f.indexOf("/assets/");
		if (e >= 0) return f.slice(e + 1);
		return f.slice(1);
	})();
	const h = p ? "index.html" : m && !m.endsWith("/") ? m : `${m}index.html`;
	let g;
	try {
		g = decodeURIComponent(h);
	} catch {
		respondNotFound(t);
		return true;
	}
	if (!isSafeRelativePath(g)) {
		respondNotFound(t);
		return true;
	}
	const _ = path.resolve(d, g);
	if (!isWithinDir(d, _)) {
		respondNotFound(t);
		return true;
	}
	const v = u.kind === "bundled";
	if (v && [".br", ".gz"].includes(path.extname(g).toLowerCase())) {
		respondNotFound(t);
		return true;
	}
	const y = v && g.startsWith("assets/");
	const b = v ? u.publicAssetBuildId : void 0;
	const x = y || Boolean(b && a.searchParams.get("v") === b && isControlUiVersionedPublicAsset(g));
	const S = e.method !== "HEAD" && e.headers?.["if-none-match"] === void 0 && e.headers?.["if-modified-since"] === void 0;
	const C = resolveControlUiAssetEncodings({
		req: e,
		contentPath: g,
		precompressed: y
	});
	let w = await readControlUiRootAsset(u, g, S, C);
	if (!w) {
		if (isControlUiStaticAssetExtension(path.extname(g).toLowerCase())) {
			respondNotFound(t);
			return true;
		}
		if (!l.spaFallback) return false;
		if (_ !== path.resolve(d, "index.html")) {
			g = "index.html";
			w = await readControlUiRootAsset(u, g, S, C);
		}
	}
	while (w) {
		if (path.basename(g) === "index.html" || path.basename(w.file.path) === "index.html") try {
			var T = _usingCtx();
			if (e.method === "HEAD") try {
				var E = _usingCtx();
				const n = E.u(startControlUiDocumentDiagnostics(r));
				E.u(n?.scope("render"));
				const i = resolveControlUiHtmlEncoding(e);
				if (i === "not-acceptable") {
					respondControlUiNotAcceptable(t);
					return true;
				}
				respondHeadForControlUiFile(t, "index.html", { encoding: i === "identity" ? void 0 : i });
				return true;
			} catch (e) {
				E.e = e;
			} finally {
				E.d();
			}
			if (!w.file.body) {
				w = await readControlUiRootAsset(u, g, true);
				continue;
			}
			const i = T.u(startControlUiDocumentDiagnostics(r));
			const a = n?.auth ? await prepareControlUiBootstrapConfig(e, t, n, o, c, false, i) : void 0;
			T.u(i?.scope("render"));
			await serveControlUiIndexHtml(e, t, w.file.body.toString("utf8"), f, o, c, n?.config?.gateway?.controlUi?.environment, b, n?.sessionEntryPath, () => a?.requestAuth.hasCurrentClientAuthority() !== false && n?.isSessionEntryCurrent?.() !== false, n?.auth?.mode === "trusted-proxy", a?.config);
			return true;
		} catch (e) {
			T.e = e;
		} finally {
			T.d();
		}
		const i = Date.now();
		const a = Math.floor(Math.min(w.file.mtimeMs, i) / 1e3) * 1e3;
		const s = resolveControlUiRepresentation(w, C);
		if (!s) {
			respondControlUiNotAcceptable(t);
			return true;
		}
		if (isControlUiFileUnmodified(e, a, i)) {
			respondControlUiNotModified(t, {
				immutable: x,
				lastModifiedMs: a
			});
			return true;
		}
		const l = {
			immutable: x,
			encoding: s.encoding,
			lastModifiedMs: a
		};
		if (e.method === "HEAD") respondHeadForControlUiFile(t, g, {
			...l,
			contentLength: s.file.size
		});
		else if (s.file.body) serveControlUiAsset(t, g, s.file.body, l);
		else {
			w = await readControlUiRootAsset(u, g, true, C);
			continue;
		}
		return true;
	}
	respondNotFound(t);
	return true;
}
//#endregion
export { handleControlUiAssistantMediaRequest, handleControlUiAvatarRequest, handleControlUiHttpRequest };