UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

7 lines • 27.6 kB
import{o as asDateTimestampMs,z as resolveTimestampMsToIsoString}from"./number-coercion-B3CfI447.mjs";import{c as resolveUserPath}from"./home-dir-DEN5DisQ.mjs";import{a as asOptionalRecord}from"./record-coerce-BTbqdJ3-.mjs";import{r as isPathInside}from"./path-guards-DGttsOJI.mjs";import"./utils-Dlk0IYAa.mjs";import{c as openLocalFileSafely,t as FsSafeError}from"./fs-safe-Bxzu1j4h.mjs";import{r as isIncognitoSessionKey}from"./session-key-DYtwLLn1.mjs";import{j as normalizeSessionKeyPreservingOpaquePeerIds}from"./session-key-BPgKfU2m.mjs";import{t as _usingCtx}from"./usingCtx-CUVyQ_FT.mjs";import{n as startsWithSvgRootElement}from"./svg-image-CTMopoti.mjs";import{h as readRuntimeConfig}from"./runtime-snapshot-Bg5K4JNu.mjs";import{t as GATEWAY_OWNER_PROFILE_ID}from"./user-profile-constants-abCq1jKI.mjs";import"./io-Di_yuX3t.mjs";import{t as safeEqualSecret}from"./secret-equal-BtEZdDeQ.mjs";import{t as ASSISTANT_DISPLAY_CONTENT_FIELD}from"./assistant-display-content-DZzkofMk.mjs";import{n as isCloudWorkerPlacementState}from"./session-placement-state-HPLMeUHk.mjs";import{n as authorizeOperatorScopesForMethod}from"./method-scopes-Dalbwzsv.mjs";import{i as isOpenClawIdTunnelPrincipalCurrent,p as prepareOpenClawIdTunnelPrincipal}from"./tunnel-principal-CmwEB_uz.mjs";import{t as captureResidentUserProfileAccess}from"./user-profile-list-DJsakwXy.mjs";import{t as isNamedOperatorRoleEnforcementEnabled}from"./operator-role-enforcement-FsaRvImR.mjs";import{i as resolveSessionPermissionCoreToolPolicy}from"./session-permission-exec-mode-CZtu8XtF.mjs";import{i as resolveSandboxConfigForAgent}from"./config-CNA3Oz0X.mjs";import{t as sameTranscriptEntryAnchor}from"./transcript-entry-anchor-vZDQhvT-.mjs";import{f as extractCanvasShortcodes}from"./chat-display-projection.canvas-BobptIQs.mjs";import{l as kindFromMime,n as detectMime}from"./mime-ZmYZsEjx.mjs";import{p as readPersistedMediaFacts}from"./media-facts-03ZYaqC1.mjs";import{r as parseInboundMediaUri}from"./inbound-media-uri-COqbYFEq.mjs";import{t as buildInboundMediaUriFromPath}from"./inbound-media-path-7gWp5rZS.mjs";import{t as captureSessionEntryMetadataRead}from"./session-entry-source-authority-DYDyuUDE.mjs";import{R as readSessionPendingInput}from"./session-accessor-CY8UYP4m.mjs";import{t as MAX_PAYLOAD_BYTES}from"./payload-limits-B_UjsOw2.mjs";import{r as resolveRequestedSessionAgentId}from"./session-request-agent-DmeXmT1P.mjs";import{n as readSessionTranscriptAnchorsAsync}from"./session-transcript-anchor-read-CKyqDTFK.mjs";import{r as CHAT_PENDING_INPUT_MESSAGE_PREFIX}from"./chat-history-constants-BSH0bMLP.mjs";import{r as resolvePreparedSandboxRuntimeStatus}from"./runtime-status-DDAPGR6Y.mjs";import{n as createProfileSessionEntryFilter}from"./session-sharing-read-Cm-EAfc6.mjs";import"./session-sharing-BmRcWi9h.mjs";import{l as createHttpRequestAbortSignal}from"./http-body-CsPV_uT5.mjs";import{a as getRemoteControlUiIngressContext,r as assertRemoteControlUiIngressCurrent}from"./ingress-attribution-Ct_hJMPU.mjs";import{o as resolveAssistantMediaRoutePath}from"./control-ui-resource-routes-DrYH_3y1.mjs";import{n as resolveEffectiveToolFsWorkspaceOnly}from"./tool-fs-policy-BoL1Z1rU.mjs";import{n as resolveSessionWorkspaceRoots}from"./session-workspace-roots-DetXNmKU.mjs";import{a as sendControlUiJson,i as respondPlainText,n as isReadHttpMethod,r as respondNotFound}from"./control-ui-http-utils-M5A3tWWK.mjs";import{o as resolveSandboxPathMapping,r as relativePathInsideSandboxRoot}from"./path-policy-mjUsNXiY.mjs";import{t as splitMediaFromOutput}from"./parse-BgeE6mU-.mjs";import{i as getDefaultMediaLocalRoots,n as getAgentScopedMediaLocalRoots}from"./local-roots-CThUmghK.mjs";import{o as extractOriginalFilename}from"./store-wPqhY4JR.mjs";import{i as resolveMediaReferenceLocalPathInfo}from"./media-reference-CVYMjRlF.mjs";import{n as LocalMediaAccessError,r as assertLocalMediaAllowed}from"./local-media-access-eksHnGvN.mjs";import{l as readSessionWorkerPlacementAsync}from"./session-placement-lifecycle-DBpnDf-4.mjs";import{o as readSessionMessageByIdAsync}from"./session-transcript-readers-D9Cuet3N.mjs";import{t as SCRATCH_EXPIRED_MESSAGE}from"./scratch-expiry-yO7SnowE.mjs";import{i as resolvePlaybackTranscode,n as replacePlaybackFileExtension,r as resolvePlaybackMetadataForSource,t as PlaybackInspectionBusyError}from"./playback-transcode-BLna216k.mjs";import{n as normalizeChatImageRenditionWidth}from"./chat-image-renditions-CrJYtcId.mjs";import{r as resolveAssistantMediaFilename,t as buildAssistantMediaContentDisposition}from"./assistant-media-content-disposition-CJzSaLfG.mjs";import{i as writeByteHeaders,r as resolveByteResponse,t as createGatewayByteStream}from"./http-byte-range-CvNBag81.mjs";import{_ as resolveHttpProfile,g as prepareHttpUserProfileCatalog,h as applyHttpOperatorRoleScopeCeiling,t as authorizeControlUiReadRequestOrReply}from"./http-auth-utils-DoyTE-rC.mjs";import{r as applyHttpImageContentSecurityPolicy}from"./http-image-response-DDogkDyc.mjs";import{t as resolveSessionWorkerPlacementContext}from"./session-worker-placement-context-B0iDtTpR.mjs";import{r as resolveScratchFilePath}from"./scratch-expiry-DdVFmxG5.mjs";import{t as applyControlUiSecurityHeaders}from"./control-ui-csp-CDzzUrNr.mjs";import{n as projectPendingInputMessage}from"./chat-pending-inputs-BLswMFaP.mjs";import path from"node:path";import{createHmac,randomBytes}from"node:crypto";import{readFileWindowFully,safeFileURLToPath}from"@openclaw/fs-safe/advanced"; //!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{if(e.openclawIdPrincipal&&!isOpenClawIdTunnelPrincipalCurrent(e.openclawIdPrincipal)||e.openclawIdPrincipal?.kind===`member`&&!e.profileId)return;const r=e.profileId?resolveHttpProfile(captureResidentUserProfileAccess(e.profileId).assertCurrent().id,t,e.openclawIdPrincipal):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-CRcFmMrL.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,openclawIdPrincipal:e.requestAuth.openclawIdPrincipal,...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&&isNamedOperatorRoleEnforcementEnabled(i))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){if(e.reader?.openclawIdPrincipal)try{await prepareOpenClawIdTunnelPrincipal(e.reader.openclawIdPrincipal)}catch{return}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`)}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}} //!src/gateway/control-ui-assistant-media-read.ts async function respondAssistantMediaReadFailure(e,t,n,r){if(n.destroyed||n.writableEnded)return;if(e instanceof Error&&`code`in e&&e.code===`not-found`&&resolveScratchFilePath(t))try{await r(()=>respondPlainText(n,410,SCRATCH_EXPIRED_MESSAGE));return}catch{}respondNotFound(n)}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}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(i.hostRoot,o.path)){const{readLocalWorkspacePath:e}=await import(`./local-workspace-read-CKiTR9hX.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(s,f.realPath))throw new LocalMediaAccessError(`invalid-path`,`Sandbox image backing is unavailable`);const{prepareLocalWorkspaceFileRead:t}=await import(`./local-workspace-quiescence-B2aGkIL9.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(t){if(t instanceof Error&&`code`in t&&t.code===`not-found`)return resolveScratchFilePath(e)?{available:false,code:`artifact-file-expired`,reason:SCRATCH_EXPIRED_MESSAGE,retryable:false}:{available:false,code:`file-not-found`,reason:`File not found`};if(t instanceof PlaybackInspectionBusyError)return{available:false,code:`attachment-unavailable`,reason:t.message,retryable:true};if(t instanceof FsSafeError)switch(t.code){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(t instanceof Error&&`code`in t){const e=t.code;switch(typeof e===`string`?e:``){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-file`:return{available:false,code:`not-a-file`,reason:`Not a file`}}}return{available:false,code:`attachment-unavailable`,reason:`Attachment unavailable`}}} //!src/gateway/control-ui-assistant-media-http.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}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`)}}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){sendControlUiJson(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?.();sendControlUiJson(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-LrBYZ8k0.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(()=>sendControlUiJson(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(e){await E?.close();await respondAssistantMediaReadFailure(e,c,t,publishResponse);return true}}catch(e){r.e=e}finally{r.d()}}export{handleControlUiAssistantMediaRequest};