UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

9 lines • 18.2 kB
import{a as asOptionalRecord}from"./record-coerce-BTbqdJ3-.mjs";import{r as isIncognitoSessionKey}from"./session-key-DYtwLLn1.mjs";import{Et as _enum,Fn as object,Jn as string}from"./schemas-DuCQi-Qb.mjs";import{t as isNormalizedMessageChannel}from"./message-channel-core-D_hPOadj.mjs";import{s as resolveSessionTranscriptActiveLeafEntryId}from"./transcript-tree-Dwc2Zlw1.mjs";import{r as augmentChatHistoryWithCanvasBlocks}from"./chat-display-projection.canvas-BobptIQs.mjs";import{i as sanitizeChatHistoryMessages}from"./chat-display-projection.sanitize-DPZ4F1ws.mjs";import{t as composeTranscriptDisplay}from"./transcript-display-position-Ct20PUM8.mjs";import{i as jsonUtf8Bytes}from"./json-utf8-bytes-BzjXgHQ3.mjs";import{n as createTranscriptDisplaySource}from"./transcript-display-position-CTVyCp-i.mjs";import{c as readLegacyCompactionMetrics}from"./session-accessor.sqlite-references-B7aXsOVx.mjs";import{r as getCliSessionBinding}from"./cli-session-binding-uwQzKK6C.mjs";import{t as captureSessionActorTranscriptRead}from"./session-actor-transcript-read-CNdxAppm.mjs";import{t as resolveCurrentUserProfileDisplay}from"./current-user-profile-display-DM7faKkD.mjs";import{c as projectChatDisplayMessagesWithState,t as createChatHistoryRecoveryProjection}from"./chat-display-projection.core-Cc0urtjV.mjs";import{d as projectedHistoryTurnBoundary,h as mapChatDisplayMessages,l as projectForwardedMessages,r as dropPreSessionStartAnnouncePairs}from"./chat-display-projection.history-BLPBlOOA.mjs";import{a as readChatHistoryAnchorPage,c as readChatHistoryPaginationKey,l as readChatHistoryRecoveryContext,o as readChatHistoryMessageId,r as dropChatHistoryOverreadContextMessage,s as readChatHistoryMessageSeq,t as createSessionActorTranscriptReader,u as readIncrementalChatHistoryTail}from"./session-transcript-memory-reader-DHqE4Ev8.mjs";import{_ as session_transcript_readers_exports}from"./session-transcript-readers-D9Cuet3N.mjs";import{n as resolveClaudeCliProjectsDir}from"./claude-cli-project-dir-PHqOOfKz.mjs";import{a as createChatHistoryActivityProjection,l as replaceOversizedChatHistoryMessages,o as createChatHistoryByteCounter,r as buildOversizedHistoryPlaceholder,t as CHAT_HISTORY_MAX_SINGLE_MESSAGE_BYTES}from"./chat-history-budget-xZqiK_CO.mjs";import{t as prepareForwardedMessageCronJobNameResolver}from"./chat-display-projection.cron-Crkajb6k.mjs";import{n as projectChatHistoryWithReplies,t as attachChatHistoryReplyMessages}from"./chat-history-reply-messages-BjVkJUZo.mjs";import{constants,deflateRawSync}from"node:zlib"; //!src/gateway/chat-history-page-cursor.ts const PREFIX=`history-page:`;const MAX_CURSOR_CHARS=4096;const cursorSchema=object({sessionId:string().min(1).max(1024),source:string().min(1).max(128),messageId:string().min(1).max(1024),direction:_enum([`older`,`newer`])});function encodeChatHistoryPageCursor(e){if(!cursorSchema.safeParse(e).success)return;const t=PREFIX+Buffer.from(JSON.stringify(e)).toString(`base64url`);return t.length<=MAX_CURSOR_CHARS?t:void 0}function decodeChatHistoryPageCursor(e){if(!e?.startsWith(PREFIX))return;if(e.length>MAX_CURSOR_CHARS)return null;try{const t=cursorSchema.safeParse(JSON.parse(Buffer.from(e.slice(13),`base64url`).toString(`utf8`)));return t.success?t.data:null}catch{return null}}function resolveChatHistorySelectorError({offset:e,messageId:t,cursor:n,sessionId:r},i,a){if(i===null)return`invalid history page cursor`;if(e!==void 0&&t!==void 0)return`offset and messageId cannot be used together`;if(n!==void 0&&(e!==void 0||t!==void 0))return`cursor cannot be used with offset or messageId`;if(r!==void 0&&t===void 0)return`sessionId requires messageId`;if(i&&a&&i.sessionId!==a)return`history page cursor does not belong to retained chat history`}function resolveChatHistoryPageCursors(e,t,n){if(!e)return{};const r=readChatHistoryMessageId(t[0]);const i=t.length>0&&r!==readChatHistoryMessageId(n[0]);const a=i?r:e.oldestMessageId??r;const o=readChatHistoryMessageId(t.at(-1))??e.newestMessageId;const cursor=(t,n)=>encodeChatHistoryPageCursor({sessionId:e.sessionId,source:e.source,messageId:t,direction:n});return{...a&&(e.hasOlder||i)?{olderCursor:cursor(a,`older`)}:{},...o&&(e.hasNewer||t.length>0&&o!==readChatHistoryMessageId(n.at(-1)))?{newerCursor:cursor(o,`newer`)}:{}}} //!src/gateway/chat-history-response-page.ts function readPageMessageSequence(e,t){if(typeof t===`function`)return t(e);return t?.[readChatHistoryPaginationKey(e)??``]??readChatHistoryMessageSeq(e)}function enrichChatHistoryCompactionMarkers(e,t,n=readLegacyCompactionMetrics(t)){if(n.length===0)return e;const r=new Map(n.map(e=>[e.entryId,e]));return mapChatDisplayMessages(e,e=>{const t=asOptionalRecord(e);const n=asOptionalRecord(t?.[`__openclaw`]);if(n?.kind!==`compaction`||typeof n.id!==`string`)return e;const i=r.get(n.id);if(!i)return e;const a=i.tokensBefore;const o=i.tokensAfter;if(a===void 0&&o===void 0)return e;return{...t,__openclaw:{...n,...a!==void 0?{tokensBefore:a}:{},...o!==void 0?{tokensAfter:o}:{}}}})}function resolveChatHistoryMessageGroup(e,t,n,r,i=Infinity){const a=readPageMessageSequence(e[t],r);let o=t;let s=t+1;let c=n(e[t]);if(a!==void 0){while(o>0&&readPageMessageSequence(e[o-1],r)===a){o-=1;if(c<=i)c+=n(e[o])}while(s<e.length&&readPageMessageSequence(e[s],r)===a){if(c<=i)c+=n(e[s]);s+=1}}return{start:o,end:s,cost:c,messages:e,sourceStart:o,sourceEnd:s}}function selectChatHistoryResponsePage(e,{entry:t,compactionMetrics:n,maxHistoryBytes:r,responseHistoryBytes:i=r,messageId:a},o=e.pagination?.messageSequences??e.anchor?.messageSequences,s=jsonUtf8Bytes){const c=enrichChatHistoryCompactionMarkers(e.messages,t,n);const l=createChatHistoryActivityProjection(c,e.activity);const u=createChatHistoryByteCounter(l,s);const d=i-(1+u.framingBytes(c));const messageCost=e=>u.messageBytes(e)+1;const f=Math.min(CHAT_HISTORY_MAX_SINGLE_MESSAGE_BYTES,d-1);const prepareGroup=e=>{const t=resolveChatHistoryMessageGroup(c,e,messageCost,o,d);let n=c;if(t.cost>d)n=[buildOversizedHistoryPlaceholder(c.slice(t.start,t.end).find(e=>readChatHistoryMessageId(e)===a)??c[t.end-1])];else if(t.cost-1>f)n=c.slice(t.start,t.end);if(n!==c)n=replaceOversizedChatHistoryMessages({byteCounter:u,messages:n,maxSingleMessageBytes:f}).messages;t.messages=n;if(n!==c){t.start=0;t.end=n.length}return t};const walk=(e,t,n)=>{let r=e;let i=t;return()=>{if(i<r.start||i>=r.end){const e=n===-1?r.sourceStart-1:r.sourceEnd;if(e<0||e>=c.length)return;r=prepareGroup(e);i=n===-1?r.end-1:r.start}const e=r.messages===c?r:resolveChatHistoryMessageGroup(r.messages,i,messageCost,o);i=n===-1?e.start-1:e.end;return e}};const p=[];const m=[];let h=0;let g=false;const _=a&&e.anchor?.direction;const v=_?_===`newer`?0:c.length-1:a?c.findIndex(e=>readChatHistoryMessageId(e)===a):c.length-1;if(v>=0&&v<c.length){let e=prepareGroup(v);let t=-1;if(a){const n=_?readChatHistoryMessageId(_===`newer`?e.messages[e.start]:e.messages[e.end-1])??a:a;if(_&&n===a){const t=c.findIndex(e=>readChatHistoryMessageId(e)===a);if(t>=0&&(t<e.sourceStart||t>=e.sourceEnd))e=prepareGroup(t)}t=e.messages.findIndex(e=>readChatHistoryMessageId(e)===n)}const n=t<0?void 0:resolveChatHistoryMessageGroup(e.messages,t,messageCost,o);if(a&&!n)g=true;else if(n&&!(n.cost<=d)){m.push(e.messages[t]);g=e.sourceStart>0||e.sourceEnd<c.length||e.end-e.start>1}else{if(n){for(let t=n.start;t<n.end;t++)m.push(e.messages[t]);h=n.cost}const t=walk(e,n?n.start-1:e.end-1,-1);const r=n?walk(e,n.end,1):void 0;const grow=(e,t,n)=>{const r=e();if(!r)return false;if(!(h+r.cost<=d)){g=true;return false}for(let e=r.start;e<r.end;e++)t.push(r.messages[n?r.end-1-(e-r.start):e]);h+=r.cost;return true};let i=true;let a=Boolean(r);while(i||a){i&&=grow(t,p,true);a&&=Boolean(r&&grow(r,m,false))}}}else g=c.length>0;const y=p.length+m.length===c.length&&p.every((e,t)=>e===c[p.length-1-t])&&m.every((e,t)=>e===c[p.length+t])?c:p.toReversed().concat(m);return{normalized:c,activity:l,byteCounter:u,byteLimited:g,capped:y,responseHistoryBytes:i}}function isChatHistoryResponsePageByteLimited(...e){const{normalized:t,byteLimited:n,capped:r}=selectChatHistoryResponsePage(...e);if(!n)return false;const i=new Set(r);return t.some(e=>!i.has(e))}function prepareChatHistoryResponsePage(...e){const[t]=e;const{normalized:n,activity:r,byteCounter:i,byteLimited:a,capped:o,responseHistoryBytes:s}=selectChatHistoryResponsePage(...e);const c=t.pagination;let l;if(c!==void 0){let e;for(const t of o){e=readPageMessageSequence(t,c.messageSequences);if(e!==void 0)break}l=e===void 0?c.offset+c.rawPageMessages:Math.max(c.offset+1,c.totalMessages-e+1)}const u=resolveChatHistoryPageCursors(t.anchor,o,n);const d=c!==void 0&&l!==void 0?l<c.totalMessages&&(!t.anchor||t.anchor.hasOlder||a):void 0;const f=new Set(o);const p=n.reduce((e,t)=>e+(f.has(t)?0:1),0);return{messages:composeTranscriptDisplay(o),...o.some(e=>r.has(e))?{activity:o.flatMap(e=>r.get(e)??[])}:{},messagesBytes:i.messagesBytes(o),...p>0?{omission:{omittedCount:p,...a?{byteLimited:true}:{}}}:{},responseHistoryBytes:s,...u,...d?{nextOffset:l}:{},...d!==void 0?{hasMore:d}:{},...c!==void 0?{totalMessages:c.totalMessages}:{}}}function encodeChatHistoryResponsePage(e,t){if(!t.encodeResponse)return e;if(t.deferChannelUserDisplay&&e.messages.some(e=>{const t=asOptionalRecord(e);const n=asOptionalRecord(asOptionalRecord(t?.[`__openclaw`])?.transport);return t?.role===`user`&&typeof n?.channel===`string`&&typeof n.accountId===`string`&&isNormalizedMessageChannel(n.channel)}))return e;const n=/* @__PURE__ */ new Map;const serialize=e=>{if(!n.has(e))n.set(e,JSON.stringify(e));return n.get(e)};const r=prepareChatHistoryResponsePage(e,t,void 0,e=>{try{return Buffer.byteLength(serialize(e)??String(e),`utf8`)}catch{return Buffer.byteLength(String(e),`utf8`)}});const i=new TextEncoder;const encodeArray=e=>{const t=e.map(e=>serialize(e)??`null`);const n=new Uint8Array(2+Math.max(0,t.length-1)+t.reduce((e,t)=>e+Buffer.byteLength(t),0));n[0]=91;let r=1;for(const[e,a]of t.entries()){if(e>0)n[r++]=44;r+=i.encodeInto(a,n.subarray(r)).written}n[r]=93;return n};const a=encodeArray(r.messages);const o=r.activity?encodeArray(r.activity):void 0;return{...e,messages:[],activity:void 0,pagination:void 0,anchor:void 0,encodedMessagesDeflate:t.deflateResponse&&a.byteLength>=4096?new Uint8Array(deflateRawSync(a,{level:1,finishFlush:constants.Z_SYNC_FLUSH})):void 0,encodedResponse:{...r,messages:a,activity:o}}} //!src/gateway/chat-history-page-kernel.ts function resolveChatHistoryActiveLeafEntryId(e){if(e.transcriptSource!==`active`)return null;if(Object.hasOwn(e,`activeLeafEntryId`))return e.activeLeafEntryId??null;return resolveSessionTranscriptActiveLeafEntryId(e.transcriptEvents??[])??null}async function readChatHistoryPageKernel(e,t){const{entry:n,sessionId:r,storePath:i,sessionAgentId:a,canonicalKey:o,max:s,maxHistoryBytes:c,effectiveMaxChars:l,offset:u,messageId:d,pageCursor:f}=e;if(!r||!i){if(d)return{messages:[]};return{...(u??0)===0?{activeLeafEntryId:null}:{},messages:[],...u!==void 0?{responseOffset:u}:{},pagination:{offset:u??0,totalMessages:0,rawPageMessages:0}}}const p={agentId:a,sessionEntry:n,sessionId:r,sessionKey:o,storePath:i};const attachReplyMessages=n=>attachChatHistoryReplyMessages(augmentChatHistoryWithCanvasBlocks(n),e,t);const m=t.readMessageSequence??readChatHistoryMessageSeq;if(d){const i=f?.direction;const a=await readChatHistoryAnchorPage(t.readers,p,{messageId:d,maxMessages:s+(i===`older`?2:i===`newer`?1:0),direction:i,allowResetArchiveFallback:true,readOnly:t.readOnly});const o=a.displaySource?createTranscriptDisplaySource([a.displaySource]):void 0;if(f&&(!a.found||a.windowReset||o!==f.source))return{messages:[],windowReset:true};if(!a.found)return{messages:[]};let u=a.messages;let h=a.hasOverreadContext?u[0]:void 0;if(i){const e=u.findIndex(e=>readChatHistoryMessageId(e)===d);if(e<0)return{messages:[],windowReset:true};const t=m(u[e]);let n=e;let r=e+1;if(t!==void 0){while(n>0&&m(u[n-1])===t)n-=1;while(r<u.length&&m(u[r])===t)r+=1}if(i===`newer`){h=u[r-1];u=u.slice(r-1)}else{u=u.slice(0,n);const e=m(u[0]);if(t!==void 0&&e!==void 0&&t-e>s){h=u[0];u=[h,...u.filter(t=>m(t)!==e)]}}}const g=dropChatHistoryOverreadContextMessage(dropPreSessionStartAnnouncePairs(u,typeof n?.sessionStartedAt===`number`?n.sessionStartedAt:void 0),h);const project=n=>projectChatDisplayMessagesWithState(n,{includePluginSteering:e.includePluginSteering,subagentCoordination:t.readers.subagentCoordination,includeCommentaryFallbacks:true,maxChars:l,toolResultMaxChars:e.toolResultMaxChars,resolveCronJobName:t.resolveCronJobName,...t.deferProfileDisplay?{}:{resolveCurrentUserProfileDisplay:t.resolveCurrentUserProfileDisplay},turnBoundaryPending:projectedHistoryTurnBoundary(h)});const _=project(g);let v=_.messages;const y=m(g.at(-1));if((i===`older`||a.offset>0)&&y!==void 0&&_.assistantErrorPending){const e=await readChatHistoryRecoveryContext({messages:g,createRecovery:e=>{const n=createChatHistoryRecoveryProjection({maxChars:l,subagentCoordination:t.readers.subagentCoordination});n.append(e);return n},readScope:p,readers:t.readers,displaySource:a.displaySource,maxBytes:c,readOnly:t.readOnly,sessionStartedAt:n?.sessionStartedAt});if(e.length>0)v=project([...g,...e]).messages.filter(e=>(m(e)??Infinity)<=y)}const b=dropChatHistoryOverreadContextMessage(u,h);const x=m(b[0]);return{messages:await attachReplyMessages(v),..._.activity.length?{activity:_.activity}:{},...o?{anchor:{sessionId:r,source:o,direction:i,hasOlder:i===`newer`||x!==void 0&&x>1,hasNewer:i===`older`||a.offset>0,oldestMessageId:readChatHistoryMessageId(b[0]),newestMessageId:readChatHistoryMessageId(b.at(-1))}}:{}}}const h=await readIncrementalChatHistoryTail({entry:n,readScope:p,effectiveMaxChars:l,max:s,toolResultMaxChars:e.toolResultMaxChars,includePluginSteering:e.includePluginSteering,maxBytes:c,isPageFull:n=>isChatHistoryResponsePageByteLimited(n,e,t.readMessageSequence),offset:u,...t});const{readPage:g}=h;const _=h.windowReset?0:u;const v=_!==void 0;const y=!v||_===0;const b=y?resolveChatHistoryActiveLeafEntryId(g):null;const x=g.displaySource?createTranscriptDisplaySource([g.displaySource]):void 0;return{...h.windowReset?{windowReset:true}:{},...y?{activeLeafEntryId:b}:{},...y&&g.transcriptSource===`active`&&g.deltaCursor&&!h.projection.assistantErrorPending?{deltaCursor:g.deltaCursor}:{},messages:await attachReplyMessages(h.projected),...h.projection.activity.length?{activity:h.projection.activity}:{},...v?{responseOffset:_}:{},...x?{anchor:{sessionId:r,source:x,hasOlder:h.hasOlder,hasNewer:(_??0)>0,oldestMessageId:h.oldestMessageId,newestMessageId:h.newestMessageId}}:{},pagination:{offset:_??0,totalMessages:g.totalMessages,rawPageMessages:h.rawPageMessages}}} //!src/gateway/server-methods/chat-history-pages.ts function prepareChatHistoryParams(e){return getCliSessionBinding(e.entry,`claude-cli`)?.sessionId?{...e,cliHistoryProjectsDir:resolveClaudeCliProjectsDir()}:e}function chatHistoryScope(e){return{agentId:e.sessionAgentId,sessionId:e.sessionId??``,sessionKey:e.canonicalKey,storePath:e.storePath,sessionEntry:e.entry}}async function readChatHistoryMessageById(e){const t=chatHistoryScope(e);const n=captureSessionActorTranscriptRead(t);const r=n?structuredClone(e):e;const i=getCliSessionBinding(r.entry,`claude-cli`);if(n&&i?.sessionId){const{readProcessHeldCliHistoryMessage:e}=await import(`./cli-session-history.process-held-D0fcBRU2.mjs`);const t=await e(prepareChatHistoryParams(r),n);n.assertCurrent();return t}if(n||!i?.sessionId||!e.storePath||e.entry?.incognito||isIncognitoSessionKey(e.canonicalKey)){const e=await(n?createSessionActorTranscriptReader(n):session_transcript_readers_exports).readSessionMessageByIdAsync(t,r.messageId,{allowResetArchiveFallback:true,historyVisibility:{sessionStartedAt:r.entry?.sessionStartedAt}});n?.assertCurrent();return e}const a=prepareChatHistoryParams(e);const{readSessionHistoryPageInWorker:o}=await import(`./session-history-worker-runtime-DwT_7nJS.mjs`);return o({kind:`rpc-message`,params:{...a,storePath:e.storePath}})}async function readChatHistoryPageUnprojected(e,t){t?.throwIfAborted();const n=chatHistoryScope(e);const r=captureSessionActorTranscriptRead(n,t);const i=getCliSessionBinding(e.entry,`claude-cli`);const a=prepareChatHistoryParams(r?structuredClone(e):e);if(r){const e=Boolean(i?.sessionId&&!a.ignoreCliSessionImports);let n;if(e){const{readProcessHeldCliHistory:e}=await import(`./cli-session-history.process-held-D0fcBRU2.mjs`);n=await e(a,t,r)}else n=await readChatHistoryPageKernel(a,{readers:createSessionActorTranscriptReader(r),readOnly:true,resolveCurrentUserProfileDisplay,resolveCronJobName:()=>void 0});const o={...n,messages:await refreshForwardedLabels(n.messages)};t?.throwIfAborted();r.assertCurrent();return e?o:encodeChatHistoryResponsePage(o,a)}if(!a.sessionId||!a.storePath||a.entry?.incognito||isIncognitoSessionKey(a.canonicalKey)){const e=await readChatHistoryPageKernel(a,{readers:session_transcript_readers_exports,resolveCurrentUserProfileDisplay,resolveCronJobName:()=>void 0});return{...e,messages:await refreshForwardedLabels(e.messages)}}const{readSessionHistoryPageInWorker:o}=await import(`./session-history-worker-runtime-DwT_7nJS.mjs`);return o({kind:`rpc`,params:{...a,compactionMetrics:readLegacyCompactionMetrics(a.entry),sessionId:a.sessionId,storePath:a.storePath}},t)}async function refreshForwardedLabels(e){return projectChatHistoryWithReplies(e.filter(e=>asOptionalRecord(e)!==void 0),async e=>projectForwardedMessages(e,await prepareForwardedMessageCronJobNameResolver(e)))}async function readChatHistoryPage(e,t,n){const r=await readChatHistoryPageUnprojected(n?{...e,deferChannelUserDisplay:true}:e,t);if(!n||r.encodedResponse)return r;const i=sanitizeChatHistoryMessages(await n.project(r.messages),e.effectiveMaxChars,{toolResultMaxChars:e.toolResultMaxChars});t?.throwIfAborted();return encodeChatHistoryResponsePage({...r,messages:i},prepareChatHistoryParams(e))}export{decodeChatHistoryPageCursor as a,prepareChatHistoryResponsePage as i,readChatHistoryPage as n,resolveChatHistorySelectorError as o,enrichChatHistoryCompactionMarkers as r,readChatHistoryMessageById as t};