UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

6 lines • 28 kB
import{M as e}from"./transcript-chat-message-content-Cx-VPFHv.mjs";import{i as t}from"./transcript-record-coerce-eN4p5mcq.mjs";import{h as n}from"./transcript-number-coercion-Dr06QpMa.mjs";import{t as r}from"./transcript-map-size-DkeBKk4z.mjs";import{n as i,r as a}from"./transcript-sql-connection-CRz-dHXM.mjs";import{u as o}from"./transcript-kysely-sync-cache-state-9JTloBF9.mjs";import{c as s}from"./transcript-sqlite-schema-facts-C4Tsn8VX.mjs";import{c,i as l,l as u,m as d,r as f,t as p,u as m}from"./transcript-kysely-sync-DQ_Yn8jW.mjs";import{i as h}from"./transcript-nested-tool-activity-nGNS0H_L.mjs";import{t as g}from"./transcript-json-values-CmANsVU4.mjs";import{t as _}from"./transcript-index-hint-B2XiKU-m.mjs";import{b as v}from"./transcript-tool-call-xml-BErSpGGl.mjs";import{f as y,p as b}from"./transcript-transcript-payload-C58U6XNI.mjs";import{n as x}from"./transcript-transcript-payload-read-BfcV5CyI.mjs";import{r as S}from"./transcript-session-transcript-read-bytes-C7AU5F9V.mjs";import{n as C,t as w}from"./transcript-session-transcript-read-fence-CgDWkLBX.mjs";import{n as T}from"./transcript-transcript-visible-record-sz9xHogO.mjs";import{i as E}from"./transcript-session-accessor.sqlite-visible-cursor-CP4ccuQd.mjs";import{c as D,o as O,t as k}from"./transcript-session-accessor.sqlite-projection-read-HIelFCp6.mjs";import{d as A,i as j,l as M,n as N,o as P,p as F,r as I,s as L,u as R}from"./transcript-session-accessor.sqlite-reset-window-CJLYEFaR.mjs";import{n as z}from"./transcript-session-transcript-raw-cursor-CM0Eyj1y.mjs";import{n as B}from"./transcript-session-accessor.sqlite-raw-delta-read-BPgFMgdh.mjs";import{t as V}from"./transcript-session-transcript-source-pages-4In3PTCc.mjs";import{n as H,r as U,t as W}from"./transcript-transcript-anchor-page-CrBoJln6.mjs";import{n as G,t as K}from"./transcript-transcript-display-position-CeSwa-oH.mjs";import{t as q}from"./transcript-session-history-visibility-VnlSe8OR.mjs";import{channel as J}from"node:diagnostics_channel";function readTranscriptDisplaySource(e){let t=e.generation;return t?G([`sqlite`,e.database.path,e.resolved.agentId,e.resolved.sessionId,t]):void 0}function positionTranscriptDisplayEvents(e,n,r,i=e.state.indexedSeq){if(!n||r.length===0)return r;let a=r.map(({event:e})=>h(t(e)?.message)?.details),o=[...new Set(a.flatMap(e=>e?.afterEntryId??[]))],s=/* @__PURE__ */ new Map,c=C({database:e.database,...e.resolved})?.beforeRawSeq,l=Math.min(i,c===void 0?1/0:c-1);if(o.length>0){let t=f(e.database.db,k(e.database).selectFrom(d`${m(o)}`.as(`requested`)).crossJoin(`transcript_event_identities as identity`).select([`identity.event_id`,`identity.seq`]).where(`identity.session_id`,`=`,e.resolved.sessionId).whereRef(`identity.event_id`,`=`,`requested.value`).where(`identity.seq`,`<=`,l)).rows;for(let e of t)s.set(e.event_id,e.seq)}if(e.hasUnindexedPrefix){let t=new Set(o.filter(e=>!s.has(e)));if(t.size>0)for(let n of F(e,{eventIds:[...t],maxRawSeq:l})){let e=typeof n.event.id==`string`?n.event.id.trim():void 0;e!==void 0&&t.has(e)&&s.set(e,n.event_seq)}}return r.map((e,t)=>({...e,displayPosition:K(n,e.eventSeq,a[t],e=>s.get(e))}))}function selectActiveResetRows(e){return k(e.database).selectFrom(`session_transcript_active_events as active`).innerJoin(`transcript_event_identities as identity`,e=>e.onRef(`identity.session_id`,`=`,`active.session_id`).onRef(`identity.seq`,`=`,`active.event_seq`)).select(`active.active_position`).where(`active.session_id`,`=`,e.resolved.sessionId).where(`identity.event_type`,`=`,`reset`)}function resolveClosedResetInterval(e,t){let n=t.eventType===`reset`?{active_position:t.activePosition}:l(e.database.db,selectActiveResetRows(e).where(`active.active_position`,`>`,t.activePosition).orderBy(`active.active_position`,`asc`).limit(1)),r=P(e).filter(e=>e.event.type===`reset`);if(t.eventType!==`reset`){let e=r.find(e=>e.active_position>t.activePosition);e&&(!n||e.active_position<n.active_position)&&(n=e)}if(!n)return;let i=l(e.database.db,selectActiveResetRows(e).where(`active.active_position`,`<`,n.active_position).orderBy(`active.active_position`,`desc`).limit(1)),a=r.findLast(e=>e.active_position<n.active_position);return a&&(!i||a.active_position>i.active_position)&&(i=a),{startExclusiveActivePosition:i?.active_position??-1,endInclusiveActivePosition:n.active_position}}function isVisibleHistoryNonMessageEventSql(e,t,n,r){return d`(${e} IN ('compaction', 'reset', 'custom_message') AND CASE WHEN ${e} IN ('compaction', 'reset') THEN TRUE WHEN ${e} = 'custom_message' THEN ${r} = 0 OR (${t} = 1 AND (${n} IS NULL OR ${n} != ${v})) ELSE FALSE END)`}function historyNavigationValidSql(e){return d`CASE WHEN identity.event_type = 'custom_message' THEN ${y(e,`navigation_valid`,`event`)} ELSE 1 END`}function parseStoredTranscriptEvent(e){return JSON.parse(e)}function selectHistoricalDisplayEvents(e,t){let n=k(e.database).selectFrom(`session_transcript_active_events as active`),r=k(e.database).selectFrom(`transcript_event_identities`).select([`session_id`,`seq`,`event_type`]).modifyEnd(_(e.database.db,`idx_agent_transcript_event_identity_sequence`)).as(`identity`),i=e.hasUnindexedPrefix?n.leftJoin(r,e=>e.onRef(`identity.session_id`,`=`,`active.session_id`).onRef(`identity.seq`,`=`,`active.event_seq`)):n.innerJoin(r,e=>e.onRef(`identity.session_id`,`=`,`active.session_id`).onRef(`identity.seq`,`=`,`active.event_seq`)),a=P(e).filter(e=>q(e.event)&&e.active_position>t.startExclusiveActivePosition&&e.active_position<=t.endInclusiveActivePosition).map(e=>e.event_seq);return i.innerJoin(`transcript_events as event`,e=>e.onRef(`event.session_id`,`=`,`active.session_id`).onRef(`event.seq`,`=`,`active.event_seq`)).where(`active.session_id`,`=`,e.resolved.sessionId).where(`active.active_position`,`>`,t.startExclusiveActivePosition).where(`active.active_position`,`<=`,t.endInclusiveActivePosition).where(t=>t.or([t(`active.message_position`,`is not`,null),isVisibleHistoryNonMessageEventSql(t.ref(`identity.event_type`),y(e.database.db,`navigation_display`,`event`),y(e.database.db,`navigation_custom_type`,`event`),y(e.database.db,`navigation_valid`,`event`)),...a.length>0?[t(`active.event_seq`,`in`,d`(SELECT CAST(value AS BIGINT) FROM ${g(e.database.db,d.val(JSON.stringify(a)))})`)]:[]]))}function selectDisplayableActiveEventById(e,t){return D(e.database).innerJoin(`transcript_events as event`,e=>e.onRef(`event.session_id`,`=`,`active.session_id`).onRef(`event.seq`,`=`,`active.event_seq`)).select([`active.event_seq`,`active.active_position`,`active.message_position`,`identity.event_type`,historyNavigationValidSql(e.database.db).as(`navigation_valid`)]).where(`identity.session_id`,`=`,e.resolved.sessionId).where(`identity.event_id`,`=`,t).where(t=>t.or([t(`active.message_position`,`is not`,null),isVisibleHistoryNonMessageEventSql(t.ref(`identity.event_type`),y(e.database.db,`navigation_display`,`event`),y(e.database.db,`navigation_custom_type`,`event`),y(e.database.db,`navigation_valid`,`event`))]))}function readDisplayableActiveEventById(e,t,n){let r=l(e.database.db,selectDisplayableActiveEventById(e,t).select(S(`event`).as(`serialized_bytes`)));if(b(r?.navigation_valid),r){if(n!==void 0&&r.serialized_bytes>n)return;let t=O(e,[r.event_seq])[0];return t?{...r,event_json:x(t)}:void 0}let i=A(e,t);if(!i||i.message_position===null&&!q(i.event)||n!==void 0&&i.serialized_bytes-1>n)return;let a=O(e,[i.event_seq])[0];return a?{event_seq:i.event_seq,active_position:i.active_position,message_position:i.message_position,event_type:typeof i.event.type==`string`?i.event.type:null,event_json:x(a)}:void 0}function readDisplayableActiveEventMetadataById(e,t){let n=l(e.database.db,selectDisplayableActiveEventById(e,t));if(b(n?.navigation_valid),n)return n;let r=A(e,t);if(r&&(r.message_position!==null||q(r.event)))return{event_seq:r.event_seq,active_position:r.active_position,message_position:r.message_position,event_type:typeof r.event.type==`string`?r.event.type:null}}function countHistoricalDisplayEvents(e,t,n){let r=selectHistoricalDisplayEvents(e,t).select(t=>[t.fn.countAll().as(`event_count`),t.fn.min(historyNavigationValidSql(e.database.db)).as(`navigation_valid`)]).where(`active.active_position`,`<`,n),i=l(e.database.db,r);return b(i?.navigation_valid??void 0),i?.event_count??0}function readHistoricalDisplayEventRange(e,t,n,r,i,a,o,s){if(i<=0)return[];let c=selectHistoricalDisplayEvents(e,n).select(t=>[`active.event_seq`,historyNavigationValidSql(e.database.db).as(`navigation_valid`),t(S(`event`),`+`,1).as(`serialized_bytes`)]),l=Math.max(0,a.displayPosition-r),u=l===0?[]:f(e.database.db,c.where(`active.active_position`,`<`,a.activePosition).orderBy(`active.active_position`,`desc`).limit(l)).rows,d=f(e.database.db,c.where(`active.active_position`,r>a.displayPosition?`>`:`>=`,a.activePosition).orderBy(`active.active_position`,`asc`).limit(i-l)).rows,p=[...u.toReversed(),...d].map((e,t)=>(b(e.navigation_valid),Object.assign(e,{displaySeq:r+t+1}))),m=Math.min(V,Math.max(1024,Math.floor(o??8388608))),h=W({readStart:0,endExclusive:p.length,hasOverreadContext:!1,offset:0},s?a.displayPosition-r:p.length-1,m,e=>p[e].serialized_bytes,s!==void 0&&o===void 0),g=p.slice(h.start,h.endExclusive);if(g.length===0)return[];let _=O(e,g.map(e=>e.event_seq)),v=new Map(_.map(e=>[e.seq,x(e)]));return positionTranscriptDisplayEvents(e,t,g.flatMap(e=>{let t=v.get(e.event_seq);return t===void 0?[]:[{event:parseStoredTranscriptEvent(t),eventSeq:e.event_seq,seq:e.displaySeq}]}))}function resolveClosedResetIntervalForDisplayable(e,t){if(typeof t.event_type==`string`)return resolveClosedResetInterval(e,{activePosition:t.active_position,eventType:t.event_type})}function resolveHistoricalHistoryEvent(e,t){let n=resolveClosedResetIntervalForDisplayable(e,t);if(n)return{event:parseStoredTranscriptEvent(t.event_json),eventSeq:t.event_seq,seq:countHistoricalDisplayEvents(e,n,t.active_position)+1}}function readHistoricalHistoryPrecedingEvent(e,t,n){let r=resolveClosedResetIntervalForDisplayable(e,t);return r&&n.seq>1?readHistoricalDisplayEventRange(e,void 0,r,n.seq-2,1,{activePosition:t.active_position,displayPosition:n.seq-1})[0]:void 0}function readHistoricalHistoryAnchorPage(e,t,n,r,i=!1){let a=resolveClosedResetIntervalForDisplayable(e,n);if(!a)return;let o=l(e.database.db,selectHistoricalDisplayEvents(e,a).select(t=>[t.fn.countAll().as(`total`),t.fn.min(historyNavigationValidSql(e.database.db)).as(`navigation_valid`),t.fn.countAll().filterWhere(`active.active_position`,`<`,n.active_position).as(`before_anchor`)]));b(o?.navigation_valid??void 0);let s=o?.before_anchor??0,c=i?s:o?.total??0,u=H(c,i?c-1:s,r),d=u.endExclusive-u.readStart,f=readHistoricalDisplayEventRange(e,t,a,u.readStart,d,{activePosition:n.active_position,displayPosition:s},r.maxBytes,r);return{events:f,found:!0,hasOverreadContext:u.hasOverreadContext&&f[0]?.seq===u.readStart+1,offset:c-(f.at(-1)?.seq??u.endExclusive),displaySource:t,totalMessages:c}}function resolveHistoryBoundaryQueryShape(e,t){if(t!==void 0)return`reset`;if(e.state.activeEventCount>=e.state.indexedSeq)return`markers`;let n=k(e.database);return l(e.database.db,n.selectFrom(n.selectFrom(`transcript_event_identities`).select([`session_id`,`event_type`,`seq`]).modifyEnd(_(e.database.db,`idx_agent_transcript_event_sequence`)).as(`identity`)).select(`seq`).where(`session_id`,`=`,e.resolved.sessionId).where(`event_type`,`in`,[`compaction`,`reset`,`custom_message`]).limit(1).offset(Math.max(0,e.state.activeEventCount-1)))?`branch`:`markers`}function selectVisibleHistoryBoundaries(e,t,n,r){let i=k(e),a=i.selectFrom(`transcript_event_identities`).select([`session_id`,`event_id`,`seq`,`event_type`]).modifyEnd(_(e.db,n===`markers`?`idx_agent_transcript_event_sequence`:`idx_agent_transcript_event_identity_sequence`)).as(`identity`);return(n===`markers`?i.selectFrom(a).crossJoin(`session_transcript_active_events as active`):i.selectFrom(`session_transcript_active_events as active`).crossJoin(a)).crossJoin(`transcript_events as event`).whereRef(`identity.session_id`,`=`,`active.session_id`).whereRef(`identity.seq`,`=`,`active.event_seq`).whereRef(`event.session_id`,`=`,`active.session_id`).whereRef(`event.seq`,`=`,`active.event_seq`).where(`active.session_id`,`=`,t).where(t=>{let n=isVisibleHistoryNonMessageEventSql(t.ref(`identity.event_type`),y(e.db,`navigation_display`,`event`),y(e.db,`navigation_custom_type`,`event`),y(e.db,`navigation_valid`,`event`));if(r===void 0)return n;let i=t(`active.active_position`,`>=`,r);return t.and([i,n])})}const Y=p(()=>/* @__PURE__ */ new Map);function getHistoryCountReader(e,t){let n=Y(e.db),r=n.get(t);return r||(r=u(e.db,n=>selectVisibleHistoryBoundaries(e,n(e=>e.sessionId),t,t===`reset`?n(e=>e.boundaryActivePosition):void 0).select(t=>[t.fn.countAll().as(`event_count`),t.fn.min(historyNavigationValidSql(e.db)).as(`navigation_valid`)])),n.set(t,r)),r}function resolveVisibleHistoryEventCount(e){if(e.state.activeEventCount===e.state.activeMessageCount)return e.state.activeMessageCount;let t=R(e),n=resolveHistoryBoundaryQueryShape(e,t.boundaryActivePosition),r=getHistoryCountReader(e.database,n)({sessionId:e.resolved.sessionId,boundaryActivePosition:t.boundaryActivePosition??0});b(r?.navigation_valid??void 0);let i=P(e).filter(e=>q(e.event)&&e.active_position>=(t.boundaryActivePosition??0));return t.total+(r?.event_count??0)+i.length}function resolveVisibleHistoryProjection(e){return e.resolveVisibleHistory?.(e)??buildVisibleHistoryProjection(e)}function buildVisibleHistoryProjection(e){let t=readTranscriptDisplaySource(e);if(e.state.activeEventCount===e.state.activeMessageCount)return{boundaries:[],boundariesById:/* @__PURE__ */ new Map,boundariesBySeq:/* @__PURE__ */ new Map,displaySource:t,latestResetRawSeq:null,total:e.state.activeMessageCount};let n=R(e),r=M(e)?.boundarySeq??null,i=k(e.database),a=f(e.database.db,selectVisibleHistoryBoundaries(e.database,e.resolved.sessionId,resolveHistoryBoundaryQueryShape(e,n.boundaryActivePosition),n.boundaryActivePosition).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.active_position`,`following.message_position as following_message_position`,`identity.event_id`,`identity.seq`,historyNavigationValidSql(e.database.db).as(`navigation_valid`),d`${S(`event`)} + 1`.as(`serialized_bytes`)]).orderBy(`active.active_position`,`asc`)).rows;for(let e of a)b(e.navigation_valid);for(let t of P(e))!q(t.event)||t.active_position<(n.boundaryActivePosition??0)||a.push({active_position:t.active_position,following_message_position:t.following_message_position,event_id:typeof t.event.id==`string`?t.event.id.trim():``,seq:t.event_seq,serialized_bytes:t.serialized_bytes,navigation_valid:1});e.hasUnindexedPrefix&&a.sort((e,t)=>e.active_position-t.active_position);let o=c(e.database.db,t=>i.selectFrom(`session_transcript_active_events`).select([`active_position`,`message_position`]).where(`session_id`,`=`,e.resolved.sessionId).where(`active_position`,`>`,t(e=>e)).where(`message_position`,`is not`,null).orderBy(`active_position`,`asc`).limit(1)),s,l=!1,u=a.map((t,r)=>{let i=t.following_message_position;i===null&&((!l||s&&s.active_position<t.active_position)&&(s=o(t.active_position).rows[0],l=!0),i=s?.message_position??e.state.activeMessageCount);let a=n.kept.length+Math.max(0,i-n.postStart);return{displayPosition:a+r,eventId:t.event_id,eventSeq:t.seq,messagePosition:a,serializedBytes:t.serialized_bytes}});return{boundaries:u,boundariesById:new Map(u.map(e=>[e.eventId,e])),boundariesBySeq:new Map(u.map(e=>[e.eventSeq,e])),displaySource:t,latestResetRawSeq:r,total:n.total+u.length}}function resolveVisibleHistoryRange(e,t,n){let r=Math.min(Math.max(0,t),e.total),i=Math.min(Math.max(r,n),e.total),a=0,o=e.boundaries.length;for(;a<o;){let t=Math.floor((a+o)/2);e.boundaries[t].displayPosition<r?a=t+1:o=t}let s=/* @__PURE__ */ new Map;for(let t=a;t<e.boundaries.length;t+=1){let n=e.boundaries[t];if(!(n.displayPosition<i))break;s.set(n.displayPosition,n)}let c=r-a;return{boundedEnd:i,boundedStart:r,boundaries:s,messageEnd:c+i-r-s.size,messageStart:c}}function resolveHistoryMessageSequence(e,t,n){let r=n>=e.postStart?e.kept.length+n-e.postStart:e.kept.indexOf(n);if(r<0)return;let i=0,a=t.boundaries.length;for(;i<a;){let e=Math.floor((i+a)/2);t.boundaries[e].messagePosition<=r?i=e+1:a=e}return r+1+i}function captureHistoryReadWindow(e,t){let n=t.at(-1);return{source:e.displaySource,latestResetRawSeq:e.latestResetRawSeq,...n?{anchor:{rawSeq:n.eventSeq,seq:n.seq}}:{}}}function resolveHistoryReadWindowChange(e,t,n){if(!n)return;if(n.source!==t.displaySource)return{};let r=n.anchor;if(!r)return n.latestResetRawSeq===t.latestResetRawSeq?void 0:{};let i=readActiveTranscriptCoordinate(e,{eventSeq:r.rawSeq})?.message_position,a=i===null?t.boundariesBySeq.get(r.rawSeq):void 0,o=i===void 0?void 0:i===null?a&&a.displayPosition+1:resolveHistoryMessageSequence(R(e),t,i);return o===r.seq&&n.latestResetRawSeq===t.latestResetRawSeq?void 0:{anchorSeq:o}}function readActiveTranscriptCoordinate(e,t){let n=k(e.database).selectFrom(`session_transcript_active_events`).select([`event_seq`,`message_position`,`active_position`]).where(`session_id`,`=`,e.resolved.sessionId);return l(e.database.db,`eventSeq`in t?n.where(`event_seq`,`=`,t.eventSeq):n.where(`active_position`,`=`,t.activePosition))}var X=/* @__PURE__ */ e({readRecentSessionTranscriptHistoryEventsFromProjection:()=>readRecentSessionTranscriptHistoryEventsFromProjection,readSessionTranscriptHistoryAnchorPageFromProjection:()=>readSessionTranscriptHistoryAnchorPageFromProjection,readSessionTranscriptHistoryEventByIdFromProjection:()=>readSessionTranscriptHistoryEventByIdFromProjection,readSessionTranscriptHistoryEventLookupFromProjection:()=>readSessionTranscriptHistoryEventLookupFromProjection,readSessionTranscriptHistoryEventPageFromProjection:()=>readSessionTranscriptHistoryEventPageFromProjection,readTranscriptDisplayDeltaFromProjection:()=>readTranscriptDisplayDeltaFromProjection});const Z={pressure:J(`openclaw.memory.critical`),windows:/* @__PURE__ */ new Map};Z.pressure.subscribe(()=>Z.windows.clear());const Q=/* @__PURE__ */ new WeakSet;function retainHistoryWindowOwner(e){Q.has(e)||(o(a(e),()=>{for(let[t,n]of Z.windows)n.database===e&&Z.windows.delete(t)}),Q.add(e))}function readBoundaryEvents(e,t){let n=Array.from(t,e=>e.eventSeq);return n.length===0?/* @__PURE__ */ new Map:new Map(O(e,n).map(e=>[e.seq,parseStoredTranscriptEvent(x(e))]))}function readVisibleHistoryRange(e,t,n,r){let i=resolveVisibleHistoryRange(r,t,n);if(i.boundedEnd<=i.boundedStart)return[];let a=L(e,i.messageStart,i.messageEnd),o=readBoundaryEvents(e,i.boundaries.values());return positionTranscriptDisplayEvents(e,r.displaySource,Array.from(mergeVisibleHistoryEvents(i,a,o)))}function*mergeVisibleHistoryEvents(e,t,n){let r=t[Symbol.iterator]();try{for(let t=e.boundedStart;t<e.boundedEnd;t+=1){let i=e.boundaries.get(t);if(i){let e=n.get(i.eventSeq);e&&(yield{event:e,eventSeq:i.eventSeq,seq:t+1});continue}let a=r.next();a.done||(yield{...a.value,seq:t+1})}}finally{r.return?.()}}function resolveRecentHistoryStart(e,t,n,r,i,a,o=!0){let{boundedEnd:s,boundedStart:c,boundaries:l,messageEnd:u,messageStart:d}=resolveVisibleHistoryRange(r,t,n),f=Math.max(d,u-a),p=I(e,f,u,`desc`),m,h=u-1,g=s,_=0,v=0;try{for(let e=s-1;e>=c&&!(_>=a);--e){let t=l.get(e),n=t?.serializedBytes;if(t||(m??=p.next(),!m.done&&m.value.logicalPosition===h&&(n=m.value.serialized_bytes,m=void 0),--h),n!==void 0){if(o&&_===0&&n>8388608)throw Error(`Chat history message exceeds the ${V}-byte page limit`);if((!o||_>0)&&v+n>i)break;g=e,_+=1,v+=n}}}finally{p.return?.()}return{start:g,bytes:v}}function resolveHistoryEventSequence(e,t,n){if(n.message_position===null){let e=t.boundariesBySeq.get(n.event_seq);return e===void 0?void 0:e.displayPosition+1}return resolveHistoryMessageSequence(R(e),t,n.message_position)}function resolveHistoryEventById(e,t,n,r){let i=n.boundariesById.get(t);if(i){if(r!==void 0&&i.serializedBytes>r)return;let t=readBoundaryEvents(e,[i]).get(i.eventSeq);return t?{event:t,eventSeq:i.eventSeq,seq:i.displayPosition+1,...r===void 0?{}:{serializedBytes:i.serializedBytes}}:void 0}let a=readDisplayableActiveEventById(e,t,r);if(!a)return;let o=resolveHistoryEventSequence(e,n,a);return o===void 0?{historical:a}:{event:parseStoredTranscriptEvent(a.event_json),eventSeq:a.event_seq,seq:o,...r===void 0?{}:{serializedBytes:Buffer.byteLength(a.event_json,`utf8`)}}}function readTranscriptDisplayDeltaFromProjection(e,t={}){let n=B(e,t);if(n.kind!==`page`)return n;if(n.events.length===0)return{...n,activeLeafEntryId:e.state.leafEventId};let r=resolveVisibleHistoryProjection(e),i=R(e),a=n.events[0].seq,o=n.events.at(-1).seq,s=k(e.database),c=new Map(f(e.database.db,s.selectFrom(`session_transcript_active_events`).select([`event_seq`,`message_position`]).where(`session_id`,`=`,e.resolved.sessionId).where(`event_seq`,`>=`,a).where(`event_seq`,`<=`,o).where(`message_position`,`is not`,null)).rows.map(e=>[e.event_seq,e.message_position===null?void 0:resolveHistoryMessageSequence(i,r,e.message_position)]));for(let e of n.events){let t=r.boundariesBySeq.get(e.seq);t&&c.set(t.eventSeq,t.displayPosition+1)}let l=positionTranscriptDisplayEvents(e,r.displaySource,n.events.map(e=>{let t=c.get(e.seq);return{...e,eventSeq:e.seq,...t===void 0?{}:{messageSeq:t}}}));return{...n,activeLeafEntryId:e.state.leafEventId,events:l}}function readRecentHistoryInSnapshot(e,t,r,i){let a=resolveHistoryReadWindowChange(e,t,r.expectedReadWindow),o=r.captureReadWindow||a,s=e.generation,c=s?z({agentId:e.resolved.agentId,generation:s,lastSeq:e.state.indexedSeq,sessionId:e.resolved.sessionId}):void 0,l=n(r.maxMessages,0,{min:0,max:E}),u=n(r.maxLines,0,{min:0}),d=l===0||u===0,{start:f,bytes:p}=d?{start:t.total,bytes:0}:resolveRecentHistoryStart(e,Math.max(0,t.total-u),t.total,t,Math.min(n(r.maxBytes,V,{min:1024}),V),l),m=d?[]:readVisibleHistoryRange(e,f,t.total,t),h={activeLeafEntryId:e.state.leafEventId,...c?{deltaCursor:c}:{},events:m,displaySource:t.displaySource,totalMessages:t.total,...o?{readWindow:captureHistoryReadWindow(t,m)}:{},...a?{windowReset:!0}:{}};return d||i?.(h,p),h}function readRecentSessionTranscriptHistoryEventsFromProjection(e,t){let read=n=>readRecentHistoryInSnapshot(e,resolveVisibleHistoryProjection(e),t,n);if(!e.generation||s(e.database.db)||i(e.database.db)||e.database.db.location()===null||t.expectedReadWindow||w(e.resolved))return read();let n=JSON.stringify([e.database.path,e.resolved.agentId,e.resolved.sessionId]),a=JSON.stringify([e.generation,e.state.indexedSeq,e.version.updatedAt,t.maxMessages,t.maxLines,t.maxBytes,!!t.captureReadWindow]),o=Z.windows.get(n);return o?.database===e.database.db&&o.revision===a?structuredClone(o.page):(Z.windows.delete(n),read((t,i)=>{if(!(i>1048576))try{let i=e.database.db;retainHistoryWindowOwner(i),Z.windows.set(n,{database:i,revision:a,page:structuredClone(t)}),r(Z.windows,16)}catch{}}))}function readSessionTranscriptHistoryEventPageFromProjection(e,t){let r=t,i=resolveVisibleHistoryProjection(e),a=resolveHistoryReadWindowChange(e,i,r.expectedReadWindow);if(a){let e=r.expectedReadWindow?.anchor;r={...r,captureReadWindow:!0,expectedReadWindow:void 0,...a.anchorSeq!==void 0&&e?{beforeSeq:r.beforeSeq===void 0?void 0:r.beforeSeq+a.anchorSeq-e.seq}:{beforeSeq:void 0,offset:0}}}let o=U(i.total,r);if(r.recentAtHead&&o===i.total)return{...readRecentHistoryInSnapshot(e,i,{...r.recentAtHead,captureReadWindow:r.captureReadWindow,expectedReadWindow:r.expectedReadWindow}),...a?{windowReset:!0}:{}};let s=n(r.maxMessages,0,{min:0}),c=Math.max(0,o-s),l=resolveRecentHistoryStart(e,c,o,i,n(r.maxBytes,V,{min:1024}),s,r.allowOversizedFirst??r.maxBytes===void 0).start;if(r.maxBytes===void 0&&l!==c)throw Error(`Transcript history page exceeds the ${V}-byte limit; request a smaller limit`);let u=s>0&&o>0&&l===o,d=u?o-1:l,f=readVisibleHistoryRange(e,l,o,i);return{activeLeafEntryId:e.state.leafEventId,events:f,displaySource:i.displaySource,totalMessages:i.total,...r.maxBytes!==void 0&&s>0&&d>0?{olderOffset:U(i.total,{beforeSeq:r.beforeSeq})-d}:{},...u?{omittedOversized:!0}:{},...r.captureReadWindow?{readWindow:captureHistoryReadWindow(i,f)}:{},...a?{windowReset:!0}:{}}}function readSessionTranscriptHistoryEventByIdFromProjection(e,t,n={},r){let i=resolveVisibleHistoryProjection(e),a=resolveHistoryEventById(e,t,i,n.maxBytes),o=a&&(`historical`in a?n.currentOnly?void 0:resolveHistoricalHistoryEvent(e,a.historical):a);if(!o)return;let s=r?.(o)?a&&`historical`in a?readHistoricalHistoryPrecedingEvent(e,a.historical,o):readVisibleHistoryRange(e,Math.max(0,o.seq-2),o.seq-1,i)[0]:void 0;return positionTranscriptDisplayEvents(e,i.displaySource,[{...o,...s?{preceding:s}:{}}])[0]}function readSessionTranscriptHistoryEventLookupFromProjection(e,t){let n=resolveVisibleHistoryProjection(e),r=resolveVisibleHistoryRange(n,0,n.total);if(!t.trim()||N(e,r.messageStart,r.messageEnd)){let t=readVisibleHistoryRange(e,0,n.total,n);return{events:t,hasDisplayMessages:t.some(e=>T(e.event))}}let i=readBoundaryEvents(e,r.boundaries.values()),a,o=!1;for(let t of mergeVisibleHistoryEvents(r,j(e,r.messageStart,r.messageEnd),i))if(a??=t,T(t.event)){o=!0;break}let s=resolveHistoryEventById(e,t.trim(),n),c=s&&!(`historical`in s)?s:void 0,l=positionTranscriptDisplayEvents(e,n.displaySource,c?[c]:a?[a]:[]);return{events:c?l:[],hasDisplayMessages:o}}function readSessionTranscriptHistoryAnchorPageFromProjection(e,t){let n=resolveVisibleHistoryProjection(e),r=readDisplayableActiveEventMetadataById(e,t.messageId);if(t.closedResetInterval===!0&&t.direction===`older`&&r?.event_type===`reset`){let i=readHistoricalHistoryAnchorPage(e,n.displaySource,r,t,!0);if(i)return{...i,...t.captureReadWindow?{readWindow:captureHistoryReadWindow(n,[])}:{}}}let i=resolveHistoryReadWindowChange(e,n,t.expectedReadWindow),a=r&&resolveHistoryEventSequence(e,n,r);if(i&&a===void 0)return{...readSessionTranscriptHistoryEventPageFromProjection(e,{offset:0,maxMessages:t.maxMessages,maxBytes:Math.min(t.maxBytes??8388608,V),captureReadWindow:!0}),windowReset:!0,found:!0,hasOverreadContext:!1,offset:0};if(!r||a===void 0){let a=r&&readHistoricalHistoryAnchorPage(e,n.displaySource,r,t);return a?{...a,...i?{windowReset:!0}:{},...t.captureReadWindow?{readWindow:captureHistoryReadWindow(n,[])}:{}}:{events:[],found:!1,hasOverreadContext:!1,offset:0,displaySource:n.displaySource,totalMessages:n.total}}let o=H(n.total,a-1,t),s=Math.min(t.maxBytes??8388608,V),c=resolveVisibleHistoryRange(n,o.readStart,o.endExclusive),l=/* @__PURE__ */ new Map,u=c.boundedStart;for(let t of I(e,c.messageStart,c.messageEnd,`asc`)){for(;c.boundaries.has(u);)u++;l.set(u++,t.serialized_bytes)}let{start:d,endExclusive:f}=W(o,a-1,Math.max(1024,s),e=>c.boundaries.get(e)?.serializedBytes??l.get(e)??0,t.maxBytes===void 0),p=readVisibleHistoryRange(e,d,f,n);return{events:p,...i?{windowReset:!0}:{},...i||t.captureReadWindow?{readWindow:captureHistoryReadWindow(n,p)}:{},found:!0,hasOverreadContext:o.hasOverreadContext&&d===o.readStart,offset:n.total-f,displaySource:n.displaySource,totalMessages:n.total}}export{readTranscriptDisplaySource as _,readSessionTranscriptHistoryEventPageFromProjection as a,buildVisibleHistoryProjection as c,resolveVisibleHistoryEventCount as d,resolveVisibleHistoryProjection as f,positionTranscriptDisplayEvents as g,parseStoredTranscriptEvent as h,readSessionTranscriptHistoryEventLookupFromProjection as i,readActiveTranscriptCoordinate as l,isVisibleHistoryNonMessageEventSql as m,readSessionTranscriptHistoryAnchorPageFromProjection as n,readTranscriptDisplayDeltaFromProjection as o,resolveVisibleHistoryRange as p,readSessionTranscriptHistoryEventByIdFromProjection as r,X as s,readRecentSessionTranscriptHistoryEventsFromProjection as t,resolveHistoryMessageSequence as u};