UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

5 lines (4 loc) • 6.05 kB
import{l as normalizeOptionalString}from"./string-coerce-CpTFcSwY.mjs";import{d as normalizeMediaFacts}from"./media-facts-03ZYaqC1.mjs";import{i as shouldLogVerbose,r as logVerbose}from"./globals-l9I53ZKA.mjs";import{n as resolveConcurrency}from"./resolve-WTRz3hbx.mjs";import{t as finalizeInboundContext}from"./inbound-context-DhAQpGu-.mjs";import{i as formatMediaUnderstandingBody,n as formatAudioTranscripts}from"./format-CO3OepTd.mjs";import{a as resolveAttachmentKind}from"./attachments.normalize-H6KPb1Ga.mjs";import{a as selectAttachments,n as runCapability}from"./runner-DeLi4UZW.mjs";import{r as sendTranscriptEcho,t as DEFAULT_ECHO_TRANSCRIPT_FORMAT}from"./echo-transcript-CpHXF0KN.mjs";import{t as resolveFileExtractionLimits}from"./file-extraction-limits-cxP57jw7.mjs";import{c as applyAttachmentMarkerBudget,n as createScopedMediaAttachmentCache,r as normalizeMediaAttachments,u as renderMediaAttachmentDisposition}from"./runner.attachments-CNy5kvmU.mjs";import{t as extractFileContext}from"./file-context-Fry77EKH.mjs";import{t as buildMediaUnderstandingRegistry}from"./provider-registry-DXDISjyv.mjs";import{t as assertMediaExecutionCurrent}from"./provider-execution-BGbeAUc3.mjs";import pMap from"p-map"; //!src/media-understanding/apply.ts const CAPABILITY_ORDER=[`image`,`audio`,`video`];const AUDIO_ONLY_CAPABILITY_ORDER=[`audio`];const EMPTY_VOICE_NOTE_PLACEHOLDER=`[Voice note could not be transcribed because the audio attachment was too small]`;const SELF_SERVE_CONTEXT_FIELDS=[`Body`,`BodyForAgent`,`agentText`];async function applyMediaUnderstanding(e){const{ctx:t,cfg:n}=e;const r=[t.CommandBody,t.RawBody,t.Body].map(e=>normalizeOptionalString(e)).find(Boolean);const i=normalizeMediaFacts(t.media);const a=normalizeMediaAttachments(t);let o;let s;const providerRegistry=()=>{if(s)throw s.error;try{return o??=buildMediaUnderstandingRegistry(e.providers,n)}catch(e){s={error:e};throw e}};const c=createScopedMediaAttachmentCache(a,e);try{const o=await pMap(e.processingMode===`files-only`?[]:e.processingMode===`audio-only`||e.processingMode===`audio-and-files`?AUDIO_ONLY_CAPABILITY_ORDER:CAPABILITY_ORDER,async r=>{const i={capability:r,cfg:n,ctx:t,attachments:c,media:a,agentId:e.agentId,agentDir:e.agentDir,workspaceDir:e.workspaceDir,providerRegistry,config:n.tools?.media?.[r],activeModel:e.activeModel,execution:e.execution};try{return await runCapability(i)}catch(e){if(shouldLogVerbose())logVerbose(`Media understanding task failed: ${String(e)}`);const t=selectAttachments({capability:r,attachments:a,policy:i.config?.attachments});return{outputs:[],decision:{capability:r,outcome:`failed`,attachments:[],attachmentDispositions:Object.fromEntries([...t.selected.map(({index:e})=>[e,{kind:`failed`}]),...t.droppedAttachmentIndexes.map(e=>[e,{kind:`not-selected`}])]),...r===`image`?{nativeVisionActive:false}:{}}}}},{concurrency:resolveConcurrency(n),stopOnError:false});if(s)throw s.error;const l=[];const u=[];const d=/* @__PURE__ */ new Set;for(const e of o){u.push(e.decision);if(e.decision.capability!==`audio`){for(const t of e.outputs)l.push(t);continue}const t=/* @__PURE__ */ new Map;for(const n of e.outputs){t.set(n.attachmentIndex,n);d.add(n.attachmentIndex)}for(const n of e.decision.attachments){const e=t.get(n.attachmentIndex);if(e)l.push(e);else if(n.attempts.some(e=>e.reason?.trim().startsWith(`tooSmall`)))l.push({kind:`audio.transcription`,attachmentIndex:n.attachmentIndex,text:EMPTY_VOICE_NOTE_PLACEHOLDER,provider:`openclaw`,model:`synthetic-empty-audio`})}}if(u.length>0)t.MediaUnderstandingDecisions=[...t.MediaUnderstandingDecisions??[],...u];if(l.length>0){const e=l.filter(e=>e.kind===`audio.transcription`);if(e.length>0){const a=formatAudioTranscripts(e);t.Transcript=a;if(r){t.CommandBody=r;t.RawBody=r}else{t.CommandBody=a;t.RawBody=a}const o=n.tools?.media?.audio;const s=formatAudioTranscripts(e.filter(e=>i[e.attachmentIndex]?.source!==`quote`));if(o?.echoTranscript&&s)await sendTranscriptEcho({ctx:t,cfg:n,transcript:s,format:o.echoFormat??`📝 "{transcript}"`})}else if(r){t.CommandBody=r;t.RawBody=r}t.MediaUnderstanding=[...t.MediaUnderstanding??[],...l]}const f=e.processingMode===`audio-only`?{blocks:[],images:[],localPathSelfServeUpgrades:[]}:await extractFileContext({attachments:a,cache:c,cfg:n,limits:resolveFileExtractionLimits(n),skipAttachmentIndexes:d.size>0?d:void 0,selfServePathsEnabled:e.selfServeLocalPaths===true,signal:e.execution?.signal,assertCurrent:e.execution?()=>assertMediaExecutionCurrent(e.execution):void 0});const p=new Set(u.map(e=>e.capability));const m=t.MediaUnderstandingDecisions??[];const h=e.deliveredImageIndexes;const g=new Set(l.map(e=>e.attachmentIndex));const _=a.flatMap(e=>{const t=resolveAttachmentKind(e);if(t!==`image`&&t!==`audio`&&t!==`video`||!p.has(t))return[];if(t===`image`&&h?.has(e.index))return[];const n=m.findLast(n=>n.capability===t&&n.attachmentDispositions?.[e.index]!==void 0);if(!n||g.has(e.index))return[];const r=n.attachmentDispositions?.[e.index];if(t===`image`&&n.nativeVisionActive!==false&&r?.kind!==`failed`)return[];const i=r?renderMediaAttachmentDisposition(t,r):null;return i?[{text:i,consumesMarkerBudget:true}]:[]});const v=applyAttachmentMarkerBudget([...f.blocks,..._]);if(l.length>0||v.length>0){const e=v.length>0?v.join(` `).trim():void 0;const enrich=t=>{const n=formatMediaUnderstandingBody({body:t,outputs:l});if(e===void 0)return n;const r=typeof n===`string`?n.trim():``;return r?`${r}\n\n${e}`.trim():e};t.agentText=enrich(t.agentText??t.BodyForAgent??t.Body);t.Body=enrich(t.Body);finalizeInboundContext(t,{forceBodyForCommands:true})}return{extractedFileImages:f.images,...f.localPathSelfServeUpgrades.length>0?{enableLocalPathSelfServe:(e,t)=>{const n=f.localPathSelfServeUpgrades;for(const r of e)for(const e of n){const n=t?.get(e.attachmentIndex);if(t&&!n)continue;const i=e.render(n);if(!i)continue;for(const t of SELF_SERVE_CONTEXT_FIELDS){const n=r[t];if(typeof n===`string`)r[t]=n.replace(e.fallback,i)}}}}:{}}}finally{await c.cleanup()}}export{applyMediaUnderstanding as t};