UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1 lines • 15.4 kB
import{i as e}from"./transcript-record-coerce-eN4p5mcq.mjs";import{r as t}from"./transcript-sqlite-reader-lifecycle-D3Huvbzy.mjs";import{t as n}from"./transcript-sqlite-jsonl-budget-error-DacbQ4UF.mjs";import{a as r,n as i}from"./transcript-sql-connection-CRz-dHXM.mjs";import{i as a,m as o,o as s,r as c}from"./transcript-kysely-sync-DQ_Yn8jW.mjs";import{c as ee,i as te}from"./transcript-session-entry-codec-CvLNFJN0.mjs";import{a as ne,t as l,u}from"./transcript-json-values-CmANsVU4.mjs";import{t as d}from"./transcript-session-actor-transaction-D7al_TuX.mjs";import{t as f}from"./transcript-index-hint-B2XiKU-m.mjs";import{c as p,f as m,i as re,o as h,p as g}from"./transcript-transcript-payload-C58U6XNI.mjs";import{n as _}from"./transcript-transcript-payload-read-BfcV5CyI.mjs";import{r as v}from"./transcript-session-transcript-read-bytes-C7AU5F9V.mjs";import{n as ie}from"./transcript-session-transcript-read-fence-CgDWkLBX.mjs";import{c as y,l as ae,o as b,p as x,t as S}from"./transcript-session-accessor.sqlite-projection-read-HIelFCp6.mjs";import{n as oe,t as C}from"./transcript-session-cache-ttl-prefix-values-C7Fcujlf.mjs";import{n as se,t as w}from"./transcript-session-bounded-context-selection-DzXodtA8.mjs";import{f as T,l as ce,o as le}from"./transcript-session-accessor.sqlite-reset-window-CJLYEFaR.mjs";function transcriptPositionSet(e,t){return o`(SELECT CAST(value AS BIGINT) FROM ${l(e.database.db,o.val(JSON.stringify(t)))})`}function readBoundedRetentionRanges(t,n,r){let i=/* @__PURE__ */ new Map,a=n.flatMap(({event:n,seq:r},a)=>{let o=e(n);return typeof o?.id==`string`?(t.hasUnindexedPrefix&&i.has(o.id)||i.set(o.id,r),(o.type===`compaction`||o.type===`reset`)&&typeof o.firstKeptEntryId==`string`?[{id:o.id,firstKeptEntryId:o.firstKeptEntryId,endIndex:a,seq:r}]:[]):[]}),o=[...new Set(a.map(e=>e.firstKeptEntryId))].filter(e=>!i.has(e));if(o.length>0){let e=n.reduce((e,t)=>Math.max(e,t.seq),-1/0),r=c(t.database.db,y(t.database).select([`identity.event_id`,`identity.seq`]).where(`identity.session_id`,`=`,t.resolved.sessionId).where(`identity.event_id`,`in`,o).where(`identity.seq`,`<=`,e)).rows;for(let e of r)i.set(e.event_id,e.seq)}if(t.hasUnindexedPrefix&&a.length>0){let e=new Set(a.map(e=>e.firstKeptEntryId));for(let n of T(t,{eventIds:[...e],maxRawSeq:a.reduce((e,t)=>Math.max(e,t.seq),-1/0)-1,first:!0})){let t=typeof n.event.id==`string`?n.event.id:void 0;if(t===void 0||!e.delete(t))continue;let r=i.get(t);if((r===void 0||n.event_seq<r)&&i.set(t,n.event_seq),e.size===0)break}}let s=/* @__PURE__ */ new Map;for(let e of a){let a=i.get(e.firstKeptEntryId);if(a===void 0||t.hasUnindexedPrefix&&a>=e.seq)continue;let o=e.endIndex>0&&n[0].seq>=a?0:Math.min(1,e.endIndex),c=o===0?0:e.endIndex;for(;o<c;){let e=Math.floor((o+c)/2);n[e].seq<a?o=e+1:c=e}s.set(e.id,{startIndex:o+r,endIndex:e.endIndex+r})}return s}function readCacheTtlProjectionPrefix(e,t){if(!t||t.activePosition===0)return;let n=o`coalesce(identity.event_type, ${m(e.database.db,`navigation_last_type`,`event`)})`,r=S(e.database),i=r.selectFrom(`transcript_event_identities`).select([`session_id`,`seq`,`event_type`]).where(`session_id`,`=`,e.resolved.sessionId),a=e.hasUnindexedPrefix?r.selectFrom(`session_transcript_active_events as active`).leftJoin(i.clearWhere().modifyEnd(f(e.database.db,`idx_agent_transcript_event_identity_sequence`)).as(`identity`),e=>e.onRef(`identity.session_id`,`=`,`active.session_id`).onRef(`identity.seq`,`=`,`active.event_seq`)):r.selectFrom(i.where(`event_type`,`in`,[`custom`,`reset`]).unionAll(i.where(`event_type`,`is`,null)).as(`identity`)).crossJoin(`session_transcript_active_events as active`).whereRef(`identity.session_id`,`=`,`active.session_id`).whereRef(`identity.seq`,`=`,`active.event_seq`),c=s(e.database.db,a.crossJoin(`transcript_events as event`).whereRef(`event.session_id`,`=`,`active.session_id`).whereRef(`event.seq`,`=`,`active.event_seq`).select(`event.seq`).select(t=>t.case().when(n,`=`,`reset`).then(h(e.database.db,`event`,o.lit(`reset`))).else(null).end().as(`reset_json`)).select(m(e.database.db,`navigation_valid`,`event`).as(`navigation_valid`)).where(`active.session_id`,`=`,e.resolved.sessionId).where(`active.active_position`,`<`,t.activePosition).$call(e=>t.beforeRawSeq===void 0?e:e.where(`active.event_seq`,`<`,t.beforeRawSeq)).where(t=>t.case().when(`identity.event_type`,`not in`,[`custom`,`reset`]).then(!1).else(t.or([t(m(e.database.db,`navigation_valid`,`event`),`=`,0),t(n,`=`,`reset`),t.and([t(n,`=`,`custom`),t(m(e.database.db,`navigation_last_custom_type`,`event`),`=`,`openclaw.cache-ttl`)])])).end()).orderBy(`active.active_position`,`desc`));return C(t,(function*(){for(let t of c){g(t.navigation_valid);let n=t.reset_json??_(b(e,[t.seq])[0]);yield JSON.parse(n)}})())}function readUnindexedLogicalParents(t,n,r){let i=/* @__PURE__ */ new Map;if(n.length===0)return i;let a=c(t.database.db,S(t.database).selectFrom(`session_transcript_active_events as active`).leftJoin(`session_transcript_active_events as previous`,e=>e.onRef(`previous.session_id`,`=`,`active.session_id`).on(e=>e(`previous.active_position`,`=`,e(`active.active_position`,`-`,1)))).leftJoin(`transcript_events as parent`,e=>e.onRef(`parent.session_id`,`=`,`previous.session_id`).onRef(`parent.seq`,`=`,`previous.event_seq`)).select(e=>[`active.event_seq`,`previous.event_seq as parent_seq`,e.fn.coalesce(p(t.database.db,`parent`),e.val(`null`)).as(`parent_json`)]).where(`active.session_id`,`=`,t.resolved.sessionId).where(`active.event_seq`,`in`,transcriptPositionSet(t,n))).rows;for(let t of a){let n=e(r.get(t.event_seq));if(typeof n?.id!=`string`)continue;let a=t.parent_seq===null?void 0:e(JSON.parse(t.parent_json));i.set(n.id,typeof a?.id==`string`?a.id:null)}return i}function readIndexedLogicalParents(e,t){let n=d(e.database,e.resolved);if(n?.transcript.complete){let e=/* @__PURE__ */ new Map;for(let t of n.transcript.identities.values()){let r=n.transcript.active.get(t.seq);r&&e.set(r.active_position,t.event_id)}let r=/* @__PURE__ */ new Map;for(let i of t){let t=n.transcript.active.get(i);if(!t)continue;let a=e.get(t.active_position);a!==void 0&&r.set(a,e.get(t.active_position-1)??null)}return r}return new Map((t.length===0?[]:c(e.database.db,S(e.database).selectFrom(`session_transcript_active_events as active`).innerJoin(`transcript_event_identities as entry`,e=>e.onRef(`entry.session_id`,`=`,`active.session_id`).onRef(`entry.seq`,`=`,`active.event_seq`)).leftJoin(`session_transcript_active_events as previous`,e=>e.onRef(`previous.session_id`,`=`,`active.session_id`).on(e=>e(`previous.active_position`,`=`,e(`active.active_position`,`-`,1)))).leftJoin(`transcript_event_identities as parent`,e=>e.onRef(`parent.session_id`,`=`,`previous.session_id`).onRef(`parent.seq`,`=`,`previous.event_seq`)).select([`entry.event_id`,`parent.event_id as parent_id`]).where(`active.session_id`,`=`,e.resolved.sessionId).where(`active.event_seq`,`in`,transcriptPositionSet(e,t))).rows).map(e=>[e.event_id,e.parent_id]))}function readSessionTranscriptCompactionPlanInTransaction(e,t,n){let r=createSessionTranscriptActiveContextReader(n,!1),{events:i,...a}=x(e,t,r);return a}function createSessionTranscriptActiveContextReader(c,l){let d=w(c);return f=>{let p=c.ignoreReadFence?void 0:ie({database:f.database,...f.resolved}),consume=(e,t)=>{let n=c.onRead?.(f,e,t);if(r(n))throw Promise.resolve(n).catch(()=>{}),Error(`Transcript snapshot consumers must remain synchronous`)};if(f.version.rawSeq===null){let e=p?p.admission.effectiveParentId:f.state.leafEventId;return consume([]),{version:f.version,activeLeafEntryId:e,opaqueParents:e?/* @__PURE__ */ new Map([[e,null]]):/* @__PURE__ */ new Map,parents:/* @__PURE__ */ new Map,firstKeptRanges:/* @__PURE__ */ new Map,persistedSuffixStartSeq:0,boundaryCount:0,events:[],cacheTtlProjectionPrefixes:[],serializedBytes:0,totalEvents:0,transcriptMutationAt:f.version.updatedAt,truncated:!1,...p?{}:{completeActivePath:!0}}}let h=S(f.database),b=h.selectFrom(`transcript_events`).where(`session_id`,`=`,f.resolved.sessionId),x=d?f.contextMetadata:void 0,C=x?x.header:a(f.database.db,b.select([`seq`,m(f.database.db,`navigation_valid`).as(`navigation_valid`),o`${v()} + 1`.as(`serialized_bytes`)]).where(e=>e.or([e(m(f.database.db,`navigation_type`),`=`,`session`),e(m(f.database.db,`navigation_valid`),`=`,0)])).orderBy(`seq`,`asc`).limit(1));g(C?.navigation_valid);let w=C?.serialized_bytes??0,T=x?void 0:ce(f,`context`,p?.beforeRawSeq),E=!d&&T?.boundaryType===`compaction`?[]:T?.keptMessagePositions??[],D=d?E.slice(-(d.maxEvents+1)):E,ue=T?.boundaryType===`compaction`?T.firstKeptActivePosition??T.boundaryActivePosition:T?.boundaryActivePosition,de=ae(f.database),fe=x?x.rows.filter(e=>!p||e.event_seq<p.beforeRawSeq).slice(0,d?d.maxEvents+1:void 0):s(f.database.db,de.where(`active.session_id`,`=`,f.resolved.sessionId).$if(p!==void 0,e=>e.where(`active.event_seq`,`<`,p.beforeRawSeq)).where(e=>{let t=e.and([e(`active.context_eligible`,`=`,1),...!d&&ue!==void 0?[e(`active.active_position`,`>=`,ue)]:[]]);return D.length>0?e.or([t,e(`active.message_position`,`in`,transcriptPositionSet(f,D))]):t}).orderBy(`active.active_position`,`desc`).$if(d!==void 0,e=>e.limit(d.maxEvents+1))),O=se(fe,w,d),{selectedRows:k}=O,A=t();A&&(A.hydrationActiveEvents=f.state.activeEventCount,A.hydrationMetadataRows=x?void 0:k.length+Number(O.truncated),A.hydrationMetadataLimit=!x&&d?d.maxEvents+1:void 0,A.hydrationExhausted=!x&&d?Number(!O.truncated):void 0,A.hydrationDependencyRows=void 0);let{serializedBytes:j,truncated:M}=O,N=k.map(e=>e.event_seq),P=x?void 0:a(f.database.db,h.selectFrom(y(f.database).select(e=>[`active.active_position`,`identity.seq`,e.fn.count(`identity.seq`).over().as(`boundary_count`)]).where(`identity.session_id`,`=`,f.resolved.sessionId).where(`identity.event_type`,`in`,[`compaction`,`reset`]).$if(p!==void 0,e=>e.where(`identity.seq`,`<`,p.beforeRawSeq)).orderBy(`active.active_position`,`desc`).limit(1).as(`boundary`)).crossJoin(`transcript_events as event`).where(`event.session_id`,`=`,f.resolved.sessionId).whereRef(`event.seq`,`=`,`boundary.seq`).select([`boundary.active_position`,`boundary.seq`,`boundary.boundary_count`,o`${v(`event`)} + 1`.as(`serialized_bytes`)])),F=P?.boundary_count??0;if(!x&&f.hasUnindexedPrefix)for(let e of le(f,p?.beforeRawSeq))e.event.type!==`compaction`&&e.event.type!==`reset`||p!==void 0&&e.event_seq>=p.beforeRawSeq||(F+=1,(!P||e.active_position>P.active_position)&&(P={active_position:e.active_position,seq:e.event_seq,serialized_bytes:e.serialized_bytes,boundary_count:F}));N.sort((e,t)=>e-t);let I;P&&!N.includes(P.seq)&&(!d||j+P.serialized_bytes<=d.maxBytes?(I=P.seq,N.unshift(P.seq)):M=!0);let L=o.ref(`dependency.navigation_json`),R=i(f.database.db),z=ne(f.database.db,L),dependencyField=e=>{let t=u(f.database.db,L,o.val(e));return R?o`CASE WHEN ${z} THEN ${t} END`:t},B=Array.from(s(f.database.db,h.with(e=>e(`dependency`).materialized(),()=>de.select(e=>[`active.context_eligible`,o`CASE WHEN facts.seq IS NOT NULL THEN facts.dependency_navigation_json ELSE ${e.selectFrom(`transcript_events as event`).select(re(f.database.db,e.ref(`active.context_eligible`)).as(`navigation_json`)).whereRef(`event.session_id`,`=`,`active.session_id`).whereRef(`event.seq`,`=`,`active.event_seq`)} END`.as(`navigation_json`)]).where(`active.session_id`,`=`,f.resolved.sessionId).where(e=>e.or([e(`active.context_eligible`,`=`,0),e(`active.event_seq`,`not in`,h.selectFrom(`transcript_event_identities`).select(`seq`).where(`session_id`,`=`,f.resolved.sessionId).where(`event_type`,`not in`,[`custom`,`reset`,`branch_summary`]))])).$if(p!==void 0,e=>e.where(`active.event_seq`,`<`,p.beforeRawSeq))).selectFrom(`dependency`).select([`event_seq`,`navigation_json`,`serialized_bytes`]).where(e=>e.or([...R?[e.not(z)]:[],e.and([e(`context_eligible`,`=`,0),e(dependencyField(`$.message.excludeFromContext`),`=`,u(f.database.db,o.lit(`{"value":true}`),o.lit(`$.value`))),e(dependencyField(`$.type`),`=`,`message`),e(dependencyField(`$.message.role`),`=`,`assistant`),e(dependencyField(`$.message.provider`),`=`,`openclaw`),e(dependencyField(`$.message.model`),`=`,`automation-result`),e(dependencyField(`$.message.openclawModelPlacement`),`=`,`pending`)]),e.and([e(dependencyField(`$.type`),`=`,`custom`),e(dependencyField(`$.customType`),`=`,ee)]),e(dependencyField(`$.type`),`in`,[`reset`,`branch_summary`])])).orderBy(`active_position`,`asc`)),e=>({seq:e.event_seq,serialized_bytes:e.serialized_bytes,event:JSON.parse(e.navigation_json)})),V=new Map(k.map(e=>[e.event_seq,e]));A&&(A.hydrationDependencyRows=B.length);let H=oe(N.map(e=>({seq:e,serialized_bytes:e===P?.seq?P.serialized_bytes:V.get(e).serialized_bytes})),B,w,d?.maxBytes);if(N.splice(0,N.length,...H.rows.map(e=>e.seq)),j=H.serializedBytes,l&&c.maxMaterializedBytes!==void 0&&j>c.maxMaterializedBytes)throw new n(`Session transcript exceeds the materialized preparation byte limit`);M||=H.truncated,I!==void 0&&!N.includes(I)&&(I=void 0);let U=C?[C.seq,...N]:N,W=new Map(H.rows.map(e=>[e.seq,e.serialized_bytes]));C&&W.set(C.seq,w);let G=/* @__PURE__ */ new Map,K,q,J;if(U.length>0)for(let t of s(f.database.db,b.select([`seq`,`event_json`,`event_zstd`,`event_utf8_bytes`]).where(`seq`,`in`,transcriptPositionSet(f,U)))){let n=JSON.parse(_(t));if(c.onEntry){let e=W.get(t.seq);if(e===void 0)throw Error(`Selected transcript row has no recorded payload size`);let i=c.onEntry(n,{rawSeq:t.seq,serializedBytes:e});if(r(i))throw Promise.resolve(i).catch(()=>{}),Error(`Transcript snapshot consumers must remain synchronous`)}let i=e(n),a=V.get(t.seq);a&&typeof i?.id==`string`&&(!K||a.active_position<K.active_position)&&(K=a,q=i),t.seq===I&&(J=i),G.set(t.seq,l?n:i?{type:typeof i.type==`string`?i.type:void 0,...`id`in i?{id:typeof i.id==`string`?i.id:void 0}:{},...`parentId`in i?{parentId:typeof i.parentId==`string`?i.parentId:null}:{},firstKeptEntryId:typeof i.firstKeptEntryId==`string`?i.firstKeptEntryId:void 0}:void 0)}let pe=f.hasUnindexedPrefix?readUnindexedLogicalParents(f,N,G):readIndexedLogicalParents(f,N),Y=l&&C?[G.get(C.seq)]:[],X=N.map(e=>({event:G.get(e),seq:e})),Z=/* @__PURE__ */ new Map,Q;for(let{event:t,seq:n}of X){let r=e(t);n===I?Q=r?.id:r&&`id`in r&&`parentId`in r&&(typeof Q==`string`&&typeof r.parentId==`string`&&r.parentId!==Q&&Z.set(r.parentId,Q),Q=r.id),l&&Y.push(t)}let me=[...P&&te(J)&&J.type===`compaction`?[{activePosition:P.active_position,id:J.id,entry:J}]:[],...K&&typeof q?.id==`string`?[{activePosition:K.active_position,id:q.id,entry:q}]:[]].flatMap(e=>{let t=readCacheTtlProjectionPrefix(f,{...e,beforeRawSeq:p?.beforeRawSeq});return t?[t]:[]}),$=p?p.admission.effectiveParentId:f.state.leafEventId;$&&Q!==$&&Z.set($,typeof Q==`string`?Q:null);let he=readBoundedRetentionRanges(f,X,+!!C),ge=f.version;return consume([...C?[{rawSeq:C.seq,serializedBytes:w}]:[],...N.map(e=>({rawSeq:e,serializedBytes:W.get(e)}))],X.some(({event:t})=>e(t)?.type===`message`)?!0:void 0),{version:ge,activeLeafEntryId:$,opaqueParents:Z,parents:pe,firstKeptRanges:he,persistedSuffixStartSeq:N[0]??(C?C.seq+1:0),boundaryCount:F,events:Y,cacheTtlProjectionPrefixes:me,serializedBytes:j,totalEvents:f.state.activeEventCount,transcriptMutationAt:ge.updatedAt,truncated:M,...!M&&!p&&!f.hasUnindexedPrefix&&k.length===f.state.activeEventCount?{completeActivePath:!0}:{}}}}export{createSessionTranscriptActiveContextReader,readSessionTranscriptCompactionPlanInTransaction};