openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,116 lines (1,115 loc) • 43.8 kB
JavaScript
import { l as asNonNegativeFiniteNumber } from "./number-coercion-D6u-4YD8.mjs";
import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs";
import { a as extractErrorCode } from "./error-coercion-hDrHOSGy.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import "./paths-DAcAg5aV.mjs";
import { h as readLocalFileSafely, u as openLocalFileSafely } from "./fs-safe-BbWvmdVn.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import { r as isIncognitoSessionKey } from "./session-key-DW1jcHbM.mjs";
import { j as parseAgentSessionKey, k as normalizeSessionKeyPreservingOpaquePeerIds } from "./session-key-CqAyZeVk.mjs";
import { i as assertExistingDatabaseIdentity } from "./sqlite-worker-identity-BH8ZkJU9.mjs";
import { r as hasSqliteWorkerOutcomeUnknown } from "./sqlite-worker-error-DEIJgRIz.mjs";
import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { t as SessionMetadataUnavailableError } from "./session-metadata-unavailable-error-ClU33Nog.mjs";
import "./sqlite-worker-contract--dxXkOty.mjs";
import { r as captureOpenClawStateWorkerContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs";
import { h as readRuntimeConfig } from "./runtime-snapshot-WbwbY5b7.mjs";
import { t as hasHttpUrlPrefix } from "./url-protocol-DXxSDuQZ.mjs";
import { n as authorizeOperatorScopesForMethod } from "./method-scopes-Dpyb0Ck-.mjs";
import { r as captureSessionStoreReadCandidate } from "./session-store-read-candidates-BjEE1iTg.mjs";
import { a as maxBytesForKind, o as mediaKindFromMime } from "./constants-ChkaB-HW.mjs";
import { d as normalizeMimeType, u as mimeTypeFromFilePath } from "./mime-D2wVBzpa.mjs";
import { r as readAssistantDisplayContent } from "./assistant-display-content-CBuMU4m5.mjs";
import { s as withSessionHistoryWorkerDatabases } from "./session-transcript-worker-runtime-DMpH3wlh.mjs";
import { a as prepareSessionStoreTargetInventory } from "./session-store-target-inventory-Cf7beBnr.mjs";
import { n as prepareSessionStoreTargetInventoryRead } from "./session-store-target-runtime-B1-mhici.mjs";
import { s as SOURCE_PAGE_MAX_BYTES, u as iterateSessionTranscriptSourcePages } from "./transcript-display-position-nYZ0UpDE.mjs";
import { n as withSessionActorStorage } from "./session-actor-storage-acquisition-bj-qIczw.mjs";
import { s as tryResolveSessionCompatibilityOwnerAgentId } from "./session-request-agent-tfwWH53J.mjs";
import "./config-CMA-J084.mjs";
import { a as getRemoteControlUiIngressContext, r as assertRemoteControlUiIngressCurrent } from "./ingress-attribution-DAAQgd6y.mjs";
import { r as resolveGatewaySessionStoreTargetInWorker } from "./session-utils-store-worker-BU_tdh8T.mjs";
import { t as collectReplyMediaEntries } from "./reply-media-entries-BE-R1jqq.mjs";
import { n as matchesHttpIfNoneMatch } from "./http-conditional-BnFeJ7I4.mjs";
import { t as sendJson } from "./http-json-ddGJz5CA.mjs";
import { d as sendMethodNotAllowed, f as sendMissingScopeForbidden } from "./http-common-FfhIIwOW.mjs";
import "./media-services-DAzmF7yi.mjs";
import { h as createImageProcessor, s as getImageMetadata } from "./image-ops-zeupBxnN.mjs";
import { i as withChannelReadAuthority, n as captureChannelReadScope } from "./channel-read-authority-BVl4WY3A.mjs";
import { n as resolveDeliveryQueueStateEnv } from "./delivery-queue-state-context-Cxp-xMAQ.mjs";
import "./delivery-queue-sqlite-lyIJZlO0.mjs";
import { t as resolveLocalMediaPath } from "./local-media-path-R9G3PyAB.mjs";
import { d as saveMediaBuffer, p as saveMediaSource, t as MEDIA_MAX_BYTES } from "./store-zsTAVy24.mjs";
import { o as resolveLocalMediaRoots, r as assertLocalMediaAllowed } from "./local-media-access-D6Qr0fZd.mjs";
import { c as retainArtifactDownloadStream, s as resolveArtifactDownloadGrant, t as assertArtifactDownloadGrantCurrent } from "./artifact-download-grants-D5a8V4KO.mjs";
import { f as readSessionMessagesWithSourceAsync, u as readSessionMessagesMatchingIdAsync } from "./session-transcript-readers-D1WqgwbF.mjs";
import { t as WEBCHAT_LOCAL_MEDIA_MAX_BYTES } from "./configured-max-bytes-lKIaFMol.mjs";
import { a as loadPendingSessionDeliveries } from "./session-delivery-queue-storage-BKIKqGr-.mjs";
import { i as resolvePlaybackTranscode, n as replacePlaybackFileExtension, r as resolvePlaybackMetadataForSource, t as PlaybackInspectionBusyError } from "./playback-transcode-bt6dS8Ae.mjs";
import { t as unlinkIfExists } from "./temp-files-DByyVLID.mjs";
import { n as normalizeChatImageRenditionWidth } from "./chat-image-renditions-swq0mtjT.mjs";
import { n as buildManagedMediaContentDisposition } from "./assistant-media-content-disposition-y--dAvCz.mjs";
import { i as writeByteHeaders, n as createImmutableFileValidators, r as resolveByteResponse, t as createGatewayByteStream } from "./http-byte-range-D1yrfDRK.mjs";
import { l as resolveOpenAiCompatibleHttpSenderIsOwner, r as authorizeGatewayHttpRequestOrReply, u as resolveSharedSecretHttpOperatorScopes } from "./http-auth-utils-B0FI4CE4.mjs";
import "./http-utils-B5V9Okzh.mjs";
import { c as listManagedImageRecordEntries, l as readManagedImageRecord, n as attachManagedImageRecordsToMessage, r as captureManagedImageContext, t as MANAGED_OUTGOING_ORIGINALS_SUBDIR } from "./managed-image-record-store-CG0Zx3S7.mjs";
import { i as resolveManagedImageOriginalPath, n as deleteManagedImageRecordArtifacts, r as insertManagedImageRecordWithFile, t as deleteAgedOrphanManagedImageFiles } from "./managed-image-attachments.custody-4JkSqqlL.mjs";
import { n as readImageThumbnailFromFile } from "./managed-image-thumbnail-cache-B4-EHveZ.mjs";
import { i as createHttpImageRepresentation } from "./http-image-response-BMmTktPR.mjs";
import { a as buildOutgoingVariantUrl, i as buildManagedOutgoingArtifactId, o as parseManagedOutgoingArtifactId, t as MANAGED_OUTGOING_ATTACHMENT_ID_RE } from "./managed-outgoing-artifact-id-CdPx-kme.mjs";
import { t as prepareRemoteIngressSessionRead } from "./remote-ingress-session-read-C1WTYcEK.mjs";
import path from "node:path";
import { randomUUID } from "node:crypto";
import fs from "node:fs/promises";
import { sanitizeUntrustedFileName } from "@openclaw/fs-safe/advanced";
//#region src/gateway/managed-image-attachments.errors.ts
function createManagedImageAttachmentError(e) {
const t = new Error(e);
t.name = "ManagedImageAttachmentError";
return t;
}
function getSanitizedManagedImageAttachmentError(e, t, n) {
if (e instanceof Error && (e.name === "ManagedImageAttachmentError" || e.message.startsWith("Managed image attachment ") || e.message.startsWith("Invalid image data URL"))) return e;
return createManagedImageAttachmentError(`Managed ${n} attachment ${JSON.stringify(t)} could not be prepared`);
}
//#endregion
//#region src/gateway/managed-image-attachments.media-kind.ts
function maxBytesForManagedMediaKind(e, t, n = false) {
return e === "image" ? t : n && (e === "audio" || e === "video") ? WEBCHAT_LOCAL_MEDIA_MAX_BYTES : maxBytesForKind(e);
}
const MANAGED_DOCUMENT_MIME_TYPES = /* @__PURE__ */ new Set([
"application/json",
"application/msword",
"application/pdf",
"application/vnd.ms-excel",
"application/vnd.ms-powerpoint",
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/x-cfb",
"application/yaml",
"application/zip",
"text/csv",
"text/html",
"text/markdown",
"text/plain"
]);
function resolveManagedMediaKind(e) {
const t = normalizeMimeType(e);
if (t === "image/svg+xml") return null;
const n = mediaKindFromMime(t);
if (n === "image" || n === "audio" || n === "video") return n;
return t && MANAGED_DOCUMENT_MIME_TYPES.has(t) ? "document" : null;
}
function formatLimitMiB(e) {
if (e < 1048576) return `${e} bytes`;
return Number.isInteger(e / 1048576) ? `${e / 1048576} MiB` : `${(e / 1048576).toFixed(1)} MiB`;
}
//#endregion
//#region src/gateway/managed-image-attachments.prepare.ts
function toRecordFilename(e, t, n, r) {
const i = n ?? path.basename(e).trim();
if (!t?.trim()) return i || null;
const a = sanitizeUntrustedFileName(t, i);
const o = r === "application/octet-stream" || mimeTypeFromFilePath(a) === r ? path.extname(a) : path.extname(e);
return `${path.parse(a).name}${o}`;
}
function prepareOutgoingMediaFromReplyPayload(e, t = e) {
const n = /* @__PURE__ */ new Map();
for (const e of collectReplyMediaEntries(t)) {
const t = e.url.trim();
if (t && e.attachment && !n.has(t)) n.set(t, e.attachment);
}
const r = /* @__PURE__ */ new Set();
return collectReplyMediaEntries(e).flatMap((t) => {
const i = t.url.trim();
if (!i || r.has(i)) return [];
r.add(i);
const a = n.get(i) ?? t.attachment;
return [{
url: t.url,
...a?.name ? { filename: a.name } : {},
...a?.mimeType ? { mimeType: a.mimeType } : {},
trustedLocal: a?.trustedLocalMedia ?? e.trustedLocalMedia === true,
...a?.durationMs !== void 0 ? { durationMs: a.durationMs } : {},
...a?.width !== void 0 ? { width: a.width } : {},
...a?.height !== void 0 ? { height: a.height } : {}
}];
});
}
//#endregion
//#region src/gateway/managed-image-session-read.ts
/** Serving keeps discovery and physical readers alive through response publication. */
async function withManagedImageSessionRead(e, t) {
const { cfg: n, sessionKey: r, agentId: i, stateDir: a } = e;
e.assertCurrent();
const o = {
agentId: i,
sessionKey: normalizeSessionKeyPreservingOpaquePeerIds(r),
storePath: n.session?.store,
env: {
...process.env,
OPENCLAW_STATE_DIR: a
}
};
if (isIncognitoSessionKey(o.sessionKey)) {
const n = e.assertCurrent;
return await withSessionActorStorage(o, {
lifetime: {
assertCurrent: n,
assertReadable: n
},
authority: {
assertCurrent: n,
authorize: n
}
}, (e) => {
const n = e.actor.snapshot(e.authority)?.entry;
if (!n) return null;
return t({
...o,
storePath: e.path,
sessionEntry: n,
sessionId: n.sessionId
}, () => {
const t = e.actor.snapshot(e.authority)?.entry;
if (t?.sessionId !== n.sessionId || t?.lifecycleRevision !== n.lifecycleRevision) throw new Error("Managed media session authority changed");
});
}) ?? null;
}
const { candidates: s, ...c } = prepareSessionStoreTargetInventory(n, [i], {
...process.env,
OPENCLAW_STATE_DIR: a
});
const l = prepareSessionStoreTargetInventoryRead({
...c,
candidates: s
});
const assertSelectionCurrent = () => {
e.assertCurrent();
for (const e of s) if (captureSessionStoreReadCandidate(e.path, e.scope).physicalPath !== e.physicalPath) throw new Error("Managed media session store changed during read");
};
return l.withRead(async (n, o) => {
const s = n.agents[0];
if (!s?.result.available) return e.unavailable ?? null;
return withSessionHistoryWorkerDatabases(s.reads.map(({ database: e }) => ({
...e,
env: c.env
})), async (n) => {
const l = /* @__PURE__ */ new Map();
const assertCurrent = () => {
o();
for (const e of n) e.assertCurrent();
for (const [e, t] of l) assertExistingDatabaseIdentity(e, t);
};
let u;
for (const [t, { database: a }] of s.reads.entries()) {
const o = {
agentId: i,
databaseAgentId: a.agentId,
storePath: a.path,
env: c.env,
sessionKey: r
};
const s = n[t];
let d;
try {
d = await s.readExactEntries({
sessionKeys: [r],
projection: "sharing",
env: c.env
});
} catch (t) {
assertCurrent();
if (e.unavailable !== void 0 || extractErrorCode(t) === "SESSION_CANONICAL_KEY_MIGRATION_REQUIRED" || t instanceof SessionMetadataUnavailableError && t.reason === "schema-missing") return e.unavailable ?? null;
throw t;
}
if (d.sharing) l.set(a.path, d.sharing.databaseIdentity);
assertCurrent();
if (d.sharing?.placeholders.length) return e.unavailable ?? null;
let f = d.entries[0]?.entry;
if (!f) {
const t = await s.readEntryResult({ scope: o }).catch((t) => {
if (e.unavailable !== void 0) return;
throw t;
});
assertCurrent();
if (!t?.ok) return e.unavailable ?? null;
f = t.value;
}
if (f) {
if (u) return e.unavailable ?? null;
u = {
...o,
sessionEntry: f,
sessionId: f.sessionId
};
}
}
if (u) return t(u, assertCurrent);
if (path.resolve(a) !== path.resolve(resolveStateDir())) return null;
const d = await resolveGatewaySessionStoreTargetInWorker({
cfg: c.config,
key: r,
agentId: i,
env: c.env,
assertActive: assertCurrent
});
assertCurrent();
if (!d.readSource) return null;
const f = d.readSource;
return withSessionHistoryWorkerDatabases([{
...f,
env: c.env
}], async ([n]) => {
const a = {
agentId: i,
databaseAgentId: f.agentId,
sessionKey: d.canonicalKey,
storePath: f.path,
env: c.env
};
const o = await n.readEntryResult({ scope: a }).catch((t) => {
if (e.unavailable !== void 0) return;
throw t;
});
const assertFallbackCurrent = () => {
assertCurrent();
n.assertCurrent();
};
assertFallbackCurrent();
if (!o?.ok) return e.unavailable ?? null;
if (!o.value) return null;
return t({
...a,
sessionKey: r,
sessionId: o.value.sessionId,
sessionEntry: o.value
}, assertFallbackCurrent);
});
});
}, assertSelectionCurrent).catch((t) => {
if (e.unavailable !== void 0 && (t instanceof SessionMetadataUnavailableError || extractErrorCode(t) === "SESSION_CANONICAL_KEY_MIGRATION_REQUIRED")) return e.unavailable;
throw t;
});
}
//#endregion
//#region src/gateway/managed-image-thumbnail-response.ts
function handleManagedImageThumbnailResponse(e, t, n) {
const r = path.parse(n.filename ?? "generated-image").name;
const i = createHttpImageRepresentation(n.thumbnail, "image/webp");
t.setHeader("etag", i.etag);
t.setHeader("cache-control", n.cacheControl);
t.setHeader("content-disposition", buildManagedMediaContentDisposition(`${r}-thumbnail.webp`, "image/webp"));
t.setHeader("x-content-type-options", "nosniff");
t.setHeader("referrer-policy", "no-referrer");
if (matchesHttpIfNoneMatch(e.headers["if-none-match"], i.etag)) {
t.statusCode = 304;
t.end();
return true;
}
t.statusCode = 200;
t.setHeader("content-type", i.contentType);
t.setHeader("content-length", String(i.body.byteLength));
t.end(e.method === "HEAD" ? void 0 : i.body);
return true;
}
//#endregion
//#region src/gateway/managed-image-attachments.ts
const DEFAULT_TRANSIENT_OUTGOING_IMAGE_TTL_MS = 9e5;
const DEFAULT_MANAGED_IMAGE_ATTACHMENT_LIMITS = {
maxBytes: 12582912,
maxWidth: 4096,
maxHeight: 4096,
maxPixels: 2e7
};
const EMPTY_MANAGED_ATTACHMENT_REFS = [];
function resolveManagedImageAttachmentLimits(e) {
return {
maxBytes: e?.maxBytes ?? DEFAULT_MANAGED_IMAGE_ATTACHMENT_LIMITS.maxBytes,
maxWidth: e?.maxWidth ?? DEFAULT_MANAGED_IMAGE_ATTACHMENT_LIMITS.maxWidth,
maxHeight: e?.maxHeight ?? DEFAULT_MANAGED_IMAGE_ATTACHMENT_LIMITS.maxHeight,
maxPixels: e?.maxPixels ?? DEFAULT_MANAGED_IMAGE_ATTACHMENT_LIMITS.maxPixels
};
}
function buildManagedMediaFailureBlock(e) {
return {
type: "attachment_error",
attachment: {
code: e.code,
kind: e.kind === "media" ? "document" : e.kind,
label: e.label,
...e.mimeType ? { mimeType: e.mimeType } : {}
}
};
}
function assertManagedMediaByteLimit(e, t, n, r) {
if (e > r) throw createManagedImageAttachmentError(`Managed ${t} attachment ${JSON.stringify(n)} exceeds the ${formatLimitMiB(r)} byte limit`);
}
function getManagedImageMetadataLimitError(e, t, n) {
if (!e) return `Managed image attachment ${JSON.stringify(t)} is missing readable dimensions`;
if (e.width > n.maxWidth) return `Managed image attachment ${JSON.stringify(t)} exceeds the ${n.maxWidth}px width limit`;
if (e.height > n.maxHeight) return `Managed image attachment ${JSON.stringify(t)} exceeds the ${n.maxHeight}px height limit`;
if (e.width * e.height > n.maxPixels) return `Managed image attachment ${JSON.stringify(t)} exceeds the ${n.maxPixels.toLocaleString("en-US")} pixel limit`;
return null;
}
function deriveAltText(e, t) {
const n = `Generated image ${t + 1}`;
try {
if (hasHttpUrlPrefix(e)) {
const t = new URL(e);
return path.basename(t.pathname || "").trim() || n;
}
} catch {}
return path.basename(e).trim() || n;
}
function parseMediaDataUrl(e, t, n) {
const r = e.trim();
if (!r.startsWith("data:")) return;
const i = r.slice(5);
const a = i.indexOf(",");
const o = a < 0 ? "" : i.slice(0, a);
if (o.slice(-7).toLowerCase() !== ";base64") throw new Error("Invalid image data URL");
const s = o.indexOf(";");
const c = (s < 0 ? o : o.slice(0, s)).trim().toLowerCase();
if (!c) throw new Error("Invalid image data URL");
const l = i.slice(a + 1);
if (!l || /[^A-Za-z0-9+/=\s]/.test(l)) throw new Error("Invalid image data URL");
const u = mediaKindFromMime(c);
if (u !== "image" && u !== "audio" && u !== "video") throw new Error("Managed media attachment has an unsupported data URL content type");
const d = maxBytesForManagedMediaKind(u, n.maxBytes);
const f = l.replace(/\s+/g, "");
const p = Math.min(/=+$/u.exec(f)?.[0].length ?? 0, 2);
assertManagedMediaByteLimit(Math.floor(f.length * 3 / 4) - p, u, t, d);
return {
buffer: Buffer.from(f, "base64"),
contentType: c,
mediaKind: u
};
}
async function cleanupManagedOutgoingMediaRecords(e) {
const t = e?.stateDir ?? resolveStateDir();
const n = e?.nowMs ?? Date.now();
const r = e?.transientMaxAgeMs ?? DEFAULT_TRANSIENT_OUTGOING_IMAGE_TTL_MS;
const i = e?.sessionKey ?? null;
const a = e?.agentId?.trim() ? normalizeAgentId(e.agentId) : void 0;
const o = i === "global" && a ? tryResolveSessionCompatibilityOwnerAgentId(readRuntimeConfig(), "global") : void 0;
const s = e?.forceDeleteSessionRecords === true;
const c = await listManagedImageRecordEntries({ stateDir: t });
let l;
const u = /* @__PURE__ */ new Map();
for (const { record: e } of c) {
if (!e.messageId) continue;
const t = managedOutgoingAttachmentSessionKey(e);
let n = u.get(t);
if (!n) {
n = { messageIds: /* @__PURE__ */ new Set() };
u.set(t, n);
}
n.messageIds.add(e.messageId);
}
for (const d of c) {
const { record: c } = d;
if (i && c.sessionKey !== i) continue;
if (i === "global" && c.sessionKey === "global" && (!a || resolveManagedSessionOwnerAgentId(c.sessionKey, c.agentId, o) !== a)) continue;
let f = d.cleanupPending;
if (!d.cleanupPending && s) f = true;
else if (!d.cleanupPending && c.messageId) f = await recordMatchesTranscriptMessage(c, u.get(managedOutgoingAttachmentSessionKey(c)), t) === "missing";
else if (!d.cleanupPending) {
const i = Date.parse(c.createdAt);
if (Number.isFinite(i) && n - i >= r && e?.hasActiveSessionRun?.(c.sessionKey, c.agentId?.trim() || void 0) !== true) {
if (l === void 0) l = await loadPendingPreparedAttachmentIds(t);
f = l !== null && !l.has(c.attachmentId);
}
}
if (f) await deleteManagedImageRecordArtifacts(c, t, d.cleanupPending);
}
await deleteAgedOrphanManagedImageFiles({
stateDir: t,
nowMs: n,
minAgeMs: Math.max(r, DEFAULT_TRANSIENT_OUTGOING_IMAGE_TTL_MS)
});
}
async function removeManagedOutgoingMediaBlocks(e, t) {
const n = e.stateDir ?? resolveStateDir();
const r = e.messageId;
const i = collectManagedOutgoingAttachmentRefs(e.blocks);
if (i.length === 0) return;
const a = t ?? captureManagedImageContext(n);
await Promise.all(i.map(async ({ attachmentId: e }) => {
const t = await readManagedImageRecord(e, n, a);
if (t?.messageId === r) {
if (await captureChannelReadScope()?.discardResource(resolveManagedImageOriginalPath(t))) return;
await deleteManagedImageRecordArtifacts(t, n, false, a);
}
}));
}
function resolveManagedSessionOwnerAgentId(e, t, n) {
const r = t?.trim() || parseAgentSessionKey(e)?.agentId || n?.trim();
return r ? normalizeAgentId(r) : void 0;
}
function buildManagedMediaBlock(e, t) {
const n = resolveManagedMediaKind(e.original.contentType);
if (!n) throw new Error("Managed media record has an unsupported content type");
const r = buildOutgoingVariantUrl(e.sessionKey, e.attachmentId, "full");
const i = buildManagedOutgoingArtifactId(e.attachmentId, n);
if (n === "document") return {
type: "attachment",
attachment: {
artifactId: i,
url: r,
kind: n,
label: e.original.filename ?? e.alt,
mimeType: e.original.contentType,
sizeBytes: e.original.sizeBytes
}
};
return {
type: n,
artifactId: i,
url: r,
openUrl: r,
...n === "image" ? { alt: e.alt } : { fileName: e.original.filename },
mimeType: e.original.contentType,
...t ? { playback: t } : {},
...n === "image" ? {
width: e.original.width,
height: e.original.height
} : {},
sizeBytes: e.original.sizeBytes
};
}
function buildManagedOutgoingAttachmentRefKey(e, t) {
return `${e}::${t}`;
}
function parseManagedOutgoingRoute(e) {
try {
const t = new URL(e, "http://localhost").pathname.match(/^\/api\/chat\/media\/outgoing\/([^/]+)\/([^/]+)\/full$/);
if (!t) return null;
const [, n, r] = t;
if (!n || !r || !MANAGED_OUTGOING_ATTACHMENT_ID_RE.test(r)) return null;
return {
sessionKey: decodeURIComponent(n),
attachmentId: r
};
} catch {
return null;
}
}
function collectManagedOutgoingAttachmentRefs(e, t) {
if (!e) return EMPTY_MANAGED_ATTACHMENT_REFS;
let n;
for (const r of e) {
const e = r?.type === "attachment" ? asOptionalRecord(r.attachment) : void 0;
if (r?.type !== "image" && r?.type !== "audio" && r?.type !== "video" && !e) continue;
for (const i of [
r.url,
r.openUrl,
e?.url
]) {
if (typeof i !== "string") continue;
const e = parseManagedOutgoingRoute(i);
if (!e) continue;
if (t && e.sessionKey !== t) continue;
(n ??= /* @__PURE__ */ new Map()).set(e.attachmentId, e);
}
}
return n ? [...n.values()] : EMPTY_MANAGED_ATTACHMENT_REFS;
}
async function loadPendingPreparedAttachmentIds(e) {
try {
const t = captureOpenClawStateWorkerContext({ env: resolveDeliveryQueueStateEnv(e) });
const n = /* @__PURE__ */ new Set();
for (const e of await loadPendingSessionDeliveries(t)) {
if (e.kind !== "agentTurn") continue;
for (const t of Object.values(e.preparedMediaBlocks ?? {})) for (const r of collectManagedOutgoingAttachmentRefs(t, e.sessionKey)) n.add(r.attachmentId);
}
return n;
} catch {
return null;
}
}
async function recordMatchesTranscriptMessage(e, t, n) {
if (!e.messageId) return "missing";
const { sessionKey: r, agentId: i, messageId: a } = e;
const o = buildManagedOutgoingAttachmentRefKey(a, e.attachmentId);
if (t.matches !== void 0) return t.matches === null ? "unavailable" : t.matches.has(o) ? "match" : "missing";
const s = readRuntimeConfig();
const c = resolveManagedSessionOwnerAgentId(r, i) ?? tryResolveSessionCompatibilityOwnerAgentId(s, r);
if (!c) return "unavailable";
const l = await withManagedImageSessionRead({
cfg: s,
agentId: c,
sessionKey: r,
stateDir: n,
assertCurrent: captureChannelReadScope()?.assertCurrent ?? (() => {}),
unavailable: "unavailable"
}, async (e, n) => {
const r = await readManagedOutgoingAttachmentIndex(e, t.messageIds);
n();
t.matches = r;
return r === null ? "unavailable" : r.has(o) ? "match" : "missing";
});
if (l === null) t.matches = /* @__PURE__ */ new Set();
return l ?? "missing";
}
function managedOutgoingAttachmentSessionKey(e) {
return e.sessionKey === "global" && e.agentId ? `agent:${e.agentId}:global` : e.sessionKey;
}
async function readManagedOutgoingAttachmentIndex(e, t) {
const n = /* @__PURE__ */ new Set();
const r = [...t];
try {
for (let i = 0; i < r.length; i += 128) {
const a = iterateSessionTranscriptSourcePages(readSessionMessagesWithSourceAsync, e, {
allowResetArchiveFallback: true,
includeOffPathMessages: true,
messageIds: r.slice(i, i + 128)
});
for await (const { messages: r } of a) for (const i of r) {
const r = asOptionalRecord(asOptionalRecord(i)?.["__openclaw"])?.id;
if (typeof r !== "string" || !t.has(r)) continue;
for (const t of collectManagedOutgoingAttachmentRefs(readAssistantDisplayContent(i), e.sessionKey)) n.add(buildManagedOutgoingAttachmentRefKey(r, t.attachmentId));
}
}
} catch (e) {
if (extractErrorCode(e) !== "TRANSCRIPT_SOURCE_MESSAGE_TOO_LARGE") throw e;
createSubsystemLogger("media").warn(`Retaining managed outgoing media for a session whose transcript exceeds the ${SOURCE_PAGE_MAX_BYTES}-byte page limit`);
return null;
}
return n;
}
async function resolveManagedOutgoingMediaArtifactDownloadForRecord(e, t) {
return withManagedOutgoingMediaRead(e, t ?? resolveStateDir(), async (t) => {
const n = resolveManagedMediaKind(e.original.contentType);
if (!n) return null;
try {
if (!(await fs.stat(resolveManagedImageOriginalPath(e))).isFile()) return null;
} catch {
return null;
}
t();
return {
artifactId: buildManagedOutgoingArtifactId(e.attachmentId, n),
sessionKey: e.sessionKey,
type: n === "document" ? "file" : n,
title: n === "image" ? e.alt : e.original.filename ?? e.alt,
...e.original.contentType ? { mimeType: e.original.contentType } : {},
...e.original.sizeBytes != null ? { sizeBytes: e.original.sizeBytes } : {},
url: buildOutgoingVariantUrl(e.sessionKey, e.attachmentId, "full")
};
});
}
async function withManagedOutgoingMediaRead(e, t, n, r = captureChannelReadScope()?.assertCurrent ?? (() => {}), i) {
r();
if (!e.messageId) return null;
const a = readRuntimeConfig();
const o = resolveManagedSessionOwnerAgentId(e.sessionKey, e.agentId) ?? tryResolveSessionCompatibilityOwnerAgentId(a, e.sessionKey);
if (!o) return null;
return withManagedImageSessionRead({
cfg: a,
agentId: o,
sessionKey: e.sessionKey,
stateDir: t,
assertCurrent: r
}, async (t, r) => {
if (i && t.sessionId !== i.sessionId) return null;
const a = await readSessionMessagesMatchingIdAsync(t, e.messageId);
r();
return a.some((t) => {
const n = asOptionalRecord(t);
return (!i || n?.role === "assistant" && n.idempotencyKey === i.idempotencyKey) && collectManagedOutgoingAttachmentRefs(readAssistantDisplayContent(t), e.sessionKey).some((t) => t.attachmentId === e.attachmentId);
}) ? n(r) : null;
});
}
/** Restore an original image only for this retained assistant source in the current session. */
async function readManagedOutgoingContextImage(e) {
e.assertCurrent();
const t = e.stateDir ?? resolveStateDir();
const n = await resolveManagedOutgoingMediaArtifactRecord({
...e,
stateDir: t
});
e.assertCurrent();
if (!n || resolveManagedMediaKind(n.original.contentType) !== "image") return null;
return withManagedOutgoingMediaRead(n, t, async (t) => {
try {
const { buffer: r } = await readLocalFileSafely({
filePath: resolveManagedImageOriginalPath(n),
maxBytes: e.maxBytes
});
t();
return {
buffer: r,
mimeType: n.original.contentType
};
} catch {
t();
return null;
}
}, e.assertCurrent, {
sessionId: e.sessionId,
idempotencyKey: e.idempotencyKey
});
}
async function resolveManagedOutgoingMediaArtifactRecord(e) {
const { artifactId: t, sessionKey: n, agentId: r, defaultAgentId: i } = e;
const a = e.stateDir ?? resolveStateDir();
const o = parseManagedOutgoingArtifactId(t);
if (!o) return null;
const s = await readManagedImageRecord(o.attachmentId, a);
if (!s || s.sessionKey !== n) return null;
const c = r ? normalizeAgentId(r) : void 0;
const l = resolveManagedSessionOwnerAgentId(s.sessionKey, s.agentId, i);
if (c && l !== c) return null;
const u = resolveManagedMediaKind(s.original.contentType);
if (!u || o.family === "image" !== (u === "image")) return null;
return s;
}
/** Prepare a transcript-backed media source; the RPC owner grants the requesting reader access. */
async function resolveManagedOutgoingMediaArtifactDownload(e) {
const t = await resolveManagedOutgoingMediaArtifactRecord(e);
return t ? resolveManagedOutgoingMediaArtifactDownloadForRecord(t, e.stateDir) : null;
}
/** Upgrade legacy managed-image URLs that predate stable artifact ids. */
async function resolveManagedOutgoingMediaUrlDownload(e) {
const { url: t, sessionKey: n } = e;
const r = resolveStateDir();
const i = parseManagedOutgoingRoute(t);
if (!i || i.sessionKey !== n) return null;
const a = await readManagedImageRecord(i.attachmentId, r);
if (!a || a.sessionKey !== n) return null;
return await resolveManagedOutgoingMediaArtifactDownloadForRecord(a, r);
}
/** Read a local preview through the same transcript ownership and thumbnail cache as HTTP. */
async function readManagedOutgoingImageThumbnail(e) {
const { maxBytes: t, signal: n } = e;
const r = e.stateDir ?? resolveStateDir();
n.throwIfAborted();
const i = await resolveManagedOutgoingMediaArtifactRecord({
...e,
stateDir: r
});
n.throwIfAborted();
if (!i || resolveManagedMediaKind(i.original.contentType) !== "image") return null;
return await withManagedOutgoingMediaRead(i, r, async (e) => {
const r = await openLocalFileSafely({ filePath: resolveManagedImageOriginalPath(i) });
try {
const i = await readImageThumbnailFromFile(r, t);
e();
n.throwIfAborted();
return i;
} finally {
await r.handle.close();
}
}, () => n.throwIfAborted());
}
function attachManagedOutgoingMediaToMessage(e) {
const t = e.messageId.trim();
const n = collectManagedOutgoingAttachmentRefs(e.blocks);
if (!t || n.length === 0) return Promise.resolve(false);
return attachManagedImageRecordsToMessage({
attachments: n,
messageId: t,
updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
stateDir: e.stateDir
});
}
async function createManagedOutgoingMediaBlocks(e) {
return await withChannelReadAuthority(e.assertCurrent, async () => {
const t = e.sessionKey.trim();
if (!t) return [];
const n = e.items ?? [];
if (n.length === 0) return [];
const r = e.stateDir ?? resolveStateDir();
const i = captureManagedImageContext(r);
const a = resolveManagedImageAttachmentLimits(e.limits);
const o = [];
const discardBlocks = () => removeManagedOutgoingMediaBlocks({
blocks: o,
messageId: e.messageId ?? null,
stateDir: r
}, i);
let s;
for (const [c, l] of n.entries()) {
const n = o.length;
const u = l.url;
const d = u.trim();
const f = /^data:(image|audio|video)\//iu.exec(d)?.[1];
const p = `Generated ${f ?? "media"} ${c + 1}`;
const m = d.startsWith("data:");
const h = m ? void 0 : resolveLocalMediaPath(u);
const g = m ? p : l.filename?.trim() || deriveAltText(h ?? u, c);
const _ = resolveManagedMediaKind(l.mimeType ?? mimeTypeFromFilePath(h ?? u));
const v = f === "image" || f === "audio" || f === "video" ? f : _ ?? "media";
let y = null;
let b;
let x = "delivery-failed";
try {
e.assertCurrent?.();
const n = parseMediaDataUrl(u, p, a);
if (h && (v === "audio" || v === "video") && !l.trustedLocal) throw new Error("Local audio/video media requires an explicitly trusted reply payload");
let d = null;
let f = n ? await saveMediaBuffer(n.buffer, n.contentType, "outgoing/originals", maxBytesForManagedMediaKind(n.mediaKind, a.maxBytes), `generated-${n.mediaKind}-${c + 1}`) : await (async () => {
if (h) {
const t = e.localRoots;
await assertLocalMediaAllowed(h, t, t === "any" ? void 0 : { resolveRoots: async () => {
s ??= await resolveLocalMediaRoots(t);
return s;
} });
}
const t = h ?? u;
const n = Math.max(a.maxBytes, h && (_ === "audio" || _ === "video") ? WEBCHAT_LOCAL_MEDIA_MAX_BYTES : 0, maxBytesForKind("audio"), maxBytesForKind("video"), maxBytesForKind("document"), MEDIA_MAX_BYTES);
if (hasHttpUrlPrefix(t)) {
const { saveRemoteMediaForStore: r } = await import("./store.remote.runtime.js");
return await r({
source: t,
subdir: "outgoing/originals",
maxBytes: n,
abortSignal: e.abortSignal
});
}
return await saveMediaSource(t, void 0, "outgoing/originals", n);
})();
y = f.path;
let m = f.contentType ?? l.mimeType;
if (!m) throw new Error("Managed media attachment has no detectable content type");
const S = resolveManagedMediaKind(m);
if (!S) {
x = "unsupported-format";
throw new Error("Managed media attachment has an unsupported content type");
}
if (h && S !== "image" && !l.trustedLocal) throw new Error("Local audio/video media requires an explicitly trusted reply payload");
const C = maxBytesForManagedMediaKind(S, a.maxBytes, Boolean(h));
assertManagedMediaByteLimit(f.size, S, g, C);
let w = {
width: null,
height: null,
sizeBytes: f.size
};
if (S === "image") {
const e = n ? n.buffer : (await readLocalFileSafely({ filePath: f.path })).buffer;
assertManagedMediaByteLimit(e.byteLength, "image", g, a.maxBytes);
const t = await getImageMetadata(e);
w = {
width: t?.width ?? null,
height: t?.height ?? null,
sizeBytes: f.size
};
const r = getManagedImageMetadataLimitError(t, g, a);
if (r) {
if (!t) throw createManagedImageAttachmentError(r);
const n = await createImageProcessor().encode(e, {
format: "auto",
limits: {
maxWidth: a.maxWidth,
maxHeight: a.maxHeight,
maxPixels: a.maxPixels
},
opaque: {
format: "jpeg",
quality: 92
},
transparent: {
format: "png",
compressionLevel: 9
},
transparency: "auto"
});
assertManagedMediaByteLimit(n.data.byteLength, "image", g, a.maxBytes);
const i = await saveMediaBuffer(n.data, n.mimeType, "outgoing/originals", a.maxBytes, toRecordFilename(f.path) ?? `generated-image-${c + 1}`);
await unlinkIfExists(f.path);
f = i;
m = i.contentType ?? n.mimeType;
y = f.path;
w = {
width: n.width,
height: n.height,
sizeBytes: i.size
};
d = {
type: "text",
text: `[Image warning] ${g} exceeded gateway dimension/pixel limits and was resized from ${t.width}×${t.height} to ${n.width}×${n.height}.`
};
}
}
const T = {
attachmentId: randomUUID(),
sessionKey: t,
...t === "global" && e.agentId?.trim() ? { agentId: e.agentId.trim() } : {},
messageId: e.messageId ?? null,
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
retentionClass: e.messageId ? "history" : "transient",
alt: g,
original: {
mediaRoot: path.dirname(path.dirname(path.dirname(path.resolve(f.path)))),
mediaId: f.id,
mediaSubdir: MANAGED_OUTGOING_ORIGINALS_SUBDIR,
contentType: m,
width: w.width,
height: w.height,
sizeBytes: w.sizeBytes,
filename: toRecordFilename(f.path, l.filename, S === "image" ? void 0 : g, m)
}
};
let E;
if (S === "audio" || S === "video") {
const t = await openLocalFileSafely({ filePath: f.path });
await t[Symbol.asyncDispose]();
try {
E = (await resolvePlaybackMetadataForSource({
sourcePath: t.realPath,
sourceStat: {
size: t.stat.size,
mtimeMs: t.stat.mtimeMs,
ctimeMs: t.stat.ctimeMs,
exactIdentity: t.exactIdentity
},
mimeType: m,
kind: S,
signal: e.abortSignal,
assertCurrent: e.assertCurrent,
admission: "immediate"
})).playback;
} catch (e) {
if (!(e instanceof PlaybackInspectionBusyError)) throw e;
}
}
const D = buildManagedMediaBlock(T, E);
await insertManagedImageRecordWithFile(T, f.path, r, i);
b = T;
i.admission.assertCurrent();
const O = asNonNegativeFiniteNumber(l.durationMs);
const k = asNonNegativeFiniteNumber(l.width);
const A = asNonNegativeFiniteNumber(l.height);
o.push({
...D,
...O !== void 0 ? { durationMs: O } : {},
...S === "video" && k !== void 0 ? { width: k } : {},
...S === "video" && A !== void 0 ? { height: A } : {}
});
if (d) o.push(d);
} catch (t) {
if (y) {
if (captureChannelReadScope()) await unlinkIfExists(y);
else if (b) await deleteManagedImageRecordArtifacts(b, r, false, i);
else if (!hasSqliteWorkerOutcomeUnknown(t)) await unlinkIfExists(y);
}
try {
e.assertCurrent?.();
} catch (e) {
await discardBlocks();
throw e;
}
const a = getSanitizedManagedImageAttachmentError(t, g, v);
if (e.continueOnPrepareError) {
o.push(buildManagedMediaFailureBlock({
code: x,
kind: v,
label: g,
mimeType: l.mimeType ?? mimeTypeFromFilePath(h ?? u)
}));
e.onPrepareError?.(a);
e.onPrepared?.(l, o.slice(n));
continue;
}
await discardBlocks();
throw a;
}
e.onPrepared?.(l, o.slice(n));
}
return o;
});
}
function sendStatus(e, t, n) {
if (e.writableEnded) return;
e.statusCode = t;
e.setHeader("content-type", "text/plain; charset=utf-8");
e.end(n);
}
async function handleManagedOutgoingMediaHttpRequest(e, t, n) {
const r = new URL(e.url ?? "/", "http://localhost");
const i = (n.basePath && r.pathname.startsWith(`${n.basePath}/`) ? r.pathname.slice(n.basePath.length) : r.pathname).match(/^\/api\/chat\/media\/outgoing\/([^/]+)\/([^/]+)\/(full|thumbnail)$/);
if (!i) return false;
const respondNotFound = () => {
sendStatus(t, 404, "not found");
return true;
};
if (e.method !== "GET" && e.method !== "HEAD") {
sendMethodNotAllowed(t, "GET, HEAD");
return true;
}
const a = i[1];
const o = i[2];
const s = i[3];
if (!a || !o || s !== "full" && s !== "thumbnail") return false;
if (!MANAGED_OUTGOING_ATTACHMENT_ID_RE.test(o)) return respondNotFound();
let c;
try {
c = decodeURIComponent(a);
} catch {
return respondNotFound();
}
const l = r.searchParams.get("mediaTicket");
const u = n.clients ?? /* @__PURE__ */ new Set();
const d = l ? resolveArtifactDownloadGrant(u, l) : void 0;
const f = buildOutgoingVariantUrl(c, o, "full");
if (l && (!d || d.grant.source.kind !== "managed" || d.grant.source.path !== f)) return respondNotFound();
let p;
const assertGrantCurrent = () => {
if (!d) return;
const t = getRemoteControlUiIngressContext(e);
assertRemoteControlUiIngressCurrent(t);
if (t && d.client.internal?.remoteIngressPrincipal?.assertCurrent !== t.resolvePrincipal().assertCurrent) throw new Error("Managed media belongs to another ingress grant");
if (p) p.assertCurrent();
else assertArtifactDownloadGrantCurrent(u, d.client, d.ticket, d.grant);
};
let assertRequestCurrent;
if (!d) {
const r = await authorizeGatewayHttpRequestOrReply({
...n,
req: e,
res: t
});
if (!r) return true;
assertRequestCurrent = r.assertCurrent;
const i = resolveSharedSecretHttpOperatorScopes(e, r);
const a = authorizeOperatorScopesForMethod("chat.history", i);
if (!a.allowed) {
sendMissingScopeForbidden(t, a.missingScope);
return true;
}
if (!resolveOpenAiCompatibleHttpSenderIsOwner(e, r)) {
sendJson(t, 403, {
ok: false,
error: {
type: "forbidden",
message: "owner access required"
}
});
return true;
}
}
const assertCallerCurrent = () => {
if (t.writableEnded || t.destroyed) throw new Error("Managed media request ended");
assertRequestCurrent?.();
assertGrantCurrent();
};
const m = n.stateDir ?? resolveStateDir();
try {
try {
var h = _usingCtx();
assertCallerCurrent();
const n = h.u(await prepareRemoteIngressSessionRead(getRemoteControlUiIngressContext(e)?.resolvePrincipal(), c));
const i = assertRequestCurrent;
assertRequestCurrent = () => {
i?.();
n.assertCurrent();
};
const a = await readManagedImageRecord(o, m);
assertCallerCurrent();
if (!a || a.sessionKey !== c) return respondNotFound();
if (await withManagedOutgoingMediaRead(a, m, async (n) => {
const i = resolveManagedMediaKind(a.original.contentType);
if (!i) return respondNotFound();
let o;
try {
o = await openLocalFileSafely({ filePath: resolveManagedImageOriginalPath(a) });
} catch {
return respondNotFound();
}
const c = d ? "private, no-store" : "private, max-age=31536000, immutable";
const writeMediaHeaders = (e, n, r = c) => {
t.setHeader("content-type", e);
t.setHeader("x-content-type-options", "nosniff");
t.setHeader("referrer-policy", "no-referrer");
t.setHeader("cache-control", r);
t.setHeader("content-disposition", buildManagedMediaContentDisposition(n, e));
};
let l = createGatewayByteStream(t, o.handle, respondNotFound);
try {
let f = a.original.contentType || "application/octet-stream";
let m = a.original.filename;
if (s === "thumbnail") {
const a = i === "image" ? await readImageThumbnailFromFile(o, void 0, normalizeChatImageRenditionWidth(r.searchParams.get("width"))).catch(() => null) : null;
await l.close();
n?.();
if (!a) {
respondNotFound();
return true;
}
return handleManagedImageThumbnailResponse(e, t, {
thumbnail: a,
filename: m,
cacheControl: c
});
}
const h = r.searchParams.get("playback") === "1" && (i === "audio" || i === "video");
if (h) {
const e = await resolvePlaybackTranscode({
sourcePath: o.realPath,
sourceStat: {
size: o.stat.size,
mtimeMs: o.stat.mtimeMs,
ctimeMs: o.stat.ctimeMs,
exactIdentity: o.exactIdentity
},
mimeType: f,
kind: i,
signal: l.signal,
assertCurrent: n
});
if (e.kind === "preparing") {
await l.close();
n?.();
sendJson(t, 202, { status: "preparing" });
return true;
}
if (e.kind === "transcoded") {
const n = await openLocalFileSafely({ filePath: e.path }).catch(() => null);
if (n) {
await l.close();
o = n;
l = createGatewayByteStream(t, o.handle, respondNotFound);
f = e.contentType;
m = replacePlaybackFileExtension(m ?? "generated-media", e.extension);
}
}
}
const g = resolveByteResponse({
file: o.stat,
validators: h ? void 0 : createImmutableFileValidators(o.stat),
method: e.method,
request: e
});
if (d) p = retainArtifactDownloadStream(u, d.client, d.ticket, d.grant);
await l.pipe(g, e.method, () => {
n?.();
writeMediaHeaders(f, m, h && !d ? "private, no-cache" : c);
writeByteHeaders(t, g);
}, d ? { assertCurrent: n } : void 0);
} catch (e) {
await l.close();
if (!t.writableEnded && !t.destroyed) throw e;
}
return true;
}, assertCallerCurrent) === null) {
assertCallerCurrent();
respondNotFound();
}
} catch (e) {
h.e = e;
} finally {
h.d();
}
} catch (e) {
if (d && !t.headersSent) respondNotFound();
else if (!t.writableEnded && !t.destroyed) throw e;
} finally {
p?.release();
}
return true;
}
//#endregion
export { createManagedOutgoingMediaBlocks as a, readManagedOutgoingContextImage as c, resolveManagedOutgoingMediaArtifactDownload as d, resolveManagedOutgoingMediaUrlDownload as f, cleanupManagedOutgoingMediaRecords as i, readManagedOutgoingImageThumbnail as l, attachManagedOutgoingMediaToMessage as n, handleManagedOutgoingMediaHttpRequest as o, prepareOutgoingMediaFromReplyPayload as p, buildManagedMediaFailureBlock as r, parseManagedOutgoingRoute as s, DEFAULT_MANAGED_IMAGE_ATTACHMENT_LIMITS as t, removeManagedOutgoingMediaBlocks as u };