openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
13 lines • 36.4 kB
JavaScript
import{l as asNonNegativeFiniteNumber}from"./number-coercion-B3CfI447.mjs";import{a as extractErrorCode}from"./error-coercion-DlKnt6w-.mjs";import{a as asOptionalRecord}from"./record-coerce-BTbqdJ3-.mjs";import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import{c as openLocalFileSafely,p as readLocalFileSafely}from"./fs-safe-Bxzu1j4h.mjs";import"./paths-D_FOvGon.mjs";import{n as normalizeAgentId}from"./agent-id-cOfqmfln.mjs";import{r as isIncognitoSessionKey}from"./session-key-DYtwLLn1.mjs";import{N as parseAgentSessionKey,j as normalizeSessionKeyPreservingOpaquePeerIds}from"./session-key-BPgKfU2m.mjs";import{i as assertExistingDatabaseIdentity}from"./sqlite-worker-identity-CikEUuqF.mjs";import{r as hasSqliteWorkerOutcomeUnknown}from"./sqlite-worker-error-DHUQ0e2U.mjs";import{t as _usingCtx}from"./usingCtx-CUVyQ_FT.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{t as SessionMetadataUnavailableError}from"./session-metadata-unavailable-error-D8TzlAxW.mjs";import"./sqlite-worker-contract-CcRGAuae.mjs";import{r as captureOpenClawStateWorkerContext}from"./openclaw-state-worker-context-Dx8YjqO2.mjs";import{h as readRuntimeConfig}from"./runtime-snapshot-Bg5K4JNu.mjs";import{t as hasHttpUrlPrefix}from"./url-protocol-BLfSvQhh.mjs";import{r as readAssistantDisplayContent}from"./assistant-display-content-DZzkofMk.mjs";import{n as authorizeOperatorScopesForMethod}from"./method-scopes-Dalbwzsv.mjs";import{r as captureSessionStoreReadCandidate}from"./session-store-read-candidates-CcJ9PtLw.mjs";import{a as maxBytesForKind,o as mediaKindFromMime}from"./constants-cCp4CBUF.mjs";import{d as normalizeMimeType,u as mimeTypeFromFilePath}from"./mime-ZmYZsEjx.mjs";import{o as withSessionHistoryWorkerDatabases}from"./session-transcript-worker-runtime-Cx43k2lO.mjs";import{n as prepareSessionStoreTargetInventoryRead}from"./session-store-target-runtime-Dp3WAJjF.mjs";import{r as prepareSessionStoreTargetInventory}from"./session-store-target-inventory-CcuhBOtl.mjs";import{i as withChannelReadAuthority,n as captureChannelReadScope}from"./channel-read-authority-BheGEIiJ.mjs";import{s as SOURCE_PAGE_MAX_BYTES,u as iterateSessionTranscriptSourcePages}from"./transcript-display-position-CTVyCp-i.mjs";import{n as withSessionActorStorage}from"./session-actor-storage-acquisition-B3-E4SDM.mjs";import{s as tryResolveSessionCompatibilityOwnerAgentId}from"./session-request-agent-DmeXmT1P.mjs";import"./config-DkZ8y8Gv.mjs";import{r as resolveGatewaySessionStoreTargetInWorker}from"./session-utils-store-worker-43BDHG7V.mjs";import{t as collectReplyMediaEntries}from"./reply-media-entries-BQdtrYXZ.mjs";import{a as getRemoteControlUiIngressContext,r as assertRemoteControlUiIngressCurrent}from"./ingress-attribution-Ct_hJMPU.mjs";import{t as sendJson}from"./http-json-g_k96dZ_.mjs";import{d as retainArtifactDownloadStream,n as assertArtifactDownloadGrantCurrent,u as resolveArtifactDownloadGrant}from"./artifact-download-grants-D28hFNXi.mjs";import{d as sendMethodNotAllowed,f as sendMissingScopeForbidden}from"./http-common-kI7-c_LU.mjs";import{n as resolveDeliveryQueueStateEnv}from"./delivery-queue-state-context-hv3uu8YS.mjs";import"./delivery-queue-sqlite-BtAn8uTD.mjs";import{t as buildOutboundMediaLoadOptions}from"./load-options-DlLitw84.mjs";import{t as resolveLocalMediaPath}from"./local-media-path-DuTtVG2b.mjs";import{d as saveMediaBuffer,p as saveMediaSource,t as MEDIA_MAX_BYTES}from"./store-wPqhY4JR.mjs";import{r as assertLocalMediaAllowed,s as resolveLocalMediaRoots}from"./local-media-access-eksHnGvN.mjs";import{f as readSessionMessagesWithSourceAsync,u as readSessionMessagesMatchingIdAsync}from"./session-transcript-readers-D9Cuet3N.mjs";import{h as createImageProcessor,s as getImageMetadata}from"./image-ops-BYBI_WlA.mjs";import"./media-services-DAOLsxWe.mjs";import{t as WEBCHAT_LOCAL_MEDIA_MAX_BYTES}from"./configured-max-bytes-D7sE4PVV.mjs";import{a as loadPendingSessionDeliveries}from"./session-delivery-queue-storage-DOXtELoJ.mjs";import{i as resolvePlaybackTranscode,n as replacePlaybackFileExtension,r as resolvePlaybackMetadataForSource,t as PlaybackInspectionBusyError}from"./playback-transcode-BLna216k.mjs";import{t as unlinkIfExists}from"./temp-files-RhishfNE.mjs";import{n as normalizeChatImageRenditionWidth}from"./chat-image-renditions-CrJYtcId.mjs";import{n as buildManagedMediaContentDisposition}from"./assistant-media-content-disposition-CJzSaLfG.mjs";import{n as matchesHttpIfNoneMatch}from"./http-conditional-CBtEomUz.mjs";import{i as writeByteHeaders,n as createImmutableFileValidators,r as resolveByteResponse,t as createGatewayByteStream}from"./http-byte-range-CvNBag81.mjs";import{l as resolveOpenAiCompatibleHttpSenderIsOwner,r as authorizeGatewayHttpRequestOrReply,u as resolveSharedSecretHttpOperatorScopes}from"./http-auth-utils-DoyTE-rC.mjs";import"./http-utils-C2sazj48.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-CslL9WDI.mjs";import{i as resolveManagedImageOriginalPath,n as deleteManagedImageRecordArtifacts,r as insertManagedImageRecordWithFile,t as deleteAgedOrphanManagedImageFiles}from"./managed-image-attachments.custody-DOJGHw-D.mjs";import{n as readImageThumbnailFromFile}from"./managed-image-thumbnail-cache-Btd6kKoi.mjs";import{i as createHttpImageRepresentation}from"./http-image-response-DDogkDyc.mjs";import{a as buildOutgoingVariantUrl,i as buildManagedOutgoingArtifactId,o as parseManagedOutgoingArtifactId,t as MANAGED_OUTGOING_ATTACHMENT_ID_RE}from"./managed-outgoing-artifact-id-DA2vgwrY.mjs";import{t as prepareRemoteIngressSessionRead}from"./remote-ingress-session-read-BUU5tO64.mjs";import path from"node:path";import{randomUUID}from"node:crypto";import fs from"node:fs/promises";import{sanitizeUntrustedFileName}from"@openclaw/fs-safe/advanced";
//!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`)}
//!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`}
//!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}:{}}]})}function createManagedMediaSourceLoader(e){let t;return async({source:n,localMediaPath:r,maxBytes:i})=>{if(r&&!e.mediaAccess){const n=e.localRoots;await assertLocalMediaAllowed(r,n,n===`any`?void 0:{resolveRoots:async()=>{t??=await resolveLocalMediaRoots(n);return t}})}if(e.mediaAccess&&!hasHttpUrlPrefix(n)){const{loadWebMediaRaw:t}=await import(`./web-media-BWasQ2l4.mjs`);const r=await t(n,buildOutboundMediaLoadOptions({maxBytes:i,mediaAccess:e.mediaAccess}));return await saveMediaBuffer(r.buffer,r.contentType,`outgoing/originals`,i,r.fileName)}const a=r??n;if(hasHttpUrlPrefix(a)){const{saveRemoteMediaForStore:t}=await import(`./store.remote.runtime-OptQd-la.mjs`);return await t({source:a,subdir:`outgoing/originals`,maxBytes:i,abortSignal:e.abortSignal})}return await saveMediaSource(a,void 0,`outgoing/originals`,i)}}
//!src/gateway/managed-image-session-read.ts
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})}
//!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}
//!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;let o;const getCleanupConfig=()=>o??=readRuntimeConfig();const s=i===`global`&&a?tryResolveSessionCompatibilityOwnerAgentId(getCleanupConfig(),`global`):void 0;const c=e?.forceDeleteSessionRecords===true;const l=await listManagedImageRecordEntries({stateDir:t});let u;const d=/* @__PURE__ */ new Map;for(const{record:o,cleanupPending:f}of l){const{sessionKey:l,agentId:p,messageId:m}=o;if(i&&l!==i)continue;let h;if(i===`global`){h=resolveManagedSessionOwnerAgentId(l,p,s);if(!h||h!==a)continue}if(f||c)await deleteManagedImageRecordArtifacts(o,t,f);else if(m){const e=h??resolveManagedSessionOwnerAgentId(l,p)??tryResolveSessionCompatibilityOwnerAgentId(getCleanupConfig(),l);if(!e)continue;const t=`${e}:${l}`;let n=d.get(t);if(!n){n={sessionKey:l,agentId:e,messageIds:/* @__PURE__ */ new Set,records:/* @__PURE__ */ new Map};d.set(t,n)}n.messageIds.add(m);n.records.set(buildManagedOutgoingAttachmentRefKey(m,o.attachmentId),o)}else{const i=Date.parse(o.createdAt);if(Number.isFinite(i)&&n-i>=r&&e?.hasActiveSessionRun?.(l,p?.trim()||void 0)!==true){if(u===void 0)u=await loadPendingPreparedAttachmentIds(t);if(u!==null&&!u.has(o.attachmentId))await deleteManagedImageRecordArtifacts(o,t,false)}}}for(const{sessionKey:e,agentId:n,messageIds:r,records:i}of d.values()){const a=await withManagedImageSessionRead({cfg:getCleanupConfig(),agentId:n,sessionKey:e,stateDir:t,assertCurrent:captureChannelReadScope()?.assertCurrent??(()=>{}),unavailable:false},async(e,t)=>{const n=await readManagedOutgoingAttachmentIndex(e,r);t();return n??false});if(a===false)continue;for(const[e,n]of i)if(!a?.has(e))await deleteManagedImageRecordArtifacts(n,t,false)}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 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})}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}async function resolveManagedOutgoingMediaArtifactDownload(e){const t=await resolveManagedOutgoingMediaArtifactRecord(e);return t?resolveManagedOutgoingMediaArtifactDownloadForRecord(t,e.stateDir):null}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)}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);const s=createManagedMediaSourceLoader(e);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 s({source:u,localMediaPath:h,maxBytes:Math.max(a.maxBytes,h&&(_===`audio`||_===`video`)?WEBCHAT_LOCAL_MEDIA_MAX_BYTES:0,maxBytesForKind(`audio`),maxBytesForKind(`video`),maxBytesForKind(`document`),MEDIA_MAX_BYTES)});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}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};