UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

5 lines • 14.6 kB
import{o as normalizeLowercaseStringOrEmpty}from"./string-coerce-CpTFcSwY.mjs";import{c as resolveUserPath}from"./home-dir-DEN5DisQ.mjs";import{t as asNonArrayRecord}from"./record-coerce-BTbqdJ3-.mjs";import"./utils-Dlk0IYAa.mjs";import{n as sha256Hex}from"./node-crypto-DPk8agfR.mjs";import{i as MAX_VIDEO_BYTES}from"./constants-cCp4CBUF.mjs";import{d as normalizeMimeType}from"./mime-ZmYZsEjx.mjs";import{d as normalizeMediaFacts,m as readRuntimePromptMediaFacts,n as applyRunHydrationSuppression,p as readPersistedMediaFacts,s as isImageMediaFact,u as isVideoMediaFact}from"./media-facts-03ZYaqC1.mjs";import{t as getMediaDir}from"./store-path-CwOJyIi3.mjs";import{i as getAgentWorkspaceAccess}from"./workspace-access-GnBgOJqh.mjs";import{r as sanitizeImageBlocks,t as MAX_IMAGE_INPUT_BYTES}from"./tool-images-1eKyajxa.mjs";import"./store-wPqhY4JR.mjs";import{r as resolveMediaReferenceLocalPath}from"./media-reference-CVYMjRlF.mjs";import{t as log}from"./logger-DQkQvjpf.mjs";import{n as readPersistedMediaImageLayout,t as readPersistedImageBlockFactIndexes}from"./prompt-image-metadata-CADeCrZP.mjs";import{r as loadWebMediaRaw}from"./web-media-Hsoexrq2.mjs";import{t as finalizeRuntimePromptImages}from"./runtime-prompt-image-provenance-CSbvcej4.mjs";import{n as resolveSandboxedBridgeMediaPath,t as createSandboxBridgeReadFile}from"./sandbox-media-paths-BNuBX1vV.mjs";import{i as resolveMediaFactLocalRef,n as isOpenClawCliImageCachePath,r as mediaFactToImageRef}from"./images.media-refs-qk5X3mgd.mjs";import path from"node:path";import{assertNoWindowsNetworkPath,safeFileURLToPath}from"@openclaw/fs-safe/advanced"; //!src/agents/embedded-agent-runner/run/prompt-image-decisions.ts const MAX_IMAGE_DECISION_SESSIONS=1e3;const sessions=/* @__PURE__ */ new Map;function promptImageSessionKey(e){return JSON.stringify([e.sessionTarget?.storePath,e.sessionTarget?.agentId??e.agentId,e.sessionId,e.workspaceDir])}function imageHash(e){return sha256Hex(`${e.mimeType}\0${e.data}`)}async function resolvePromptImageDecisions(e){const t=JSON.stringify([Reflect.get(e.message,`idempotencyKey`)??[e.message.timestamp??e.messageIndex,e.media.map(e=>e.url??e.path??null)]]);const n=sessions.get(e.sessionKey)??/* @__PURE__ */ new Map;sessions.delete(e.sessionKey);sessions.set(e.sessionKey,n);if(sessions.size>MAX_IMAGE_DECISION_SESSIONS)for(const e of sessions.keys()){sessions.delete(e);break}const r=n.get(t);const i=await e.load(r?e.media.map((e,t)=>isImageMediaFact(e)?{...r.media.get(t)??e,hydrationSuppressed:e.hydrationSuppressed===true||!r.hashes.has(t)}:e):e.media,e.existingImages);if(!r){const r=/* @__PURE__ */ new Map;i.images.forEach((e,t)=>{const n=i.imageFactIndexes[t]??null;const a=r.get(n)??/* @__PURE__ */ new Set;a.add(imageHash(e));r.set(n,a)});const a=new Map(e.media.flatMap((e,t)=>isImageMediaFact(e)&&r.has(t)?[[t,e]]:[]));n.set(t,{media:a,hashes:r,includedCount:i.images.length,failedMediaCount:i.failedMediaCount});return i}const a=[];const o=[];i.images.forEach((e,t)=>{const n=i.imageFactIndexes[t]??null;if(r.hashes.get(n)?.has(imageHash(e))){a.push(e);o.push(n)}});const s=new Set(o);for(const e of r.hashes.keys())if(!s.has(e))r.hashes.delete(e);return{images:a,imageFactIndexes:o,failedMediaCount:r.failedMediaCount+Math.max(0,r.includedCount-a.length)}} //!src/agents/embedded-agent-runner/run/images.ts const IMAGE_EXTENSION_PATTERN=`png|jpg|jpeg|gif|webp|bmp|tiff|tif|heic|heif`;const FILE_URL_REGEX_SOURCE=`file://[^\\s<>"'\`\\]]+\\.(?:`+IMAGE_EXTENSION_PATTERN+`)`;const WINDOWS_DRIVE_PATH_REGEX_SOURCE=`(?:^|\\s|["'\`(])([A-Za-z]:[\\\\/][^\\s"'\`()\\[\\]]*\\.(?:`+IMAGE_EXTENSION_PATTERN+`))`;const PATH_REGEX_SOURCE=`(?:^|\\s|["'\`(])((\\.\\.?/|[~/])[^\\s"'\`()\\[\\]]*\\.(?:`+IMAGE_EXTENSION_PATTERN+`))`;const FILE_URL_PATTERN=new RegExp(FILE_URL_REGEX_SOURCE,`gi`);const WINDOWS_DRIVE_PATH_PATTERN=new RegExp(WINDOWS_DRIVE_PATH_REGEX_SOURCE,`gi`);const PATH_PATTERN=new RegExp(PATH_REGEX_SOURCE,`gi`);const LEGACY_ATTACHMENT_MARKER_PATTERN=/\[(?:media attached(?:\s+\d+\/\d+)?:|Image:\s*source:)\s*[^\]]+\]/gi;function normalizeRefForDedupe(e){const t=process.platform===`darwin`&&e.startsWith(`/private/var/`)?e.slice(8):e;return process.platform===`win32`?normalizeLowercaseStringOrEmpty(t):t}function detectImageReferences(e){const t=[];const n=/* @__PURE__ */ new Set;const r=e.replace(LEGACY_ATTACHMENT_MARKER_PATTERN,e=>` `.repeat(e.length));const addPathRef=(e,r)=>{const i=e.trim();const a=normalizeRefForDedupe(i);if(!i||n.has(a))return;if(!r&&!path.extname(i))return;let o=i;try{if(r)o=safeFileURLToPath(i);else assertNoWindowsNetworkPath(i,`Image path`)}catch{return}if(!r&&i.startsWith(`~`))o=resolveUserPath(i);if(isOpenClawCliImageCachePath(o))return;n.add(a);t.push({raw:i,type:`path`,resolved:o})};for(const[e,t,n]of[[FILE_URL_PATTERN,0,true],[WINDOWS_DRIVE_PATH_PATTERN,1,false],[PATH_PATTERN,1,false]]){e.lastIndex=0;let i;while((i=e.exec(r))!==null)if(i[t])addPathRef(i[t],n)}return t}function applySandboxStagedImagePaths(e,t){const n=/* @__PURE__ */ new Map;for(const e of t??[])if(e.staged===true&&e.path&&e.url?.startsWith(`media://`))n.set(e.url,e.path);if(n.size===0)return e;return e.map(e=>{const t=e.url?n.get(e.url):void 0;if(!t||e.hydrationSuppressed===true)return e;return{...e,path:t,staged:true}})}function refDedupeKey(e,t){const n=e.type===`path`&&t&&!path.isAbsolute(e.resolved)?path.resolve(t,e.resolved):e.resolved;return`${e.type}\0${normalizeRefForDedupe(n)}`}function rawAliasDedupeKey(e){return path.isAbsolute(e)||/^[A-Za-z]:[\\/]/.test(e)||/^[a-z][a-z0-9+.-]*:/i.test(e)?normalizeRefForDedupe(e):void 0}async function loadMediaFromRef(e,t,n,r=false){t.signal?.throwIfAborted();const i=r&&Boolean(e.type===`media-uri`||getAgentWorkspaceAccess(t.agentWorkspaceDir??t.workspaceDir,`prepareTurnAttachments`)?.prepareTurnAttachments);const a=i?void 0:t.sandbox;try{let r=e.resolved;if(!a)r=await resolveMediaReferenceLocalPath(r);if(a)try{r=(await resolveSandboxedBridgeMediaPath({sandbox:{...a,workspaceOnly:t.workspaceOnly},mediaPath:r,inboundFallbackDir:`media/inbound`})).resolved}catch(e){const t=e instanceof Error?e.message:``;const i=t.startsWith(`Sandbox media reference is not staged:`)?`not-staged`:/escapes|outside|not within/i.test(t)?`outside-workspace`:`invalid-path`;const a=r.startsWith(`media://`)?`managed-media`:path.isAbsolute(r)?`absolute`:`relative`;log.warn(`${n}: sandbox validation failed (reason=${i}, pathClass=${a})`);return null}else if(!path.isAbsolute(r))r=path.resolve(e.workspaceDir??t.workspaceDir,r);const o=a?void 0:i?[getMediaDir()]:(typeof t.localRoots===`function`?t.localRoots():t.localRoots)??(t.workspaceOnly?[t.workspaceDir]:void 0);const s=a?await loadWebMediaRaw(r,{maxBytes:t.maxBytes,sandboxValidated:true,readFile:createSandboxBridgeReadFile({sandbox:a})}):await loadWebMediaRaw(r,o?{maxBytes:t.maxBytes,localRoots:o}:t.maxBytes);t.signal?.throwIfAborted();return s}catch{t.signal?.throwIfAborted();log.warn(`${n}: failed to load`);return null}}async function detectAndLoadPromptImages(e){const t={failedMediaCount:0,loadedCount:0,skippedCount:0};if(!e.model.input?.includes(`image`))return{images:[],imageFactIndexes:[],detectedRefs:[],...t};const n=await e.userTurnTranscriptRecorder?.resolveMessage();const r=n?readPersistedMediaFacts(n):void 0;const i=applySandboxStagedImagePaths(normalizeMediaFacts(r?applyRunHydrationSuppression(r,e.media):e.media),e.sandbox?e.media:void 0);const a=(n?readPersistedMediaImageLayout(n):void 0)??e.mediaImageLayout;const o=/* @__PURE__ */ new Set([...a?.suppressedFactIndexes??[],...i.flatMap((e,t)=>e.hydrationSuppressed===true?[t]:[])]);const s=i.flatMap((e,t)=>isImageMediaFact(e)&&!o.has(t)?[t]:[]);const c=i.map(mediaFactToImageRef).filter(e=>Boolean(e));const l=new Map(c.map(e=>[e.factIndex,e]));const u=(()=>{if(e.imageOrder?.length===s.length)return e.imageOrder.map((e,t)=>({kind:e,factIndex:s[t]}));if(e.imageOrder?.length){const t=[...s];return[...e.imageOrder.map(e=>({kind:e,...e===`offloaded`&&t.length?{factIndex:t.shift()}:{}})),...t.map(e=>({kind:`offloaded`,factIndex:e}))]}return s.map((t,n)=>({factIndex:t,kind:!i[t]?.path&&!i[t]?.url&&n<(e.existingImages?.length??0)?`inline`:`offloaded`}))})();const d=a?.slots.length?a.slots.filter(e=>e.factIndex===void 0||!o.has(e.factIndex)):u;const f=(a?.slots??d).flatMap(e=>e.kind===`inline`?[e.factIndex??null]:[]);const p=(n?readPersistedImageBlockFactIndexes(n):void 0)??e.existingImageFactIndexes??(f.length===(e.existingImages?.length??0)?f:e.existingImages?.map(()=>null));const m=(e.existingImages??[]).map((e,t)=>({image:e,factIndex:p?.[t]??null})).filter(e=>e.factIndex===null||!o.has(e.factIndex));const takeExisting=(e,t)=>{const n=m.findIndex(t=>t.factIndex===e);const r=n>=0?n:t?m.findIndex(e=>e.factIndex===null):-1;return r>=0?m.splice(r,1)[0]:void 0};const h=d.flatMap(e=>e.kind===`offloaded`&&e.factIndex!==void 0?l.get(e.factIndex)??[]:[]);const g=new Set(h.map(t=>refDedupeKey(t,t.workspaceDir??e.workspaceDir)));const _=new Set(h.flatMap(e=>e.aliases.flatMap(e=>rawAliasDedupeKey(e)??[])));const v=detectImageReferences(e.prompt).filter(t=>!_.has(rawAliasDedupeKey(t.raw)??``)&&!g.has(refDedupeKey(t,e.workspaceDir)));const y=[...c.flatMap(({detect:e,hydrate:t,raw:n,type:r,resolved:i})=>e!==false&&(t||!i.startsWith(`http://`)&&!i.startsWith(`https://`))?[{raw:n,type:r,resolved:i}]:[]),...v];const loadRef=async(n,r=false)=>{const i=await loadMediaFromRef(n,{...e,maxBytes:MAX_IMAGE_INPUT_BYTES,signal:void 0},`Native image`,r);if(!i||i.kind!==`image`){t.skippedCount++;return null}const a={type:`image`,data:i.buffer.toString(`base64`),mimeType:i.contentType??`image/jpeg`};t.loadedCount++;return a};const b=[];for(const e of d){const n=takeExisting(e.factIndex,e.kind===`inline`);if(n){b.push(n);continue}const r=e.factIndex===void 0?void 0:l.get(e.factIndex);const i=r?.hydrate?await loadRef(r,true):null;if((r?.hydrate||e.kind===`inline`)&&!i)t.failedMediaCount++;if(i)b.push({image:i,factIndex:r?.factIndex??null})}b.push(...m);for(const e of v){const t=await loadRef(e);if(t)b.push({image:t,factIndex:null})}const x={maxBytes:e.maxBytes,maxDimensionPx:e.maxDimensionPx,verifyDecodability:true};const S=[];let C=0;for(const e of b){const n=await sanitizeImageBlocks([e.image],`prompt:images`,x);const r=n.images[0];if(r)S.push({image:{type:`image`,data:r.data,mimeType:r.mimeType},factIndex:e.factIndex});C+=n.dropped;if(n.dropped>0&&e.factIndex!==null)t.failedMediaCount++}if(C>0)log.warn(`Native image: dropped ${C} image(s) after sanitization (prompt:images).`);return{...finalizeRuntimePromptImages(S),detectedRefs:y,...t}}function buildPromptImageFailureNotice(e){return`System note: ${e} image attachment${e===1?``:`s`} could not be loaded; their image contents are unavailable. Tell the user and ask them to resend ${e===1?`the image`:`the images`}; do not claim inspection.`}const VIDEO_OMISSION={unsupported:`(video omitted: provider does not support native video)`,unavailable:`(video omitted: source unavailable)`,invalid:`(video omitted: invalid video MIME type)`,limit:`(video omitted: native video byte limit exceeded)`};async function materializeVideoFact(e,t,n){if((e.sizeBytes??0)>t.remaining)return{type:`text`,text:VIDEO_OMISSION.limit};const r=resolveMediaFactLocalRef(e);const i=r?await loadMediaFromRef({...r,workspaceDir:e.workspaceDir},{...n,maxBytes:t.remaining},`Native video`,true):null;if(!i)return{type:`text`,text:VIDEO_OMISSION.unavailable};const a=normalizeMimeType(i.contentType);if(i.kind!==`video`||!a?.startsWith(`video/`))return{type:`text`,text:VIDEO_OMISSION.invalid};if(i.buffer.length>t.remaining)return{type:`text`,text:VIDEO_OMISSION.limit};t.remaining-=i.buffer.length;return{type:`video`,data:i.buffer.toString(`base64`),mimeType:a}}async function materializePromptMediaMessages(e,t){let n;const r={remaining:MAX_VIDEO_BYTES};const i=e.findLastIndex(e=>e.role===`user`);for(const[a,o]of e.entries()){if(o.role!==`user`)continue;const s=readRuntimePromptMediaFacts(o);const c=Reflect.get(o,`__openclaw`);const l=s??readPersistedMediaFacts(o)??[];const u=readPersistedMediaImageLayout(o);if(!l.length)continue;const d=Array.isArray(o.content)?o.content:[{type:`text`,text:o.content}];const f=d.filter(e=>e.type===`image`);const load=(e,n)=>detectAndLoadPromptImages({...t,prompt:``,media:e,existingImages:n,existingImageFactIndexes:readPersistedImageBlockFactIndexes(o),mediaImageLayout:u});const p=!t.model.input?.includes(`image`)?{images:[],imageFactIndexes:[],failedMediaCount:0}:t.imageSessionKey&&(f.length>0||l.some(isImageMediaFact))?await resolvePromptImageDecisions({sessionKey:t.imageSessionKey,message:o,messageIndex:a,media:l,existingImages:f,load}):await load(l,f);const{images:m,imageFactIndexes:h}=p;const g=await(async()=>{const e=new Set(Object.values(VIDEO_OMISSION));const n=d.filter(t=>t.type===`text`&&!e.has(t.text));if(!l.some(isVideoMediaFact))return[...n,...m];const i=/* @__PURE__ */ new Map;const a=[];m.forEach((e,t)=>{const n=h[t];if(n==null)a.push(e);else i.set(n,[...i.get(n)??[],e])});for(const[e,a]of l.entries())if(isImageMediaFact(a))n.push(...i.get(e)??[]);else if(isVideoMediaFact(a))n.push(t.provider?await materializeVideoFact(a,r,t):{type:`text`,text:VIDEO_OMISSION.unsupported});n.push(...a);return n})();if((t.provider||t.onCurrentTurnImageFailure)&&p.failedMediaCount>0){if(a===i)t.onCurrentTurnImageFailure?.(p.failedMediaCount);if(!g.some(e=>e.type===`text`&&e.text===buildPromptImageFailureNotice(p.failedMediaCount)))g.push({type:`text`,text:buildPromptImageFailureNotice(p.failedMediaCount)})}n??=e.slice();if(t.provider){n[a]={role:`user`,content:g,timestamp:o.timestamp,...o.runtimeContextCarrier?{runtimeContextCarrier:true}:{},...o.runtimeContextCarrierRetained!==void 0?{runtimeContextCarrierRetained:o.runtimeContextCarrierRetained}:{}};continue}const _={...asNonArrayRecord(c)};if(p.images.length>0)_.mediaImageBlockFactIndexes=p.imageFactIndexes;else delete _.mediaImageBlockFactIndexes;const v={...o,content:g};if(Object.keys(_).length>0)Reflect.set(v,`__openclaw`,_);else Reflect.deleteProperty(v,`__openclaw`);n[a]=v}return n??e}async function hydratePromptMediaMessages(e,t){return await materializePromptMediaMessages(e,t)}async function materializeProviderContext(e){const t=await materializePromptMediaMessages(e.context.messages,{...e,model:{input:[`text`,`image`]},provider:true});e.signal?.throwIfAborted();return t===e.context.messages?e.context:{...e.context,messages:t}}export{materializeProviderContext as a,hydratePromptMediaMessages as i,detectAndLoadPromptImages as n,promptImageSessionKey as o,detectImageReferences as r,buildPromptImageFailureNotice as t};