UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

5 lines • 11.7 kB
import{a as asOptionalRecord}from"./record-coerce-BTbqdJ3-.mjs";import{r as truncateUtf16Safe}from"./utf16-slice-DA3Mllbx.mjs";import{r as isIncognitoSessionKey}from"./session-key-DYtwLLn1.mjs";import{N as parseAgentSessionKey}from"./session-key-BPgKfU2m.mjs";import{i as listAgentIds}from"./agent-roster-4XrgUgPK.mjs";import{z as resolvePersistedSessionStoreOwnerForKey}from"./agent-scope-config-CG9CFpGX.mjs";import{i as assertExistingDatabaseIdentity}from"./sqlite-worker-identity-CikEUuqF.mjs";import{t as ASSISTANT_DISPLAY_CONTENT_FIELD}from"./assistant-display-content-DZzkofMk.mjs";import{d as extractCanvasFromRecord,f as extractCanvasShortcodes}from"./chat-display-projection.canvas-BobptIQs.mjs";import{n as sanitizeChatHistoryContentBlock}from"./chat-display-projection.sanitize-DPZ4F1ws.mjs";import{n as isToolCallContentType,o as resolveToolBlockArgs}from"./tool-content-FhKUiJzR.mjs";import{r as MAX_IMAGE_BYTES}from"./constants-cCp4CBUF.mjs";import{r as unwrapToolCallForDisplay}from"./tool-display-call-CqUrC2DS.mjs";import{i as jsonUtf8Bytes}from"./json-utf8-bytes-BzjXgHQ3.mjs";import{c as resolveSessionPublicShare}from"./session-accessor.sqlite-entry-store-Cxqr6m6F.mjs";import{t as findTranscriptEvent}from"./session-transcript-match-ntWbkUzu.mjs";import{c as withReadySessionRows}from"./session-row-prepared-read-B7-BN1nJ.mjs";import{c as publicSessionMessageText,i as collectPublicSessionAttachments,l as readPublicWidgetReceipt,s as publicSessionMessageEntry}from"./control-ui-public-session-attachments-DyRHqlMl.mjs";import{d as readSessionMessagesPageWithStatsAsync,o as readSessionMessageByIdAsync}from"./session-transcript-readers-D9Cuet3N.mjs";import{n as parseCanvasDocumentHttpPath}from"./documents-CEJ-RxdU.mjs"; //!src/gateway/control-ui-public-session-project.ts function toolSummary(e){const t=asOptionalRecord(e);const n=t?[`command`,`cmd`,`path`,`file_path`,`query`,`q`,`url`].map(e=>t[e]).find(e=>typeof e===`string`):typeof e===`string`?e:void 0;return typeof n===`string`?truncateUtf16Safe(n.replace(/\s+/gu,` `).trim(),160):``}function publicSessionLinkHref(e){const t=e?URL.parse(e):null;return t&&(t.protocol===`https:`||t.protocol===`http:`)&&!t.username&&!t.password?t.href:void 0}function hostedWidget(e){if(!e?.url)return;const t=parseCanvasDocumentHttpPath(e.url);if(!t||e.mcpApp||e.viewId&&e.viewId!==t.documentId)return;return{kind:`widget`,docId:t.documentId,title:e.title,height:e.preferredHeight}}function projectPublicSessionItems(e){const t=[];const n=/* @__PURE__ */ new Map;const r=e.map(e=>{const t=publicSessionMessageEntry(e);const r=hostedWidget(extractCanvasFromRecord(readPublicWidgetReceipt(e)));if(r?.title)n.set(r.docId,r.title);const i=t?publicSessionMessageText(t):``;const a=extractCanvasShortcodes(t?.role===`assistant`?i:void 0);const o=a.previews.flatMap(e=>{const t=hostedWidget(e);const n=t?void 0:publicSessionLinkHref(e.url);return t?[t]:n?[{kind:`link`,href:n,title:e.title}]:[]});return{message:e,entry:t,receipt:r,text:t?.role===`assistant`?a.text:i,shortcodeEmbeds:o,deferReceipt:false}});const i=/* @__PURE__ */ new Set;for(const e of r.toReversed()){if(e.entry?.role===`user`)i.clear();e.deferReceipt=Boolean(e.receipt&&i.has(e.receipt.docId));for(const t of e.shortcodeEmbeds)if(t.kind===`widget`)i.add(t.docId)}const a=/* @__PURE__ */ new Set;for(const[e,{message:i,entry:o,receipt:s,text:c,shortcodeEmbeds:l,deferReceipt:u}]of r.entries()){const r=[];for(const e of[...l,...s&&!u?[s]:[]])if(e.kind===`link`)r.push(e);else if(!a.has(e.docId)){a.add(e.docId);r.push({...e,title:e.title??n.get(e.docId)})}const d=o?collectPublicSessionAttachments(o):[];if(c||d.length>0||r.length>0)t.push({kind:`message`,role:o?.role===`user`?`user`:`assistant`,text:c,message:i,sourceIndex:e,embeds:r});if(o?.role!==`assistant`||!Array.isArray(o.content))continue;for(const n of o.content){const r=asOptionalRecord(n);if(!r||!isToolCallContentType(r.type))continue;const i=unwrapToolCallForDisplay({name:typeof r.name===`string`?r.name:`tool`,args:resolveToolBlockArgs(r)});const a=truncateUtf16Safe(i.name,80);const o=toolSummary(i.args);const s=t.at(-1);if(s?.kind===`tools`)s.calls.push({name:a,summary:o});else t.push({kind:`tools`,calls:[{name:a,summary:o}],sourceIndex:e})}}return t} //!src/gateway/control-ui-public-session-read.ts const PUBLIC_SESSION_PAGE_ITEMS=50;const PUBLIC_SESSION_SCAN_ROWS=2e3;const PUBLIC_SESSION_READ_BYTES=1048576;const PUBLIC_SESSION_MEDIA_ENTRY_BYTES=Math.ceil(MAX_IMAGE_BYTES*4/3)+PUBLIC_SESSION_READ_BYTES;const PUBLIC_SESSION_MAX_MESSAGES=100;async function readPublicSessionOpening(e){let t=PUBLIC_SESSION_READ_BYTES;let n=await readSessionMessagesPageWithStatsAsync(e,{offset:0,beforeSeq:2,maxMessages:1,maxBytes:t,allowResetArchiveFallback:false});let r=n.omittedOversized;for(let i=0;i<PUBLIC_SESSION_MAX_MESSAGES;i++){if(i>0){n=await readSessionMessagesPageWithStatsAsync(e,{offset:0,beforeSeq:i+2,maxMessages:1,maxBytes:t,allowResetArchiveFallback:false});r||=n.omittedOversized}const a=n.messages[0];const o=publicSessionMessageEntry(a);if(o?.role===`user`&&publicSessionMessageText(o))return{...n,messages:[a],olderOffset:void 0,omittedOversized:r};if(a!==void 0)t-=Buffer.byteLength(JSON.stringify(a));if(i+1>=n.totalMessages||t<1024)break}return{...n,messages:[],olderOffset:void 0,omittedOversized:r}}function compactInlineImagePayloads(e){const t=asOptionalRecord(e);if(!t)return;const n={...t};let r=false;for(const e of[`content`,ASSISTANT_DISPLAY_CONTENT_FIELD]){const i=t[e];if(!Array.isArray(i))continue;n[e]=i.map(e=>{const t=asOptionalRecord(e);const n=asOptionalRecord(t?.source);const i=asOptionalRecord(t?.image_url);if(!t||![`image`,`image_url`,`input_image`].includes(String(t.type))||![t.data,t.blob,n?.data,n?.blob].some(e=>typeof e===`string`&&e.length>0)&&![t.url,t.image_url,i?.url,n?.url].some(e=>typeof e===`string`&&e.startsWith(`data:image/`)))return e;r=true;const a=asOptionalRecord(sanitizeChatHistoryContentBlock(Object.assign({},t,{type:`image`}),{maxChars:Number.MAX_SAFE_INTEGER}).block);return Object.assign(a??{},{type:t.type})})}return r&&jsonUtf8Bytes([n])<=PUBLIC_SESSION_READ_BYTES?n:void 0}async function readVisiblePage(e,t){let n=[];let r=2;let i=t;let a=0;let o=false;let s;let c;while(n.length<PUBLIC_SESSION_SCAN_ROWS&&r<=1047552){const l=await readSessionMessagesPageWithStatsAsync(e,{offset:i,maxMessages:Math.min(100,PUBLIC_SESSION_SCAN_ROWS-n.length),maxBytes:PUBLIC_SESSION_READ_BYTES-r,allowResetArchiveFallback:false,...c?{beforeSeq:a+1,expectedReadWindow:c}:{captureReadWindow:true}});if(l.windowReset)return null;if(!c){a=l.totalMessages;c=l.readWindow}if(l.omittedOversized&&n.length>0){s=i;break}if(l.omittedOversized){const t=await readSessionMessagesPageWithStatsAsync(e,{offset:i,beforeSeq:a+1,expectedReadWindow:c,maxMessages:1,maxBytes:PUBLIC_SESSION_MEDIA_ENTRY_BYTES,allowResetArchiveFallback:false});if(t.windowReset)return null;const r=t.messages.length===1?compactInlineImagePayloads(t.messages[0]):void 0;if(r){n=[r];s=l.olderOffset;break}}n=[...l.messages,...n];r+=jsonUtf8Bytes(l.messages);s=l.olderOffset;o||=l.omittedOversized===true;const u=projectPublicSessionItems(n);if(u.length>PUBLIC_SESSION_PAGE_ITEMS){const e=u[u.length-PUBLIC_SESSION_PAGE_ITEMS].sourceIndex;n=n.slice(e);s=t+n.length;break}if(s===void 0||l.messages.length<100)break;i=s}o||=s!==void 0&&projectPublicSessionItems(n).length<PUBLIC_SESSION_PAGE_ITEMS;return{messages:n,totalMessages:a,truncated:o,olderOffset:s}}function readAuthorizedTarget(e,t,n){const r=parseAgentSessionKey(t.sessionKey);const i=resolvePersistedSessionStoreOwnerForKey(e,t.sessionKey);if(t.sessionKey!==`global`&&(!r||r.agentId!==t.agentId||t.sessionKey!==`agent:${r.agentId}:${r.rest}`)||i.kind===`retired`||i.kind===`configured`&&i.agentId!==t.agentId||!listAgentIds(e).includes(t.agentId)||isIncognitoSessionKey(t.sessionKey)||n.sharingRevision===void 0||n.state.cfg!==e)return;const a={key:t.sessionKey,agentId:t.agentId};const o=n.sharingTargetState(a);if(o.status!==`ready`)return;const s=o.target;const c=resolveSessionPublicShare(s.entry);if(s.canonicalKey!==t.sessionKey||s.agentId!==t.agentId||c?.id!==t.shareId||c.sessionId!==t.sessionId)return;const l=n.readSource({...a,storePath:s.storePath});if(!l||typeof l.databaseIdentity!==`string`)return;assertExistingDatabaseIdentity(l.path,`file:${l.databaseIdentity}`,l.databaseBirthtime);return{target:s,source:l}}function isPublicSessionShareActive(e,t,n){return Boolean(readAuthorizedTarget(e,t,n))}async function readPublicSessionShare(e,t,n){const{projection:r}=n;if(isIncognitoSessionKey(t.sessionKey)||!listAgentIds(e).includes(t.agentId))return null;const queries=()=>[{key:t.sessionKey,agentId:t.agentId}];const i=await withReadySessionRows(r,queries,()=>readAuthorizedTarget(e,t,r));if(!i)return null;const a={agentId:i.source.agentId,sessionKey:t.sessionKey,sessionId:t.sessionId,storePath:i.source.path,sessionEntry:i.target.entry};const o=n.card?await readPublicSessionOpening(a):await readVisiblePage(a,n.offset??0);if(!o)return null;const s=n.card?(await import(`./control-ui-public-session-card-facts-BTM3KZt8.mjs`)).resolvePublicSessionCardFacts:void 0;return withReadySessionRows(r,queries,a=>{const c=readAuthorizedTarget(e,t,r);if(!c||c.source.path!==i.source.path||c.source.databaseIdentity!==i.source.databaseIdentity||c.source.databaseBirthtime!==i.source.databaseBirthtime)return null;const l=(c.target.entry.label||c.target.entry.displayName||`Shared session`).trim();const u=n.card?a.describe(queries()[0]):void 0;return{title:l||`Shared session`,messages:o.messages,totalMessages:o.totalMessages,truncated:`truncated`in o?o.truncated:o.omittedOversized===true,...u&&s?{cardFacts:s({cfg:e,record:u,rowContext:a.state.rowContext,pullRequests:n.pullRequests})}:{},...o.olderOffset!==void 0?{olderOffset:o.olderOffset}:{}}})}async function readPublicSessionMessage(e,t,n){const{projection:r}=n;if(isIncognitoSessionKey(t.sessionKey)||!listAgentIds(e).includes(t.agentId))return null;const queries=()=>[{key:t.sessionKey,agentId:t.agentId}];const i=await withReadySessionRows(r,queries,()=>readAuthorizedTarget(e,t,r));if(!i)return null;const a=await readSessionMessageByIdAsync({agentId:i.source.agentId,sessionKey:t.sessionKey,sessionId:t.sessionId,storePath:i.source.path,sessionEntry:i.target.entry},n.entryId,{currentOnly:true,maxBytes:PUBLIC_SESSION_MEDIA_ENTRY_BYTES,allowResetArchiveFallback:false});return withReadySessionRows(r,queries,()=>{const n=readAuthorizedTarget(e,t,r);return n&&n.source.path===i.source.path&&n.source.databaseIdentity===i.source.databaseIdentity&&n.source.databaseBirthtime===i.source.databaseBirthtime&&a.found&&!a.oversized?asOptionalRecord(a.message)??null:null})}async function readPublicSessionWidget(e,t,n){const{projection:r}=n;if(isIncognitoSessionKey(t.sessionKey)||!listAgentIds(e).includes(t.agentId))return false;const queries=()=>[{key:t.sessionKey,agentId:t.agentId}];const i=await withReadySessionRows(r,queries,()=>readAuthorizedTarget(e,t,r));if(!i)return false;const a=await findTranscriptEvent({agentId:i.source.agentId,sessionKey:t.sessionKey,sessionId:t.sessionId,storePath:i.source.path,sessionEntry:i.target.entry},{kind:`canvas-widget`,docId:n.docId},void 0,`public-session-widget`);return withReadySessionRows(r,queries,()=>{const n=readAuthorizedTarget(e,t,r);return Boolean(a&&readPublicWidgetReceipt(asOptionalRecord(a.event)?.message)&&n&&n.source.path===i.source.path&&n.source.databaseIdentity===i.source.databaseIdentity&&n.source.databaseBirthtime===i.source.databaseBirthtime)})}export{projectPublicSessionItems as a,readPublicSessionWidget as i,readPublicSessionMessage as n,publicSessionLinkHref as o,readPublicSessionShare as r,isPublicSessionShareActive as t};