openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
6 lines • 27.6 kB
JavaScript
import{i as e}from"./transcript-record-coerce-CPLgmAk9.mjs";import{w as t}from"./transcript-redact-BJEzMNLa.mjs";import{p as n}from"./transcript-number-coercion-D2B2TTt-.mjs";import{d as r,u as i}from"./transcript-sqlite-post-commit-B_pko32i.mjs";import{u as a}from"./transcript-kysely-sync-cache-state-DHCXK7mb.mjs";import{c as o}from"./transcript-sqlite-schema-facts-C1_zV4Yg.mjs";import{c as s,i as c,l,p as u,r as d,t as f,u as p}from"./transcript-kysely-sync-CAP5xe3V.mjs";import{r as m}from"./transcript-nested-tool-activity-DplsSnjy.mjs";import{t as h}from"./transcript-json-values-C_3KtpDU.mjs";import{d as g,i as _,l as v,n as y,o as b,p as x,r as S,s as C,u as w}from"./transcript-session-accessor.sqlite-reset-window-dONVogQj.mjs";import{t as T}from"./transcript-index-hint-B4mtmDR4.mjs";import{r as E}from"./transcript-internal-runtime-context-Blo7FWkI.mjs";import{d as D,m as O,p as k,u as A}from"./transcript-transcript-payload-F5t-l1WZ.mjs";import{r as j}from"./transcript-session-transcript-read-bytes-DJiUSe6g.mjs";import{n as M}from"./transcript-transcript-visible-record-BPnefnPg.mjs";import{n as N,t as P}from"./transcript-session-transcript-read-fence-Fb_G9Rx1.mjs";import{i as F}from"./transcript-session-accessor.sqlite-visible-cursor-CP4ccuQd.mjs";import{a as I,s as L,t as R}from"./transcript-session-accessor.sqlite-projection-read-B2CcfDOt.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-CsVwM-rX.mjs";import{t as V}from"./transcript-session-transcript-source-pages-BOCIi65D.mjs";import{n as H,r as U,t as W}from"./transcript-transcript-anchor-page-BS85ds7I.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-J5TnrySj.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(t,n,r,i=t.state.indexedSeq){if(!n||r.length===0)return r;let a=r.map(({event:t})=>m(e(t)?.message)?.details),o=[...new Set(a.flatMap(e=>e?.afterEntryId??[]))],s=/* @__PURE__ */ new Map,c=N({database:t.database,...t.resolved})?.beforeRawSeq,l=Math.min(i,c===void 0?1/0:c-1);if(o.length>0){let e=d(t.database.db,R(t.database).selectFrom(u`${p(o)}`.as(`requested`)).crossJoin(`transcript_event_identities as identity`).select([`identity.event_id`,`identity.seq`]).where(`identity.session_id`,`=`,t.resolved.sessionId).whereRef(`identity.event_id`,`=`,`requested.value`).where(`identity.seq`,`<=`,l)).rows;for(let t of e)s.set(t.event_id,t.seq)}if(t.hasUnindexedPrefix){let e=new Set(o.filter(e=>!s.has(e)));if(e.size>0)for(let n of x(t,{eventIds:[...e],maxRawSeq:l})){let t=typeof n.event.id==`string`?n.event.id.trim():void 0;t!==void 0&&e.has(t)&&s.set(t,n.event_seq)}}return r.map((e,t)=>({...e,displayPosition:K(n,e.eventSeq,a[t],e=>s.get(e))}))}function selectActiveResetRows(e){return R(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}:c(e.database.db,selectActiveResetRows(e).where(`active.active_position`,`>`,t.activePosition).orderBy(`active.active_position`,`asc`).limit(1)),r=b(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=c(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 u`(${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} != ${E}))
ELSE FALSE END)`}function historyNavigationValidSql(e){return u`CASE WHEN identity.event_type = 'custom_message'
THEN ${A(e,`navigation_valid`,`event`)} ELSE 1 END`}function parseStoredTranscriptEvent(e){return JSON.parse(e)}function selectHistoricalDisplayEvents(e,t){let n=R(e.database).selectFrom(`session_transcript_active_events as active`),r=R(e.database).selectFrom(`transcript_event_identities`).select([`session_id`,`seq`,`event_type`]).modifyEnd(T(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=b(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`),A(e.database.db,`navigation_display`,`event`),A(e.database.db,`navigation_custom_type`,`event`),A(e.database.db,`navigation_valid`,`event`)),...a.length>0?[t(`active.event_seq`,`in`,u`(SELECT CAST(value AS BIGINT) FROM ${h(e.database.db,u.val(JSON.stringify(a)))})`)]:[]]))}function selectDisplayableActiveEventById(e,t){return L(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`),A(e.database.db,`navigation_display`,`event`),A(e.database.db,`navigation_custom_type`,`event`),A(e.database.db,`navigation_valid`,`event`))]))}function readDisplayableActiveEventById(e,t,n){let r=R(e.database),i=c(e.database.db,selectDisplayableActiveEventById(e,t).select(t=>n===void 0?O(e.database.db,`event`).as(`event_json`):t.case().when(t(j(`event`),`<=`,n)).then(O(e.database.db,`event`)).else(null).end().as(`event_json`)));if(D(i?.navigation_valid),i)return i.event_json===null?void 0:{...i,event_json:i.event_json};let a=g(e,t);if(!a||a.message_position===null&&!q(a.event)||n!==void 0&&a.serialized_bytes-1>n)return;let o=c(e.database.db,r.selectFrom(`transcript_events`).select(O(e.database.db).as(`event_json`)).where(`session_id`,`=`,e.resolved.sessionId).where(`seq`,`=`,a.event_seq));return o?{event_seq:a.event_seq,active_position:a.active_position,message_position:a.message_position,event_type:typeof a.event.type==`string`?a.event.type:null,event_json:o.event_json}:void 0}function readDisplayableActiveEventMetadataById(e,t){let n=c(e.database.db,selectDisplayableActiveEventById(e,t));if(D(n?.navigation_valid),n)return n;let r=g(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=c(e.database.db,r);return D(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(j(`event`),`+`,1).as(`serialized_bytes`)]),l=Math.max(0,a.displayPosition-r),u=l===0?[]:d(e.database.db,c.where(`active.active_position`,`<`,a.activePosition).orderBy(`active.active_position`,`desc`).limit(l)).rows,f=d(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(),...f].map((e,t)=>(D(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 _=d(e.database.db,R(e.database).selectFrom(`transcript_events`).select([`seq`,O(e.database.db).as(`event_json`)]).where(`session_id`,`=`,e.resolved.sessionId).where(`seq`,`in`,g.map(e=>e.event_seq))).rows,v=new Map(_.map(e=>[e.seq,e.event_json]));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=c(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`)]));D(o?.navigation_valid??void 0);let s=o?.before_anchor??0,l=i?s:o?.total??0,u=H(l,i?l-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:l-(f.at(-1)?.seq??u.endExclusive),displaySource:t,totalMessages:l}}function resolveHistoryBoundaryQueryShape(e,t){if(t!==void 0)return`reset`;if(e.state.activeEventCount>=e.state.indexedSeq)return`markers`;let n=R(e.database);return c(e.database.db,n.selectFrom(n.selectFrom(`transcript_event_identities`).select([`session_id`,`event_type`,`seq`]).modifyEnd(T(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=R(e),a=i.selectFrom(`transcript_event_identities`).select([`session_id`,`event_id`,`seq`,`event_type`]).modifyEnd(T(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`),A(e.db,`navigation_display`,`event`),A(e.db,`navigation_custom_type`,`event`),A(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=f(()=>/* @__PURE__ */ new Map);function getHistoryCountReader(e,t){let n=Y(e.db),r=n.get(t);return r||(r=l(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=w(e),n=resolveHistoryBoundaryQueryShape(e,t.boundaryActivePosition),r=getHistoryCountReader(e.database,n)({sessionId:e.resolved.sessionId,boundaryActivePosition:t.boundaryActivePosition??0});D(r?.navigation_valid??void 0);let i=b(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=w(e),r=v(e)?.boundarySeq??null,i=R(e.database),a=d(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`),u`${j(`event`)} + 1`.as(`serialized_bytes`)]).orderBy(`active.active_position`,`asc`)).rows;for(let e of a)D(e.navigation_valid);for(let t of b(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=s(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)),c,l=!1,f=a.map((t,r)=>{let i=t.following_message_position;i===null&&((!l||c&&c.active_position<t.active_position)&&(c=o(t.active_position).rows[0],l=!0),i=c?.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:f,boundariesById:new Map(f.map(e=>[e.eventId,e])),boundariesBySeq:new Map(f.map(e=>[e.eventSeq,e])),displaySource:t,latestResetRawSeq:r,total:n.total+f.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(w(e),t,i);return o===r.seq&&n.latestResetRawSeq===t.latestResetRawSeq?void 0:{anchorSeq:o}}function readActiveTranscriptCoordinate(e,t){let n=R(e.database).selectFrom(`session_transcript_active_events`).select([`event_seq`,`message_position`,`active_position`]).where(`session_id`,`=`,e.resolved.sessionId);return c(e.database.db,`eventSeq`in t?n.where(`event_seq`,`=`,t.eventSeq):n.where(`active_position`,`=`,t.activePosition))}const X={pressure:J(`openclaw.memory.critical`),windows:/* @__PURE__ */ new Map};X.pressure.subscribe(()=>X.windows.clear());const Z=/* @__PURE__ */ new WeakSet;function retainHistoryWindowOwner(e){Z.has(e)||(a(r(e),()=>{for(let[t,n]of X.windows)n.database===e&&X.windows.delete(t)}),Z.add(e))}function readBoundaryEvents(e,t){let n=Array.from(t,e=>e.eventSeq);return n.length===0?/* @__PURE__ */ new Map:new Map(I(e,n).map(e=>[e.seq,parseStoredTranscriptEvent(k(e))]))}function readVisibleHistoryRange(e,t,n,r){let i=resolveVisibleHistoryRange(r,t,n);if(i.boundedEnd<=i.boundedStart)return[];let a=C(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=S(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(`Transcript 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(w(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=w(e),a=n.events[0].seq,o=n.events.at(-1).seq,s=R(e.database),c=new Map(d(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:F}),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,n){let read=t=>readRecentHistoryInSnapshot(e,resolveVisibleHistoryProjection(e),n,t);if(!e.generation||o(e.database.db)||i(e.database.db)||e.database.db.location()===null||n.expectedReadWindow||P(e.resolved))return read();let r=JSON.stringify([e.database.path,e.resolved.agentId,e.resolved.sessionId]),a=JSON.stringify([e.generation,e.state.indexedSeq,e.version.updatedAt,n.maxMessages,n.maxLines,n.maxBytes,!!n.captureReadWindow]),s=X.windows.get(r);return s?.database===e.database.db&&s.revision===a?structuredClone(s.page):(X.windows.delete(r),read((n,i)=>{if(!(i>1048576))try{let i=e.database.db;retainHistoryWindowOwner(i),X.windows.set(r,{database:i,revision:a,page:structuredClone(n)}),t(X.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()||y(e,r.messageStart,r.messageEnd)){let t=readVisibleHistoryRange(e,0,n.total,n);return{events:t,hasDisplayMessages:t.some(e=>M(e.event))}}let i=readBoundaryEvents(e,r.boundaries.values()),a,o=!1;for(let t of mergeVisibleHistoryEvents(r,_(e,r.messageStart,r.messageEnd),i))if(a??=t,M(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 S(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{readSessionTranscriptHistoryEventPageFromProjection as a,readActiveTranscriptCoordinate as c,resolveVisibleHistoryProjection as d,resolveVisibleHistoryRange as f,readTranscriptDisplaySource as g,positionTranscriptDisplayEvents as h,readSessionTranscriptHistoryEventLookupFromProjection as i,resolveHistoryMessageSequence as l,parseStoredTranscriptEvent as m,readSessionTranscriptHistoryAnchorPageFromProjection as n,readTranscriptDisplayDeltaFromProjection as o,isVisibleHistoryNonMessageEventSql as p,readSessionTranscriptHistoryEventByIdFromProjection as r,buildVisibleHistoryProjection as s,readRecentSessionTranscriptHistoryEventsFromProjection as t,resolveVisibleHistoryEventCount as u};