UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

8 lines • 15 kB
import{a as e}from"./transcript-record-coerce-CPLgmAk9.mjs";import{w as t}from"./transcript-redact-BJEzMNLa.mjs";import{d as n,u as r}from"./transcript-sqlite-post-commit-B_pko32i.mjs";import{u as i}from"./transcript-kysely-sync-cache-state-DHCXK7mb.mjs";import{c as a}from"./transcript-sqlite-schema-facts-C1_zV4Yg.mjs";import{i as o,m as s,o as c,p as l,r as u}from"./transcript-kysely-sync-CAP5xe3V.mjs";import{a as d,g as f,o as p,p as m,s as h,t as g,v as _}from"./transcript-json-values-C_3KtpDU.mjs";import{f as v}from"./transcript-tool-result-pairing-DrpmDHYa.mjs";import{a as y,d as b,i as x,o as S,u as C}from"./transcript-transcript-payload-F5t-l1WZ.mjs";import{r as w}from"./transcript-session-transcript-read-bytes-DJiUSe6g.mjs";import{c as T,l as E,n as D,o as O,r as k,s as A,t as j,u as M}from"./transcript-session-accessor.sqlite-projection-read-B2CcfDOt.mjs";import{toUSVString as N}from"node:util";function engineStringPosition(e,t,n){return s().fn(r(e)?`strpos`:`instr`,[t,n])}const P={type:!0,id:!0,parentId:!0,targetId:!0,appendParentId:!0,appendMode:!0,firstKeptEntryId:!0,customType:!0,display:!0};function parseNavigation(t){let n=Object.keys(P),r=_(t,n);if(!r.valid||r.maximumDepth>1e3||!t.trimStart().startsWith(`{`)){let r=JSON.parse(t);return e(r)?Object.fromEntries(n.map(e=>[e,r[e]])):void 0}let i={};for(let e of n){let t=r.last.get(e);i[e]=t?.kind===`string`?m(t):t?JSON.parse(t.text):void 0}return i}function navigationCandidatesSql(e,t,n,r,i){let a=l.ref(`member.value`),o=i.length>32?l`true`:l`(${l.join(i.map(t=>l`${engineStringPosition(e,a,l.val(t))} > 0`),l` OR `)})`;return l`CASE WHEN ${t} IS NOT NULL THEN false WHEN ${r} = 1 AND ${d(e,n)} THEN EXISTS ( SELECT 1 FROM ${h(e,n)} AS member WHERE member.key = ${`id`} AND ${o} ) ELSE true END`}function canFilterEventIds(e){return e!==void 0&&e.every(e=>N(e)===e&&!e.includes(`\0`))}function unindexedNavigationQuery(e,t){let n=y(e.database.db,`event`);return j(e.database).selectFrom(`transcript_events as event`).leftJoin(`transcript_event_identities as identity`,e=>e.onRef(`identity.session_id`,`=`,`event.session_id`).onRef(`identity.seq`,`=`,`event.seq`)).select([`event.seq as event_seq`,l`CASE WHEN event.navigation_valid = 1 THEN ${p(e.database.db,n,P)} ELSE ${n} END`.as(`event_json`),l`${w(`event`)} + 1`.as(`serialized_bytes`)]).where(`event.session_id`,`=`,e.resolved.sessionId).where(`identity.seq`,`is`,null).$if(canFilterEventIds(t),r=>r.where(r=>navigationCandidatesSql(e.database.db,r.ref(`identity.seq`),n,r.ref(`event.navigation_valid`),t)))}function*navigationRows(e){for(let{event_json:t,...n}of e){let e=parseNavigation(t);e&&(yield{...n,event:e})}}function*iterateUnindexedTranscriptNavigation(e,t={}){if(!e.hasUnindexedPrefix||t.eventIds?.length===0)return;let n=unindexedNavigationQuery(e,t.eventIds).$if(t.controlsOnly===!0,t=>t.where(t=>t.or([t(C(e.database.db,`navigation_valid`,`event`),`=`,0),t(C(e.database.db,`navigation_last_type`,`event`),`in`,[`reset`,`compaction`,`custom_message`])]))).where(`event.seq`,`<=`,t.maxRawSeq??e.state.indexedSeq).$if(t.afterRawSeq!==void 0,e=>e.where(`event.seq`,`>`,t.afterRawSeq)).orderBy(`event.seq`,`asc`);yield*navigationRows(c(e.database.db,n))}function*iterateUnindexedActiveTranscriptNavigation(e,t={}){if(!e.hasUnindexedPrefix||t.eventIds?.length===0)return;let n=unindexedNavigationQuery(e,t.eventIds).innerJoin(`session_transcript_active_events as active`,e=>e.onRef(`event.session_id`,`=`,`active.session_id`).onRef(`event.seq`,`=`,`active.event_seq`)).select([`active.active_position`,`active.message_position`]).where(`active.event_seq`,`<=`,t.maxRawSeq??e.state.indexedSeq).$if(t.beforeActivePosition!==void 0,e=>e.where(`active.active_position`,`<`,t.beforeActivePosition)).orderBy(`active.active_position`,t.first?`asc`:`desc`);yield*navigationRows(c(e.database.db,n))}function findUnindexedActiveTranscriptEntry(e,t){for(let n of iterateUnindexedActiveTranscriptNavigation(e,{eventIds:[t]}))if(typeof n.event.id==`string`&&n.event.id.trim()===t)return n}function isWindowBoundary(e,t){return e===`reset`||t===`context`&&e===`compaction`}const F=/* @__PURE__ */ new Map,I=/* @__PURE__ */ new WeakSet;function cacheResetMessageWindow(e,r){let{database:a}=r;I.has(a)||(i(n(a),()=>{for(let[e,t]of F)t.database===a&&F.delete(e)}),I.add(a)),F.delete(e),F.set(e,r),t(F,64)}function readUnindexedHistoryControls(e,t){if(!e.hasUnindexedPrefix)return[];let n=Math.min(e.state.indexedSeq,(t??1/0)-1),r=e.unindexedHistoryControls;if(r&&r.coveredThrough>=n)return r.coveredThrough===n?r.rows:r.rows.filter(e=>e.event_seq<=n);let i=`${e.database.path}\0${e.resolved.sessionId}\0unindexed-controls`,o=!a(e.database.db),s=o?F.get(i):void 0,c=s?.database===e.database.db&&`controls`in s&&s.generation===e.generation&&s.indexedSeq<=e.state.indexedSeq?s:void 0,d=[...c?.controls??[]];if(!c||c.indexedSeq<n){for(let t of iterateUnindexedTranscriptNavigation(e,{afterRawSeq:c?.indexedSeq,maxRawSeq:n,controlsOnly:!0})){let e=t.event.type;(e===`reset`||e===`compaction`||e===`custom_message`)&&d.push(t)}o&&(d.length<=4096?cacheResetMessageWindow(i,{database:e.database.db,generation:e.generation,indexedSeq:n,controls:d}):F.delete(i))}let f=new Map(d.filter(e=>e.event_seq<=n).map(e=>[e.event_seq,e])),p=f.size===0?[]:u(e.database.db,j(e.database).selectFrom(l`(SELECT CAST(value AS BIGINT) AS value FROM ${g(e.database.db,l.val(JSON.stringify([...f.keys()])))})`.as(`requested`)).crossJoin(`session_transcript_active_events as active`).leftJoin(`transcript_event_identities as identity`,e=>e.onRef(`identity.session_id`,`=`,`active.session_id`).onRef(`identity.seq`,`=`,`active.event_seq`)).leftJoin(`session_transcript_active_events as following`,e=>e.onRef(`following.session_id`,`=`,`active.session_id`).on(e=>e(`following.active_position`,`=`,e(`active.active_position`,`+`,1)))).select([`active.event_seq`,`active.active_position`,`active.message_position`,`following.message_position as following_message_position`]).where(`active.session_id`,`=`,e.resolved.sessionId).whereRef(`active.event_seq`,`=`,`requested.value`).where(`identity.seq`,`is`,null).orderBy(`active.active_position`,`asc`)).rows.map(e=>Object.assign({},f.get(e.event_seq),e));return e.unindexedHistoryControls={coveredThrough:n,rows:p},p}function readLatestActiveBoundaryMetadataByType(e,t,n){let r=e.latestIndexedReset,i=t===`reset`&&r!==void 0&&(!r||n===void 0||r.seq<n)?r??void 0:o(e.database.db,A(e.database).select([`active.active_position`,`identity.event_id`,`identity.event_type`,`identity.seq`]).where(`active.session_id`,`=`,e.resolved.sessionId).where(`identity.event_type`,`=`,t).$if(n!==void 0,e=>e.where(`identity.seq`,`<`,n)).orderBy(`identity.seq`,`desc`).limit(1)),a;for(let r of readUnindexedHistoryControls(e,n))r.event.type===t&&(n===void 0||r.event_seq<n)&&(!a||r.event_seq>a.event_seq)&&(a=r);return a&&(!i||a.event_seq>i.seq)?{active_position:a.active_position,...typeof a.event.id==`string`?{event_id:a.event.id}:{},event_type:t,seq:a.event_seq}:i}function readLatestActiveResetBoundary(e,t){return readLatestActiveBoundaryMetadataByType(e,`reset`,t)}function readLatestActiveBoundaryMetadata(e,t,n){let r=readLatestActiveBoundaryMetadataByType(e,`reset`,n);if(t!==`context`)return r;let i=readLatestActiveBoundaryMetadataByType(e,`compaction`,n);return r&&(!i||r.seq>i.seq)?r:i}function readBoundaryWindowFacts(e,t,n){let r=o(e.database.db,j(e.database).selectFrom(`transcript_events`).select([S(e.database.db).as(`event_json`),l`${w()} + 1`.as(`serialized_bytes`)]).select(n=>n.selectFrom(`session_transcript_active_events`).select(`message_position`).where(`session_id`,`=`,e.resolved.sessionId).where(`active_position`,`>`,t.active_position).where(`message_position`,`is not`,null).orderBy(`active_position`,`asc`).limit(1).as(`post_boundary_message_position`)).where(`session_id`,`=`,e.resolved.sessionId).where(`seq`,`=`,t.seq).limit(1));if(!r)throw Error(`Active transcript boundary is missing`);let i=JSON.parse(r.event_json);if(!isWindowBoundary(i.type,n))throw Error(`Active transcript boundary has invalid payload`);return{firstKeptEntryId:i.firstKeptEntryId,sizeBytes:r.serialized_bytes,postBoundaryMessagePosition:r.post_boundary_message_position??e.state.activeMessageCount}}function findLatestResetMessageWindow(e,t,n){let r=readLatestActiveBoundaryMetadata(e,t,n);if(!r)return null;let i=readBoundaryWindowFacts(e,r,t),a,s=[],u=r.event_type===`compaction`,d=+!!u,p=u?i.sizeBytes:0;if(typeof i.firstKeptEntryId==`string`){let n=o(e.database.db,A(e.database).select(`active.active_position`).where(`identity.session_id`,`=`,e.resolved.sessionId).where(`identity.event_id`,`=`,i.firstKeptEntryId).where(`active.active_position`,`<`,r.active_position)),m;for(let t of iterateUnindexedActiveTranscriptNavigation(e,{beforeActivePosition:n?.active_position??r.active_position,eventIds:[i.firstKeptEntryId],first:!0}))if(t.event.id===i.firstKeptEntryId){m=t;break}let h=m??n;if(h&&h.active_position<r.active_position){a=h.active_position;let n=c(e.database.db,O(e.database).select([`active.message_position`,(u?S(e.database.db,`event`):l`CASE WHEN ${f(e.database.db,y(e.database.db,`event`))} THEN ${x(e.database.db,`event`)} ELSE ${y(e.database.db,`event`)} END`).as(`event_json`),l`${w(`event`)} + 1`.as(`serialized_bytes`)]).where(`active.session_id`,`=`,e.resolved.sessionId).where(`active.active_position`,`>=`,h.active_position).where(`active.active_position`,`<`,r.active_position).where(`active.message_position`,`is not`,null).$if(t===`context`&&r.event_type!==`reset`,e=>e.where(`active.context_eligible`,`=`,1)).orderBy(`active.active_position`,`asc`)),i=[];for(let e of n)try{i.push({message_position:e.message_position,serialized_bytes:e.serialized_bytes,event:JSON.parse(e.event_json)})}catch{continue}let o=i;if(r.event_type===`reset`){let e=new Set(v(i.map(e=>e.event)));o=i.filter(t=>e.has(t.event))}d+=o.length,p+=o.reduce((e,t)=>e+t.serialized_bytes,0);for(let e of o){if(e.message_position===null||e.event.type!==`message`)continue;let n=e.event.message.role;(t!==`history`||n===`user`||n===`assistant`)&&s.push(e.message_position)}}}return{boundarySeq:r.seq,boundaryType:u?`compaction`:`reset`,firstKeptActivePosition:a,contextPrefixEventCount:d,keptMessagePositions:s,contextPrefixSizeBytes:p,postBoundaryMessagePosition:i.postBoundaryMessagePosition,boundaryActivePosition:r.active_position}}function resolveTranscriptBoundaryWindow(e,t=`history`,n){if(n!==void 0||a(e.database.db))return findLatestResetMessageWindow(e,t,n);let r=`${e.database.path}\0${e.resolved.sessionId}\0${t}`,i=F.get(r),o=e.generation;if(i?.database===e.database.db&&`window`in i){if(i.generation===o&&i.indexedSeq===e.state.indexedSeq)return i.window;if(i.generation===o&&i.window&&readLatestActiveBoundaryMetadata(e,t)?.seq===i.window.boundarySeq)return cacheResetMessageWindow(r,{...i,indexedSeq:e.state.indexedSeq}),i.window}let s=findLatestResetMessageWindow(e,t);return cacheResetMessageWindow(r,{database:e.database.db,generation:o,indexedSeq:e.state.indexedSeq,window:s}),s}function resolveVisibleMessagePositions(e){let t=resolveTranscriptBoundaryWindow(e);return t?{boundaryActivePosition:t.boundaryActivePosition,kept:t.keptMessagePositions,postStart:t.postBoundaryMessagePosition,total:t.keptMessagePositions.length+Math.max(0,e.state.activeMessageCount-t.postBoundaryMessagePosition)}:{kept:[],postStart:0,total:e.state.activeMessageCount}}function selectVisibleMessageRanges(e,t,n){let r=[];if(n<=t)return r;let i=resolveVisibleMessagePositions(e),a=Math.min(Math.max(0,t),i.total),o=Math.min(Math.max(a,n),i.total),s=Math.min(o,i.kept.length);for(let e=a;e<s;e+=500){let t=i.kept.slice(e,Math.min(e+500,s)),n=new Map(t.map((t,n)=>[t,e+n]));r.push({positions:t,logicalPosition:e=>n.get(e)})}let c=Math.max(a,i.kept.length);if(o>c){let e=i.postStart+c-i.kept.length;r.push({start:e,endExclusive:e+o-c,logicalPosition:t=>c+t-e})}return r}function readVisibleMessageRange(e,t,n){return Array.from(iterateVisibleMessageRange(e,t,n))}function*iterateVisibleMessageRange(e,t,n){for(let r of selectVisibleMessageRanges(e,t,n)){let t=`positions`in r?c(e.database.db,E(M(e.database,e.resolved.sessionId,r))):D(e.database).messages({sessionId:e.resolved.sessionId,start:r.start,endExclusive:r.endExclusive});for(let e of t)yield k(e)}}function hasUnindexedVisibleMessages(e,t,n){return selectVisibleMessageRanges(e,t,n).some(t=>o(e.database.db,M(e.database,e.resolved.sessionId,t).leftJoin(`transcript_event_identities as identity`,e=>e.onRef(`identity.session_id`,`=`,`active.session_id`).onRef(`identity.seq`,`=`,`active.event_seq`)).select(`active.event_seq`).where(`identity.seq`,`is`,null).limit(1))!==void 0)}function hasOversizedVisibleMessages(e,t,n,r,i){let a=C(e.database.db,`navigation_valid`,`event`),s=C(e.database.db,`message_role`,`event`);return selectVisibleMessageRanges(e,t,n).some(t=>{let n=o(e.database.db,M(e.database,e.resolved.sessionId,t).select(a.as(`navigation_valid`)).where(e=>e(w(`event`),`>=`,r)).where(e=>e.or([e(s,`in`,i),e(a,`=`,0)])).limit(1));return b(n?.navigation_valid),n!==void 0})}function*iterateVisibleMessageMetadata(e,t,n,r=`asc`){let i=selectVisibleMessageRanges(e,t,n);for(let t of r===`desc`?i.toReversed():i){let n=`positions`in t?c(e.database.db,T(M(e.database,e.resolved.sessionId,t).clearOrderBy().orderBy(`active.message_position`,r))):D(e.database)[r===`desc`?`metadataDescending`:`metadata`]({sessionId:e.resolved.sessionId,start:t.start,endExclusive:t.endExclusive});for(let e of n)yield{event_seq:e.event_seq,message_position:e.message_position,serialized_bytes:e.serialized_bytes,logicalPosition:t.logicalPosition(e.message_position)}}}function readVisibleTranscriptStats(e,t=!1){if(e.contextStats)return e.contextStats;if(e.contextMetadata){let{eventCount:t,sizeBytes:n}=e.contextMetadata;return{eventCount:t,sizeBytes:n,boundaryActivePosition:-1}}let n=t?findLatestResetMessageWindow(e,`context`):resolveTranscriptBoundaryWindow(e,`context`),r=O(e.database).select(e=>[e.fn.countAll().as(`event_count`),l`CAST(COALESCE(SUM(${w(`event`)} ), 0) + COUNT(*) AS BIGINT)`.as(`size_bytes`)]).where(`active.session_id`,`=`,e.resolved.sessionId).where(`active.context_eligible`,`=`,1),i=o(e.database.db,n?r.where(`active.active_position`,`>`,n.boundaryActivePosition):r);return{eventCount:(i?.event_count??0)+(n?.contextPrefixEventCount??0),sizeBytes:(i?.size_bytes??0)+(n?.contextPrefixSizeBytes??0),boundaryActivePosition:n?.boundaryActivePosition??-1}}export{readLatestActiveResetBoundary as a,readVisibleTranscriptStats as c,findUnindexedActiveTranscriptEntry as d,iterateUnindexedActiveTranscriptNavigation as f,iterateVisibleMessageRange as i,resolveTranscriptBoundaryWindow as l,hasUnindexedVisibleMessages as n,readUnindexedHistoryControls as o,iterateUnindexedTranscriptNavigation as p,iterateVisibleMessageMetadata as r,readVisibleMessageRange as s,hasOversizedVisibleMessages as t,resolveVisibleMessagePositions as u};