openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
3 lines • 16.2 kB
JavaScript
import{i as e,r as t}from"./transcript-record-coerce-CPLgmAk9.mjs";import{s as n}from"./transcript-plugin-instance-invocation-7y9lfaeO.mjs";import"./transcript-redact-BJEzMNLa.mjs";import{a as r}from"./transcript-path-guards-u0N7Z9_x.mjs";import"./transcript-sqlite-error-diagnostics-CLL4Z7ly.mjs";import{i}from"./transcript-number-coercion-D2B2TTt-.mjs";import{l as a}from"./transcript-state-dir-DEo0wD2Q.mjs";import{l as o}from"./transcript-usage-DMfnyEbn.mjs";import{a as s,c,f as l,h as u,i as d,l as f,o as p,r as m,u as h}from"./transcript-chat-message-content-DeOIjx3p.mjs";import{C as g,P as _,S as v,a as y,b,i as x,o as S,p as C,r as w,s as T,v as E,x as D,y as O}from"./transcript-chat-display-projection.canvas-BVwGQyPV.mjs";import{I as k,o as A}from"./transcript-internal-runtime-context-Blo7FWkI.mjs";import{p as j,t as M,y as N}from"./transcript-tool-call-xml-BuZjCNyQ.mjs";import P from"node:path";import{safeFileURLToPath as F}from"@openclaw/fs-safe/advanced";const I=/^\[([^\]]+)\]\s*/,L=[`WebChat`,`WhatsApp`,`Telegram`,`Signal`,`Slack`,`Discord`,`Google Chat`,`iMessage`,`Teams`,`Matrix`,`Zalo`,`Zalo Personal`];function looksLikeEnvelopeHeader(e){return/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}Z\b/.test(e)||/\d{4}-\d{2}-\d{2} \d{2}:\d{2}\b/.test(e)?!0:L.some(t=>e.startsWith(`${t} `))}function stripEnvelope(e){let t=e.match(I);return!t||!looksLikeEnvelopeHeader(t[1]??``)?e:e.slice(t[0].length)}function estimateBase64DecodedBytes(e){let t=e.length,n=e.search(/[\x00-\x20]/);if(n!==-1)for(let r=n;r<e.length;r+=1)e.charCodeAt(r)<=32&&--t;if(t===0)return 0;let r=0,i=e.length-1;for(;i>=0&&e.charCodeAt(i)<=32;)--i;if(i>=0&&e[i]===`=`){for(r=1,--i;i>=0&&e.charCodeAt(i)<=32;)--i;i>=0&&e[i]===`=`&&(r=2)}let a=Math.floor(t*3/4)-r;return Math.max(0,a)}function base64DataValue(e){return e>=65&&e<=90?e-65:e>=97&&e<=122?e-97+26:e>=48&&e<=57?e-48+52:e===43?62:e===47?63:-1}function canonicalizeBase64(e){let t=inspectBase64(e,`canonical`);return t?.canonicalPadBits?t.base64:void 0}function inspectBase64(e,t){if(t===`attachment`&&(e.length===0||e.length%4!=0))return;let n,r=0,i=0,a=0;for(let o=0;o<e.length;o+=1){let s=e.charCodeAt(o);if(s<=32){if(t===`attachment`)return;if(n===void 0){n=Buffer.allocUnsafe(e.length-1);for(let t=0;t<o;t+=1)n[t]=e.charCodeAt(t);r=o}}else{if(s===61){if(i+=1,i>2)return}else{let e=base64DataValue(s);if(i>0||e<0)return;a=e}n!==void 0&&(n[r]=s,r+=1)}}let o=n===void 0?e.length:r;if(o===0)return;let s=o%4;if(s!==0&&(i>0||s===1))return;let c=s===0?i:4-s,l=c===2?15:c===1?3:0,u=n===void 0?e:n.subarray(0,r).toString(`latin1`);return{base64:s===0?u:u+`=`.repeat(4-s),decodedBytes:Math.floor(o*3/4)-i,canonicalPadBits:(a&l)===0}}function stripInternalMetadataForDisplay(e){return N(A(e))}function prepareAgentRunReplyText(e){if(!u(e))return l(e)??e.replace(/[\r\n]\s*NO_REPLY\s*$/iu,``)}function getMediaDir(){return P.join(n(),`media`)}function maybeLocalPathFromSource(e){if(/^file:/i.test(e))try{return F(e)}catch{return null}return e.startsWith(`~`)?a(e):P.isAbsolute(e)?e:null}function buildInboundMediaUriFromPath(e){let t=maybeLocalPathFromSource(e.trim());if(!t)return;let n=P.resolve(getMediaDir(),`inbound`),i=P.relative(n,P.resolve(t));if(!(!i||r(i)||i.includes(P.sep)||i.includes(`\\`)))try{return _(`media://inbound/${i}`)?.normalizedSource}catch{return}}function findNativeToolMarkerTextBlocks(t){let n=/* @__PURE__ */ new Set,r=e(t);if(r?.role!==`assistant`||s(r.phase)||!Array.isArray(r.content))return n;let i=0,a=``,o=``,c=!1;for(let t=0;t<=r.content.length;t++){let s=e(r.content[t]);if(s&&m(s.type)&&typeof s.text==`string`)a+=s.text,c||=!!p(s)?.phase;else{if(s?.type===`toolCall`&&!c&&a.includes(`<`)&&!M({stripFunctionCallsXmlPayloads:!0},!0).transform(a.trimEnd()).trim()&&!k(o.length+a.indexOf(`<`),j(o+a)))for(let e=i;e<t;e++)n.add(e);o=c?``:`${o}${a}\n`,i=t+1,a=``,c=!1}}return n}function projectAssistantCommentaryFallbacks(t,n){let r=e(t);if(!r||r.role!==`assistant`||d(r)||!Array.isArray(r.content)||r.stopReason===`error`||typeof r.errorMessage==`string`)return{fallbacks:[],message:t};let i=e(r.__openclaw),a=new Set(c(r,`commentary`)),o=typeof i?.id==`string`?i.id.trim():typeof r.id==`string`?r.id.trim():void 0,s=[],l=/* @__PURE__ */ new Set,u=!1,f;for(let t of r.content){let n=e(t);if(!n)continue;if(!m(n.type)){f&&[`image`,`audio`,`video`,`attachment`,`attachment_error`].includes(String(n.type))&&(f.content.push(n),f.sourceBlocks.push(t));continue}let r=p(n),i=typeof n.text==`string`?n.text:``,c=r?.id?.trim(),l=c||o;!a.has(t)||!l?f=void 0:(f?.itemId!==l&&(f={itemId:l,providerKeyed:!!c,content:[],text:[],sourceBlocks:[]},s.push(f)),f.providerKeyed||=!!c,r?.phase!==`commentary`&&f.sourceBlocks.push(t),i.trim()&&(f.content.push({type:`text`,text:i}),f.text.push(i)))}let h=s.flatMap(({itemId:t,providerKeyed:a,content:o,text:s,sourceBlocks:c})=>{let d=o.some(e=>e.type!==`text`);if(o.length===0||!a&&!d)return[];for(let t of c)l.add(t),u||=m(e(t)?.type);let f=g(s.join(`
`),n),p=f.truncated?{...i,truncated:!0,reason:typeof i?.reason==`string`?i.reason:`display-cap`}:i?{...i}:void 0;return[{role:`assistant`,content:o,...typeof r.timestamp==`number`?{timestamp:r.timestamp}:{},openclawStreamFallback:{replacementText:f.text,source:`segment`,itemId:t},...p?{__openclaw:p}:{}}]});if(l.size===0)return{fallbacks:h,message:t};let _=r.content.filter(e=>!l.has(e)),v={...r,content:_};return u&&_.some(t=>w(e(t)?.type))&&(v.content=_.filter(e=>!a.has(e)),delete v.phase),{fallbacks:h,message:v}}function projectWorkspaceResultConflict(e,t,n){let r=[...new Set(e)].toSorted(),i=[],a=0;for(let e of r){let t=Buffer.byteLength(e);if(i.length>=256||a+t>32768)break;i.push(e),a+=t}if(i.length===0)throw Error(`Cloud workspace result conflict projection has no bounded path`);return{paths:i,stagedResultRef:t,totalCount:Math.max(n??r.length,r.length)}}function projectWorkspaceConflictDetails(t){if(t.role!==`custom`||t.customType!==`cloud-workspace-conflict`)return;let n=e(t.details),r=n?.totalCount;if(!(!n||!Array.isArray(n.paths)||n.paths.length===0||!n.paths.every(e=>typeof e==`string`&&e.length>0)||typeof n.stagedResultRef!=`string`||!/^refs\/openclaw\/worker-results\/[A-Za-z0-9-]+$/u.test(n.stagedResultRef)||r!==void 0&&(typeof r!=`number`||!Number.isSafeInteger(r)||r<n.paths.length)))try{return projectWorkspaceResultConflict(n.paths,n.stagedResultRef,r)}catch{return}}const R=[`data`,`blob`,`path`,`file`,`filePath`,`localPath`],z=[`url`,`openUrl`,`image_url`,`audio_url`,`video_url`],B=[`workspaceDir`,...R.filter(e=>e!==`path`)];function projectChatHistoryMediaReference(e){if(typeof e!=`string`)return;let t=e.trim();if(/^\/(?:api\/chat\/media\/outgoing|media|__openclaw__)\//u.test(t))return t.split(/[?#]/u,1)[0];try{if(/^media:/iu.test(t))return _(t)?.normalizedSource;let e=new URL(t);return e.protocol!==`http:`&&e.protocol!==`https:`?void 0:(e.username=e.password=e.search=e.hash=``,e.toString())}catch{return}}function projectChatHistoryMediaBlock(t,n=!1){if(!n&&(typeof t.type!=`string`||!/^(?:image|audio|video)$/u.test(t.type)))return!1;let r=t,i=typeof r.data==`string`||typeof r.blob==`string`,a=n?void 0:e(r.source),o=a?{...a}:void 0,s=[r,...o?[o]:[]];o&&(r.source=o);let c=n?B:R,l=n?[`path`,`url`]:z,u=!a&&(!n||typeof r.source!=`string`||/^(?:[a-z][a-z0-9+.-]*:|~?[\\/])|[\\/]/iu.test(r.source)),d;for(let e of s){let t=!1,i=typeof e.data==`string`?e.data:e.blob;d===void 0&&typeof i==`string`&&(d=i);for(let n of c)Object.hasOwn(e,n)&&(delete e[n],t=!0);let a=e===r&&u?[...l,`source`]:l;for(let r of a){if(!Object.hasOwn(e,r))continue;let i=(n?buildInboundMediaUriFromPath(String(e[r])):void 0)??projectChatHistoryMediaReference(e[r]);e[r]=i,i===void 0&&(delete e[r],t=!0)}!n&&t&&((e===r||r.type!==`image`)&&(e.omitted=!0),(e===r||r.type!==`audio`)&&(r.omitted=!0))}return!n&&d!==void 0&&((r.type===`audio`&&!i&&o?o:r).bytes=estimateBase64DecodedBytes(d)),!0}function projectChatHistoryAttachmentBlock(t){let n=t.type===`attachment`?e(t.attachment):void 0;if(!n)return!1;let r={...n};for(let e of R)delete r[e];return r.url=projectChatHistoryMediaReference(r.url),r.url||delete r.url,t.attachment=r,!0}function projectChatHistoryMediaFacts(t){return Array.isArray(t)?t.map(t=>{let n={...e(t)};return projectChatHistoryMediaBlock(n,!0),n}):void 0}function sanitizeChatHistoryContentBlock(t,n){if(!t||typeof t!=`object`)return{block:t,changed:!1,truncated:!1};let r={...t};if(r.type===`plugin_view`)return{block:{type:`text`,text:``},changed:!0,truncated:!1};let i=D(r),a=!1,o=n?.preserveExactToolPayload===!0||w(r.type),s=n?.maxChars??8e3,c=n?.preserveExactToolPayload||x(r.type)?n?.toolResultMaxChars:void 0;if(x(r.type)&&`details`in r){let e=S(r.details,s,r);e.details?r.details=e.details:delete r.details,i=!0,a||=e.truncated}if(o&&Array.isArray(r.content)){if(typeof r.text==`string`){let t=r.content.flatMap(t=>{let n=e(t)?.text;return typeof n==`string`?[n]:[]}).join(`
`);r.text===t&&(delete r.text,i=!0)}let t=r.content.map(e=>sanitizeChatHistoryContentBlock(e,{preserveExactToolPayload:!0,maxChars:s,toolResultMaxChars:c}));t.some(e=>e.changed)&&(r.content=t.map(e=>e.block),i=!0),a||=t.some(e=>e.truncated)}for(let e of[`text`,`content`,`partialJson`,`arguments`,`thinking`]){if(typeof r[e]!=`string`||o&&(e===`partialJson`||e===`arguments`))continue;let t=g(r[e],s,o&&(e===`text`||e===`content`),e===`text`||e===`content`?c:void 0);r[e]=t.text,i||=t.truncated,a||=t.truncated}for(let e of[`thinkingSignature`,`openclawReasoningReplay`])e in r&&(delete r[e],i=!0);let l=projectChatHistoryMediaBlock(r),u=projectChatHistoryAttachmentBlock(r);return i||=l||u,{block:i?r:t,changed:i,truncated:a}}function sanitizeAssistantPhasedContentBlocks(e){if(!e.some(e=>{let n=t(e);return n&&m(n.type)&&p(n)?.phase}))return e;let n=e.filter(e=>{let n=t(e);return!n||!m(n.type)||p(n)?.phase===`final_answer`});return n.length===e.length?e:n}function projectAssistantMixedToolContent(e,n){if(!e.some(e=>w(t(e)?.type)))return null;let r=!1,i=[];for(let a of e){let e=t(a);if(!e)continue;if(!m(e.type)){i.push(a);continue}if(p(e)?.phase===`commentary`||typeof e.text!=`string`||!e.text.trim())continue;let o=g(e.text,n);o.text.trim()&&(i.push({type:`text`,text:o.text}),r=!0)}return r?i:null}const V=[`input`,`output`,`cacheRead`,`cacheWrite`,`total`],H=[`input`,`output`,`total`,`totalTokens`,`inputTokens`,`outputTokens`,`promptTokens`,`completionTokens`,`cacheRead`,`cacheWrite`,`cache_read_input_tokens`,`cache_creation_input_tokens`,`input_tokens`,`output_tokens`,`prompt_tokens`,`completion_tokens`,`total_tokens`];function sanitizeNumericMetadata(e,n){let r=t(e);if(!r)return;let a={};for(let e of n){let t=i(r[e]);t!==void 0&&(a[e]=t)}if(n===H){let e=t(r.usageReport)?.state;(e===`available`||e===`unavailable`)&&(a.usageReport={state:e});let n=sanitizeNumericMetadata(r.cost,V);n&&(a.cost=n);let i=o(r.contextUsage);i&&(a.contextUsage=i)}return Object.keys(a).length>0?a:void 0}function prepareAssistantHistoryMessage(e){let n=t(e);if(n?.role!==`assistant`||n.display===!0||n.display===!1||f(n)||E(n))return e;let r=typeof n.text==`string`?`text`:`content`,i=n[r];if(typeof i!=`string`&&!Array.isArray(n.content))return e;let a=c(n,`final_answer`),o=a.length?a:c(n),s=typeof i==`string`?i:o.map(e=>e.text).join(``),l=prepareAgentRunReplyText(s);if(l===void 0||l===s)return e;if(typeof i==`string`)return{...n,[r]:l,display:!0};let u=s.endsWith(l)?s.length-l.length:0,d=l.length,p=/* @__PURE__ */ new Map;for(let e of o){let t=Math.min(u,e.text.length);u-=t;let n=e.text.slice(t,t+d);d-=n.length,n!==e.text&&p.set(e,{...e,text:n})}return{...n,content:Array.isArray(n.content)?n.content.map(e=>p.get(e)??e):n.content,display:!0}}function sanitizeChatHistoryMessage(t,n=T,r){if(!t||typeof t!=`object`)return{message:t,changed:!1};let i=prepareAssistantHistoryMessage(t),a={...i},o=i!==t,s=findNativeToolMarkerTextBlocks(t);s.size&&Array.isArray(a.content)&&(a.content=a.content.map((t,n)=>s.has(n)?{...e(t),text:``}:t),o=!0);let c=!1;(`providerReplay`in a||`openclawResponsesInputReplay`in a)&&(delete a.providerReplay,delete a.openclawResponsesInputReplay,o=!0);let l=e(a.__openclaw);if(l&&(`upstreamUserText`in l||`modelPromptProjection`in l||`sessionSendDelivery`in l||`requesterOrigin`in l||`chatInputRecovery`in l||`media`in l)){let e={...l};delete e.upstreamUserText,delete e.modelPromptProjection,delete e.sessionSendDelivery,delete e.requesterOrigin,delete e.chatInputRecovery,`media`in e&&(e.media=projectChatHistoryMediaFacts(e.media),e.media===void 0&&delete e.media),Object.keys(e).length>0?a.__openclaw=e:delete a.__openclaw,o=!0}let u=typeof a.role==`string`?a.role.toLowerCase():``,d=v(a,u);o||=d.changed;let f=u===`toolresult`||u===`tool_result`||u===`tool`||u===`function`||typeof a.toolName==`string`||typeof a.tool_name==`string`||typeof a.toolCallId==`string`||typeof a.tool_call_id==`string`,p=f&&y(a)?r:void 0;if(`details`in a){let t=projectWorkspaceConflictDetails(a),r=!t&&y(a)?S(a.details,n,a):void 0,i=a.role===`custom`&&a.customType===`run-failed-before-reply`&&e(a.details)?.errorKind===`state_contention`?{errorKind:`state_contention`,diagnostic:`SQLite transaction admission remained busy. Execution may have occurred; check the recorded outcome before resending.`}:void 0,s=a.role===`custom`&&a.customType===`session-model-change`?e(a.details):void 0,l=typeof s?.from==`string`&&typeof s.to==`string`?{from:s.from,to:s.to}:void 0,u=t??r?.details??i??l;u?a.details=u:delete a.details,o=!0,c||=r?.truncated===!0}for(let e of[`usage`,`cost`]){if(!(e in a))continue;let t=a.role===`assistant`?sanitizeNumericMetadata(a[e],e===`usage`?H:V):void 0;t?a[e]=t:delete a[e],o=!0}let h=u===`assistant`&&!O(a),projectText=e=>{let t=g(e,n,f,p),r=h?b(t.text,d.urls):t.text;return o||=r!==t.text,o||=t.truncated,c||=t.truncated,r};if(typeof a.content==`string`)a.content=projectText(a.content);else if(Array.isArray(a.content)){let t=a.content,i=e(a.openclawStreamFallback)?.source===`segment`,s=n,l;for(let a=0;a<t.length;a++){let o=i?e(t[a]):void 0,u=o&&m(o.type)&&typeof o.text==`string`?o.text:void 0;if(u!==void 0&&s<=0){l??=t.slice(),l[a]=void 0,c||=u.length>0;continue}let p=sanitizeChatHistoryContentBlock(t[a],{preserveExactToolPayload:f,maxChars:u===void 0?n:s,toolResultMaxChars:r});u!==void 0&&(s-=u.length+1);let g=h?e(p.block):void 0;if(g&&m(g.type)&&typeof g.text==`string`){let e=b(g.text,d.urls);e!==g.text&&(p.block={...g,text:e},p.changed=!0)}p.changed&&(l??=t.slice(),l[a]=p.block),c||=p.truncated}if(l&&(a.content=i?l.filter(e=>e!==void 0):l,o=!0),a.role===`assistant`&&Array.isArray(a.content)){let e=projectAssistantMixedToolContent(a.content,n);if(e)a.content=e,a.phase===`commentary`&&delete a.phase,o=!0;else{let e=sanitizeAssistantPhasedContentBlocks(a.content);e!==a.content&&(a.content=e,o=!0)}}}if(typeof a.text==`string`&&(a.text=projectText(a.text)),c){let t=e(a.__openclaw);a.__openclaw={...t,truncated:!0,reason:typeof t?.reason==`string`?t.reason:`display-cap`},o=!0}return{message:o?a:t,changed:o}}function hasAssistantMixedToolVisibleText(e){let n=t(e)?.content;if(!Array.isArray(n))return!1;let r=!1,i=!1;for(let e of n){let n=t(e);n&&(r||=w(n.type),m(n.type)&&typeof n.text==`string`&&n.text.trim()&&(i=!0))}return r&&i}function shouldDropAssistantHistoryMessage(e){let n=t(e);return n?.role===`assistant`?n.display===!1?!0:n.display===!0||f(n)||E(n)?!1:h(e)===`commentary`?!hasAssistantMixedToolVisibleText(e):d(e):!1}function sanitizeChatHistoryMessages(t,n=T,r){let i=!1,a=[];for(let o of t){let t=o;if(r?.includeCommentaryFallbacks===!0){let s=projectAssistantCommentaryFallbacks(t,n);t=s.message,i||=t!==o;for(let t of s.fallbacks){if(i=!0,!C(e(t)??{})&&shouldDropAssistantHistoryMessage(t))continue;let o=sanitizeChatHistoryMessage(t,n,r?.toolResultMaxChars);a.push(o.message)}}if(shouldDropAssistantHistoryMessage(t)){i=!0;continue}let s=sanitizeChatHistoryMessage(t,n,r?.toolResultMaxChars);i||=s.changed,a.push(s.message)}return i?a:t}export{shouldDropAssistantHistoryMessage as a,estimateBase64DecodedBytes as c,sanitizeChatHistoryMessages as i,stripEnvelope as l,sanitizeChatHistoryContentBlock as n,stripInternalMetadataForDisplay as o,sanitizeChatHistoryMessage as r,canonicalizeBase64 as s,prepareAssistantHistoryMessage as t};