UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1 lines • 33.9 kB
import{M as e}from"./transcript-chat-message-content-Cx-VPFHv.mjs";import{i as t,o as n}from"./transcript-record-coerce-eN4p5mcq.mjs";import{t as r}from"./transcript-errno-CsW5NI8i.mjs";import{u as i}from"./transcript-string-coerce-BxRUqIXb.mjs";import{s as a}from"./transcript-string-readers-D1-IC7yv.mjs";import{t as o}from"./transcript-json-coercion-FJNyjMmt.mjs";import{g as s,h as c}from"./transcript-number-coercion-Dr06QpMa.mjs";import{t as l}from"./transcript-map-size-DkeBKk4z.mjs";import"./transcript-path-existence-DsAt-_G2.mjs";import{n as u,t as d}from"./transcript-session-transcript-projection-error-BeJK3y26.mjs";import"./transcript-boundary-path-CPtHZQz7.mjs";import{r as f}from"./transcript-artifacts-BzUw22qv.mjs";import{i as p,r as m}from"./transcript-paths-EL7FYwW9.mjs";import{r as h}from"./transcript-kysely-sync-DQ_Yn8jW.mjs";import"./transcript-runtime-process-url-BahjIwf7.mjs";import"./transcript-worker-task-pool-xHbAfEur.mjs";import{i as g}from"./transcript-nested-tool-activity-nGNS0H_L.mjs";import"./transcript-transcript-events-CeN2k8Gr.mjs";import"./transcript-transcript-payload-C58U6XNI.mjs";import{n as ee}from"./transcript-transcript-payload-read-BfcV5CyI.mjs";import{c as _}from"./transcript-transcript-tree-BBaX4q0_.mjs";import{r as v}from"./transcript-session-transcript-read-bytes-C7AU5F9V.mjs";import{n as y}from"./transcript-transcript-visible-record-sz9xHogO.mjs";import{n as b}from"./transcript-json-utf8-bytes-C2npPbGW.mjs";import{f as x,i as S,n as C,o as w,p as T}from"./transcript-chat-display-projection.core-CazZ-wgQ.mjs";import{i as E,r as D,t as O}from"./transcript-archive-compression-CfnyO0vG.mjs";import{o as te,t as k}from"./transcript-session-accessor.sqlite-projection-read-HIelFCp6.mjs";import{i as ne,l as A,u as j}from"./transcript-session-accessor.sqlite-reset-window-CJLYEFaR.mjs";import{n as M}from"./transcript-session-accessor.sqlite-active-events-read-33K9npQ5.mjs";import{n as N,t as re}from"./transcript-session-transcript-source-pages-4In3PTCc.mjs";import{n as ie,r as ae,t as oe}from"./transcript-transcript-anchor-page-CrBoJln6.mjs";import{n as se,t as ce}from"./transcript-transcript-display-position-CeSwa-oH.mjs";import{_ as P,a as F,d as I,g as L,h as R,i as z,l as B,n as V,o as H,r as U,t as W}from"./transcript-session-accessor.sqlite-history-query-C43twHr3.mjs";import{t as le}from"./transcript-session-history-visibility-VnlSe8OR.mjs";import{t as G}from"./transcript-payload-limits-DETN1Ggi.mjs";import{i as K,s as ue}from"./transcript-session-history-tail-IGkPqW3K.mjs";import{i as q,n as J}from"./transcript-session-transcript-entry-message-Cmvv9REf.mjs";import{t as de}from"./transcript-transcript-recent-text-2p2pOyiK.mjs";import Y from"node:path";import X from"node:fs";import"@openclaw/fs-safe/config";function readSessionTranscriptSourcePageFromProjection(e,t){if(t.cursor?.kind===`archive`)throw Error(`Archive source cursors require the archive reader`);let r=k(e.database),i=e.resolved.sessionId,a=A(e),o=t.cursor?.snapshot.activeEventCount??e.state.activeEventCount,s=B(e,{activePosition:o-1}),c=t.cursor?.snapshot??{indexedSeq:e.state.indexedSeq,activeEventCount:o,totalMessages:I(e),generation:e.generation,tailEventSeq:s?.event_seq,resetSeq:a?.boundarySeq??null};if(t.cursor&&(c.generation!==e.generation||c.indexedSeq>e.state.indexedSeq||c.tailEventSeq!==s?.event_seq||c.resetSeq!==(a?.boundarySeq??null)))throw new d(i,`window-changed`);if(!t.cursor&&c.totalMessages===0)return{events:[],snapshot:c,nextCursor:t.includeOffPathMessages?{kind:`off-path`,position:-1,messageSeq:0,snapshot:c}:void 0};let l=a?.keptMessagePositions??[],u=t.messageIds?.map(e=>e.trim()),f=u?r.selectFrom(`transcript_event_identities`).select(`seq`).where(`session_id`,`=`,i).where(`event_id`,`in`,u):void 0,p=t.cursor??{kind:l.length>0?`kept`:`active`,position:l.length>0?0:a?.boundaryActivePosition??0,messageSeq:0,snapshot:c},m=[],g=[],_=0,y=0;for(;p&&_<128;){let o=p.kind,s=128-_,d=o===`kept`?l.slice(p.position,p.position+s):[],b=r.selectFrom(`session_transcript_active_events as active`).crossJoin(`transcript_events as event`).whereRef(`event.session_id`,`=`,`active.session_id`).whereRef(`event.seq`,`=`,`active.event_seq`).select([`event.seq`,`active.active_position as position`,`active.message_position`,v(`event`).as(`bytes`)]).where(`active.session_id`,`=`,i),x=o===`off-path`?r.selectFrom(`transcript_events as event`).select([`event.seq`,`event.seq as position`,e=>e.val(null).as(`message_position`),v(`event`).as(`bytes`)]).where(`event.session_id`,`=`,i).where(`event.seq`,`>`,p.position).where(`event.seq`,`<=`,c.indexedSeq).where(e=>e.not(e.exists(e.selectFrom(`session_transcript_active_events as active`).select(`active.event_seq`).whereRef(`active.session_id`,`=`,`event.session_id`).whereRef(`active.event_seq`,`=`,`event.seq`).where(`active.active_position`,`<`,c.activeEventCount)))).orderBy(`event.seq`,`asc`):o===`kept`?b.where(`active.message_position`,`in`,d).orderBy(`active.message_position`,`asc`):b.where(`active.active_position`,`>=`,p.position).where(`active.active_position`,`<`,c.activeEventCount).orderBy(`active.active_position`,`asc`),S=f?x.where(e=>e.or([e(`event.seq`,`in`,f),e.not(e.exists(e.selectFrom(`transcript_event_identities as identity`).select(`identity.seq`).whereRef(`identity.session_id`,`=`,`event.session_id`).whereRef(`identity.seq`,`=`,`event.seq`)))])):x,C=u?.length===0||o===`kept`&&d.length===0?[]:h(e.database.db,S.limit(s)).rows,w=0;for(let e of C){if(e.bytes+1>8388608)throw new N;if(y+e.bytes+1>8388608)break;y+=e.bytes+1,w++}let T=C.slice(0,w),E=new Map(T.length===0?[]:te(e,T.map(e=>e.seq)).map(e=>[e.seq,R(ee(e))])),D=p.messageSeq;for(let e of T){let t=E.get(e.seq);if(o===`off-path`||e.message_position!==null||n(t)&&le(t)){let n={event:t,eventSeq:e.seq,seq:o===`off-path`?e.seq+1:++D};(o===`off-path`?g:m).push(n)}}_+=w;let O=T.at(-1),k=o===`kept`?p.position+(w<C.length?d.indexOf(C[w].message_position):d.length):O?O.position+(o===`off-path`?0:1):p.position;if(p={kind:o,position:k,messageSeq:D,snapshot:c},w<C.length)break;o===`kept`&&k>=l.length?p={kind:`active`,position:a?.boundaryActivePosition??0,snapshot:c,messageSeq:D}:o===`active`&&(C.length<s||k>=c.activeEventCount)?p=t.includeOffPathMessages?{kind:`off-path`,position:-1,snapshot:c,messageSeq:D}:void 0:o===`off-path`&&C.length<s&&(p=void 0)}return{events:[...L(e,P(e),m,c.indexedSeq),...g],snapshot:c,...p?{nextCursor:p}:{}}}function extractGeneratedTranscriptSessionId(e){let t=e?.trim();if(!t)return;let n=Y.basename(t);if(!n.endsWith(`.jsonl`))return;let r=n.slice(0,-6),i=r.indexOf(`-topic-`);if(i>0){let e=r.slice(0,i);return looksLikeGeneratedSessionId(e)?e:void 0}let a=r.match(/^(\d{4}-\d{2}-\d{2}T[\w-]+(?:Z|[+-]\d{2}(?:-\d{2})?)?)_(.+)$/);return a?.[2]?looksLikeGeneratedSessionId(a[2])?a[2]:void 0:looksLikeGeneratedSessionId(r)?r:void 0}function looksLikeGeneratedSessionId(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}const Z=/* @__PURE__ */ new Map;function planSessionTranscriptCandidates(e,t,n,r){let i=[],a=extractGeneratedTranscriptSessionId(n),o=!!(a&&a!==e);if(t){let e=m(t);n&&!o&&i.push({sessionsDir:e,agentId:r,sessionFile:n}),i.push({sessionsDir:e}),n&&o&&i.push({sessionsDir:e,agentId:r,sessionFile:n})}else n&&(r?o||i.push({agentId:r,sessionFile:n}):n.trim()&&i.push(Y.resolve(n.trim())));return r&&(i.push({agentId:r}),n&&o&&i.push({agentId:r,sessionFile:n})),i}function resolveSessionTranscriptCandidates(e,t,n,r){let i=[];for(let a of planSessionTranscriptCandidates(e,t,n,r))try{i.push(typeof a==`string`?a:p(e,a,a))}catch{}return a(i)}async function resetArchiveHeaderMatchesSessionId(e,t){try{let r=(await E(t,65536)).toString(`utf-8`).split(/\r?\n/);for(let t of r){let r=t.trim();if(!r)continue;let i=JSON.parse(r);return n(i)&&i.type===`session`&&i.id===e}return!1}catch(e){if(r(e,`ERR_BUFFER_TOO_LARGE`))throw e;return!1}}async function listResetArchiveCandidatesForTranscriptAsync(e){let t=Y.basename(e);if(!t.endsWith(`.jsonl`))return;let n=Y.dirname(e),r=await X.promises.stat(n).catch(()=>null);if(!r?.isDirectory())return;let i=`${n}\0${t}`,a=Z.get(i);if(a&&a.dirMtimeMs===r.mtimeMs&&a.dirSize===r.size)return Z.delete(i),Z.set(i,a),a.archives;let o=[];try{for(let e of await X.promises.readdir(n,{withFileTypes:!0})){if(!e.isFile()||!e.name.startsWith(`${t}.reset.`))continue;let r=f(e.name,`reset`);r!=null&&o.push({archivePath:Y.join(n,e.name),name:e.name,timestamp:r})}}catch{return}o.sort((e,t)=>t.timestamp-e.timestamp||t.name.localeCompare(e.name));let s=o.slice(0,128);return Z.set(i,{dirMtimeMs:r.mtimeMs,dirSize:r.size,archives:s}),l(Z,2048),s}async function resolveSessionTranscriptResetArchiveCandidatesAsync(e,t,n,r){let i=/* @__PURE__ */ new Map;for(let a of resolveSessionTranscriptCandidates(e,t,n,r)){let e=Y.basename(a),t=i.get(e)??[];t.push(a),i.set(e,t)}let o=(await Promise.all(Array.from(i.values(),async t=>(await Promise.all(t.map(async t=>{let n=await listResetArchiveCandidatesForTranscriptAsync(t)??[];if(extractGeneratedTranscriptSessionId(t)===e)return n;let r=[];for(let t of n)await resetArchiveHeaderMatchesSessionId(e,t.archivePath)&&r.push(t);return r}))).flat().toSorted((e,t)=>t.timestamp-e.timestamp||t.name.localeCompare(e.name))))).flat();return a(o.map(e=>e.archivePath))}const fe={id:/"id"\s*:\s*"((?:\\.|[^"\\])*)"/,parentId:/"parentId"\s*:\s*"((?:\\.|[^"\\])*)"/,type:/"type"\s*:\s*"((?:\\.|[^"\\])*)"/,timestamp:/"timestamp"\s*:\s*"((?:\\.|[^"\\])*)"/,role:/"role"\s*:\s*"((?:\\.|[^"\\])*)"/,idempotencyKey:/"idempotencyKey"\s*:\s*"((?:\\.|[^"\\])*)"/},pe=/"parentId"\s*:\s*null/,me=/"timestamp"\s*:\s*(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/;function extractJsonStringFieldPrefix(e,t){let n=fe[t].exec(e);if(n)return i(o(`"${n[1]}"`))}function extractJsonNumberFieldPrefix(e){let t=me.exec(e);if(!t)return;let n=Number(t[1]);return Number.isFinite(n)?n:void 0}function isJsonObjectFieldToken(e,t){for(let n=t-1;n>=0;n--){let t=e.charAt(n);if(!/\s/.test(t))return t===`{`||t===`,`}return!0}function extractJsonStringFieldSuffix(e,t){let n=JSON.stringify(t),r=Math.max(0,e.length-65536);for(;r<e.length;){let t=e.indexOf(n,r);if(t<0)return;if(r=t+n.length,!isJsonObjectFieldToken(e,t))continue;let a=/^\s*:\s*"((?:\\.|[^"\\])*)"/.exec(e.slice(r));if(a)return i(o(`"${a[1]}"`))}}function recoverOversizedMultimodalTranscriptRecord(e,r){let i=`__openclaw_omitted_image_`;if(e.includes(i))return;let a=[],o=/"data"\s*:\s*"/g,s=0;for(let t=o.exec(e);t;t=o.exec(e)){if(!isJsonObjectFieldToken(e,t.index))continue;if(++s>32)return;let n=t.index+t[0].length,r=n,c=0,l=!0;for(;r<e.length&&e.charCodeAt(r)!==34;r++){let t=e.charCodeAt(r);t===92?(l=!1,r++):l&&(t===61?++c>2&&(l=!1):(c>0||((t|32)<97||(t|32)>122)&&(t<48||t>57)&&t!==43&&t!==47)&&(l=!1))}if(r>=e.length)return;o.lastIndex=r+1,l&&(r-n)%4==0&&a.push({start:n,end:r,marker:`${i}${a.length}__`,bytes:(r-n)*3/4-c})}if(a.length!==0)try{let parseBoundedRedaction=t=>{let a=t.reduce((e,t)=>e-(t.end-t.start-t.marker.length),r);if(t.length===0||a>262144)return;let o=0,s=[];for(let n of t)s.push(e.slice(o,n.start),n.marker),o=n.end;s.push(e.slice(o));let c=new Set(t.map(e=>e.marker)),l=JSON.parse(s.join(``),(e,t)=>{if(typeof t==`string`&&t.startsWith(i)&&!c.delete(t))throw Error(`invalid transcript image recovery marker`);return t});if(!(c.size>0||!n(l)))return l},imageDataOwners=e=>{let n=t(e.source);return n?.type===`base64`?[e,n]:[e]},o=parseBoundedRedaction(a),s=t(o?.message)?.content;if(!Array.isArray(s))return;let c=new Map(a.map(e=>[e.marker,e])),l=/* @__PURE__ */ new Set;for(let e of s)if(n(e)&&e.type===`image`){for(let t of imageDataOwners(e))if(typeof t.data==`string`){if(!c.has(t.data)||l.has(t.data))return;l.add(t.data)}}if(l.size===0)return;let u=a.filter(e=>l.has(e.marker)),d=parseBoundedRedaction(u),f=t(d?.message)?.content;if(!d||!Array.isArray(f))return;let p=new Map(u.map(e=>[e.marker,e]));for(let e of f){if(!n(e)||e.type!==`image`)continue;let t;for(let n of imageDataOwners(e)){if(typeof n.data!=`string`)continue;let e=p.get(n.data);if(!e)return;p.delete(e.marker),t??=e.bytes,delete n.data}t!==void 0&&(e.omitted=!0,e.bytes=t)}return p.size===0&&b(d)<=262144?d:void 0}catch{return}}function parseTranscriptRecord(e){let t=Buffer.byteLength(e,`utf8`),r=t>262144,a=r?recoverOversizedMultimodalTranscriptRecord(e,t):void 0;if(!r||a)try{let r=a??JSON.parse(e);if(!n(r))return null;let o=i(r.id);return{byteLength:t,...o?{id:o}:{},...a?{recoveredImageData:!0}:{},record:r}}catch{return null}let o=e.slice(0,65536),s=/"message"\s*:/.exec(o),c=s?o.slice(0,s.index):o,l=extractJsonStringFieldPrefix(o,`id`),u=pe.test(o)?null:extractJsonStringFieldPrefix(o,`parentId`),d=extractJsonStringFieldPrefix(o,`type`),f=extractJsonStringFieldPrefix(c,`timestamp`)??extractJsonNumberFieldPrefix(c),p=extractJsonStringFieldPrefix(o,`role`)??`assistant`,m=extractJsonStringFieldPrefix(o,`idempotencyKey`)??extractJsonStringFieldSuffix(e,`idempotencyKey`),h={...d?{type:d}:{},...l?{id:l}:{},...u===void 0?{}:{parentId:u},...f===void 0?{}:{timestamp:f},message:{role:p,...m?{idempotencyKey:m}:{},content:[{type:`text`,text:`[chat.history omitted: message too large]`}],__openclaw:{truncated:!0,reason:`oversized`}}};return{byteLength:t,...l?{id:l}:{},record:h}}const Q=/* @__PURE__ */ new Map,$=65536;function transcriptArtifactDisplaySource(e,t){let n=`${t.dev}:${t.ino}:${t.ctimeMs}:${t.mtimeMs}:${t.size}`;return se([`archive`,e,n])}function assertArchiveTranscriptSource(e,t,n,r){if(transcriptArtifactDisplaySource(e,t)!==n)throw new d(r)}function selectArchiveTranscriptEntries(e,n=!1){let r=_({entries:e,recordOf:e=>e.record,failClosedOnInvalidLeafControl:n}),i=r.findLastIndex(({record:e})=>e.type===`compaction`||e.type===`reset`);if(i<0||r[i]?.record.type!==`reset`)return r;let a=r[i]?.record.firstKeptEntryId,o=typeof a==`string`?r.findIndex((e,t)=>t<i&&e.id===a):-1;return[...o<0?[]:r.slice(o,i).filter(({record:e})=>{let n=t(e.message)?.role;return n===`user`||n===`assistant`}),...r.slice(i)]}function archiveNavigationRecord(e){let n={};for(let t of[`id`,`type`,`parentId`,`targetId`,`appendParentId`,`appendMode`,`firstKeptEntryId`])if(Object.hasOwn(e,t)){let r=e[t];n[t]=typeof r==`string`||r===null?r:!1}let r=t(e.message)?.role;return n.message=e.message?{role:r===`user`||r===`assistant`?r:void 0}:!1,e.type===`custom_message`&&(n.display=e.display===!0,n.customType=e.customType),n}function appendArchiveNavigationRecord(e){let t=Buffer.concat(e.fragments,e.length).toString(`utf8`),n=t.trim()?parseTranscriptRecord(t):null;if(!n)return;let r=e.records.length+1,i=g(n.record.message)?.details;e.records.push({...n,record:archiveNavigationRecord(n.record),rawSeq:r,offset:e.lineOffset,length:e.length,...i?{activity:{afterEntryId:i.afterEntryId,scopeId:i.scopeId,startOrder:i.startOrder}}:{}}),n.id&&e.rawSeqById.set(n.id,r)}function finishSessionTranscriptIndex({records:e,rawSeqById:t},n,r){let i=selectArchiveTranscriptEntries(e).filter(e=>y(e.record)).map((e,r)=>({id:e.id,rawId:typeof e.record.id==`string`?e.record.id:void 0,offset:e.offset,length:e.length,seq:r+1,transcriptPosition:ce(n,e.rawSeq,e.activity,e=>t.get(e))}));return{byteSize:r,entries:i,byId:new Map(i.flatMap(e=>e.id?[[e.id,e]]:[])),displaySource:n}}function assertSourceLineBound(e){if(e>8388608)throw new N}async function prepareTranscriptIndexStep(e,t,n,r){let i=t.preparation,a=await D(e);try{assertArchiveTranscriptSource(e,await a.stat(),t.identity,n);let o=r?i.length:0,s=0,c=r?128:1/0;scan:for(;i.offset<t.size&&s<c;){let l=r?re-o:$;if(l<=0&&(!r||i.length<8388608))break;let u=Math.min($,Math.max(1,l),t.size-i.offset),f=Buffer.allocUnsafe(u),p=await a.read(f,i.offset);if(p!==u){if(!e.endsWith(`.zst`))throw new d(n);t.size=i.offset+p,f=f.subarray(0,p)}o+=u;let m=0;for(i.afterCr&&=(f[0]===10&&(m++,i.offset++,i.lineOffset++),!1);m<f.length&&s<c;){let e=f.indexOf(10,m),n=f.indexOf(13,m),a=e<0?n:n<0?e:Math.min(e,n),o=a<0?f.length:a,c=f.subarray(m,o);if(t.largestLine=Math.max(t.largestLine,i.length+c.length),r&&t.largestLine>8388608)break scan;if(i.fragments.push(c),i.length+=c.length,i.offset+=c.length,a<0)break;appendArchiveNavigationRecord(i),s++,i.fragments=[],i.length=0,i.offset++,m=a+1,i.afterCr=f[a]===13,i.afterCr&&m<f.length&&(f[m]===10&&(m++,i.offset++),i.afterCr=!1),i.lineOffset=i.offset}}i.offset===t.size&&(i.length>0&&appendArchiveNavigationRecord(i),t.value=finishSessionTranscriptIndex(i,t.identity,t.size),t.preparation=void 0),assertArchiveTranscriptSource(e,await a.stat(),t.identity,n)}finally{await a.close()}}function advanceTranscriptIndex(e,t,n,r){return t.pending??=prepareTranscriptIndexStep(e,t,n,r).catch(n=>{throw Q.get(e)===t&&Q.delete(e),n}).finally(()=>{t.pending=void 0})}async function readIndexedTranscriptEntries(e,t,n,r){let i=await D(e);try{assertArchiveTranscriptSource(e,await i.stat(),t.displaySource,r);let a=n.map((e,t)=>({entry:e,order:t})).toSorted((e,t)=>e.entry.offset-t.entry.offset),o=[];for(let e=0;e<a.length;){let t=a[e].entry,n=e+1,s=t.offset+t.length;for(;n<a.length;){let e=a[n].entry;if(e.offset+e.length-t.offset>1048576)break;s=Math.max(s,e.offset+e.length),n++}let c=Buffer.allocUnsafe(s-t.offset);if(await i.read(c,t.offset)!==c.length)throw new d(r);for(let i=e;i<n;i++){let{entry:e,order:n}=a[i],s=e.offset-t.offset,l=parseTranscriptRecord(c.toString(`utf8`,s,s+e.length));if(!l)throw new d(r);o[n]={...e,...l}}e=n}return assertArchiveTranscriptSource(e,await i.stat(),t.displaySource,r),o}finally{await i.close()}}async function acquireTranscriptIndex(e){let t=await X.promises.stat(e).catch(()=>null);if(!t?.isFile())return Q.delete(e),null;let n=transcriptArtifactDisplaySource(e,t),r=Q.get(e);return r?.identity!==n&&(r={identity:n,size:e.endsWith(`.zst`)?1/0:t.size,largestLine:0,preparation:{offset:0,lineOffset:0,length:0,afterCr:!1,fragments:[],records:[],rawSeqById:/* @__PURE__ */ new Map}}),Q.delete(e),Q.set(e,r),l(Q,256),r}async function prepareSessionTranscriptIndex(e,t,n=!1){let r=await acquireTranscriptIndex(e);if(!r)return null;try{return assertSourceLineBound(r.largestLine),r.pending||n?{displaySource:r.identity}:r.value?{displaySource:r.identity,index:r.value}:(await advanceTranscriptIndex(e,r,t,!0),assertSourceLineBound(r.largestLine),{displaySource:r.identity})}catch(t){throw!r.value&&!r.pending&&Q.get(e)===r&&Q.delete(e),t}}async function readSessionTranscriptIndex(e,t){let n=await acquireTranscriptIndex(e);if(!n)return null;for(;!n.value||n.pending;)await advanceTranscriptIndex(e,n,t,!1);return n.value}var he=/* @__PURE__ */ e({ArchivedTranscriptReader:()=>ArchivedTranscriptReader});function normalizeRecentSessionReadOptions(e){let t=s(e?.maxMessages,0);return{maxMessages:t,maxBytes:c(e?.maxBytes,8388608,{min:1024}),maxLines:c(e?.maxLines,t*20+20,{min:t})}}async function readRecentSessionSnapshotFromPathAsync(e,t,n,r){if(t.maxMessages===0)return{messages:[],transcriptEvents:[]};let{maxBytes:i,maxLines:a}=t,o=await D(e),s;try{assertArchiveTranscriptSource(e,await o.stat(),n.displaySource,r);let t=Math.min(n.byteSize,i),c=Math.max(0,n.byteSize-t),l=Buffer.alloc(t),u=await o.read(l,c);if(assertArchiveTranscriptSource(e,await o.stat(),n.displaySource,r),u<=0)return{messages:[],transcriptEvents:[]};s=l.toString(`utf-8`,0,u).split(/\r?\n/).slice(+(c>0)).filter(e=>e.trim().length>0).slice(-a)}finally{await o.close()}return parseRecentTranscriptTailSnapshot(s,t.maxMessages,n)}function parseRecentTranscriptTailSnapshot(e,t,n){let r=selectArchiveTranscriptEntries(e.flatMap(e=>{let t=parseTranscriptRecord(e);return t?[t]:[]}),!0),i=r.filter(e=>y(e.record)).slice(-t),a=Math.max(1,n.entries.length-i.length+1);return{messages:i.flatMap((e,t)=>{let r=e.id?n.byId.get(e.id):void 0,i=J(e.record,r?.seq??a+t,r?.transcriptPosition);return i?[i]:[]}),transcriptEvents:r.map(e=>e.record)}}var ArchivedTranscriptReader=class{constructor(e){this.scope=e}async resolvePaths(){return this.scope.exactArchivePath?[this.scope.exactArchivePath]:resolveSessionTranscriptResetArchiveCandidatesAsync(this.scope.sessionId,this.scope.storePath,this.scope.sessionFile,this.scope.agentId)}async resolvePath(e){let t=await this.resolvePaths();for(let n of t.slice(e?t.indexOf(e)+1:0))if((await X.promises.stat(n).catch(()=>null))?.isFile())return n;return null}canTryOlderArchive(e){return!this.scope.exactArchivePath&&O(e)&&!r(e,`ERR_BUFFER_TOO_LARGE`)}async*readableIndexes(){for(let e of await this.resolvePaths())try{let t=await readSessionTranscriptIndex(e,this.scope.sessionId);t&&(yield{filePath:e,index:t})}catch(e){if(!this.canTryOlderArchive(e))throw e}}async resolveIndexedPath(){let e=await this.readableIndexes().next();return e.done?null:e.value}async readSourcePage(e,t){let n=e.cursor?.kind===`archive`?e.cursor:void 0,r=n?.path??await this.resolvePath(),i=e.includeOffPathMessages&&t.indexedSeq>=0?{kind:`off-path`,snapshot:t,position:-1,messageSeq:t.totalMessages}:void 0;if(!r)return{messages:[],nextCursor:i};let a=n?.position??0,o;try{o=await prepareSessionTranscriptIndex(r,this.scope.sessionId)}catch(e){if(!this.canTryOlderArchive(e))throw e;if(r=await this.resolvePath(r),!r)return{messages:[],nextCursor:i};o=await prepareSessionTranscriptIndex(r,this.scope.sessionId,!0),a=0}if(n&&r===n.path&&o?.displaySource!==n.source)throw Error(`Chat history archive changed during source pagination; retry the read`);if(o&&!o.index)return{messages:[],transcriptPath:r,nextCursor:{kind:`archive`,snapshot:t,position:a,messageSeq:0,path:r,source:o.displaySource}};let s=o?.index,c=e.messageIds&&new Set(e.messageIds),l=[],u=a,d=0;if(s)for(;u<s.entries.length&&l.length<128;){let e=s.entries[u];if(c&&(c.size===0||e.rawId!==void 0&&!c.has(e.rawId))){u++;continue}let t=e.length;if(d+t>8388608)break;d+=t,l.push(e),u++}return{messages:s?(await readIndexedTranscriptEntries(r,s,l,this.scope.sessionId)).flatMap(indexedTranscriptEntryToMessages):[],transcriptPath:r,nextCursor:s&&u<s.entries.length?{kind:`archive`,snapshot:t,position:u,messageSeq:0,path:r,source:s.displaySource}:i}}async readById(e,t){let n=await this.resolveIndexedPath();if(!n)return{oversized:!1,found:!1};let{filePath:r,index:i}=n,a=i.byId.get(e);if(!a)return{oversized:!1,found:!1};let[o]=await readIndexedTranscriptEntries(r,i,[a],this.scope.sessionId);if(!o)return{oversized:!1,found:!1};let s=o.byteLength>262144&&(o.recoveredImageData!==!0||b(o.record)>262144);if(s&&!t)return{oversized:!0,found:!0,seq:o.seq};let c=indexedTranscriptEntryToMessage(o),l=t&&T(c,t.sessionStartedAt)?i.entries[o.seq-2]:void 0,u=l?(await readIndexedTranscriptEntries(r,i,[l],this.scope.sessionId))[0]:void 0;return{message:c,seq:o.seq,oversized:s,found:!0,...t?{historyContext:{transcriptPath:r,displaySource:i.displaySource,...u?{precedingMessage:indexedTranscriptEntryToMessage(u)}:{}}}:{}}}async readMessageCandidatesById(e){let t=await this.resolveIndexedPath();if(!t)return[];let{filePath:n,index:r}=t;return(await readIndexedTranscriptEntries(n,r,r.entries.filter(t=>t.rawId===void 0||t.rawId===e),this.scope.sessionId)).flatMap(indexedTranscriptEntryToMessages)}async readRecentWithStats(e){let t=await this.resolveIndexedPath();if(!t)return{messages:[],totalMessages:0};let{filePath:n,index:r}=t,i=r.entries.length,a=await readRecentSessionSnapshotFromPathAsync(n,normalizeRecentSessionReadOptions(e),r,this.scope.sessionId);return{displaySource:r.displaySource,messages:a.messages,transcriptEvents:a.transcriptEvents,totalMessages:i,transcriptPath:n,transcriptSource:`reset-archive`}}async readPage(e){let t=await this.resolveIndexedPath();if(!t)return{messages:[],totalMessages:0};let{filePath:n,index:r}=t,i=r.entries.length,a=ae(i,e),o;if(e.recentAtHead&&a===i)o=await readRecentSessionSnapshotFromPathAsync(n,normalizeRecentSessionReadOptions(e.recentAtHead),r,this.scope.sessionId);else{let t=Math.max(0,a-s(e.maxMessages,0)),i=await readIndexedTranscriptEntries(n,r,r.entries.slice(t,a),this.scope.sessionId);o={messages:i.flatMap(indexedTranscriptEntryToMessages),transcriptEvents:i.map(e=>e.record)}}return{displaySource:r.displaySource,messages:o.messages,transcriptEvents:o.transcriptEvents,totalMessages:i,transcriptPath:n,transcriptSource:`reset-archive`}}async readAroundId(e){let t;for await(let{filePath:n,index:r}of this.readableIndexes()){t??=r.displaySource;let i=r.entries.findIndex(t=>t.id===e.messageId);if(i<0)continue;let a=ie(r.entries.length,i,e),o=await readIndexedTranscriptEntries(n,r,r.entries.slice(a.readStart,a.endExclusive),this.scope.sessionId);return{displaySource:r.displaySource,found:!0,hasOverreadContext:a.hasOverreadContext,messages:o.flatMap(indexedTranscriptEntryToMessages),offset:a.offset,totalMessages:r.entries.length,transcriptPath:n,transcriptSource:`reset-archive`}}return{displaySource:t,found:!1,hasOverreadContext:!1,messages:[],offset:0,totalMessages:0}}};function indexedTranscriptEntryToMessage(e){return J(e.record,e.seq,e.transcriptPosition)}function indexedTranscriptEntryToMessages(e){let t=indexedTranscriptEntryToMessage(e);return t?[t]:[]}async function prepareSessionTranscriptSummaryReader(e){if(e.kind===`mcp-app`){let{selectMcpAppReconstructionData:t}=await import(`./transcript-mcp-app-transcript-B-zaItGs.mjs`);return n=>({kind:`mcp-app`,data:t(n,e.lookup)})}let{createSessionTranscriptUsageAccumulator:t}=await import(`./transcript-session-transcript-derived-readers-CBFJMw0C.mjs`).then(e=>e.n);return e=>{let n=t();return e(n.add),{kind:`usage`,usage:n.finish()}}}function archivedTranscriptReader(e){return new ArchivedTranscriptReader({agentId:e.agentId,sessionId:e.sessionId,storePath:e.storePath})}function projectSqliteHistoryEvents(e){let t=[];for(let n of e){let e=q(n);e&&t.push(e)}return t}function capAnchorEventsByBytes(e,n){if(n.maxBytes===void 0)return e;let r=e.findIndex(({event:e})=>t(e)?.id===n.messageId),i=oe({readStart:0,endExclusive:e.length,hasOverreadContext:!1,offset:0},r>=0?r:n.direction===`newer`?0:e.length-1,Math.max(1024,Math.floor(n.maxBytes)),t=>b(e[t])+1);return e.slice(i.start,i.endExclusive)}function readRecentSqliteMessageRecords(e,t){let n=Math.max(0,Math.floor(t?.maxMessages??0)),r=W(e,{maxMessages:n,maxBytes:c(t?.maxBytes,8388608,{min:1024}),maxLines:c(t?.maxLines,n*20+20,{min:n}),captureReadWindow:t?.captureReadWindow,expectedReadWindow:t?.expectedReadWindow});return{...r.activeLeafEntryId===void 0?{}:{activeLeafEntryId:r.activeLeafEntryId},...r.deltaCursor?{deltaCursor:r.deltaCursor}:{},displaySource:r.displaySource,...r.readWindow?{readWindow:r.readWindow}:{},...r.windowReset?{windowReset:!0}:{},messages:projectSqliteHistoryEvents(r.events),totalMessages:r.totalMessages}}function filterSessionMessagesMatchingId(e,n){return e.filter(e=>t(t(e)?.__openclaw)?.id===n)}function selectSessionTranscriptProjection(e,t,n){switch(t.kind){case`recent-text`:return de(t=>M(e,t),t.options);case`delta`:return H(e,t.options);case`count`:return I(e);case`recent`:return{...readRecentSqliteMessageRecords(e,t.options),transcriptPath:n,transcriptSource:`active`};case`page`:{let r=F(e,t.options);return{...Object.hasOwn(r,`activeLeafEntryId`)?{activeLeafEntryId:r.activeLeafEntryId}:{},...r.olderOffset===void 0?{}:{olderOffset:r.olderOffset},...r.deltaCursor?{deltaCursor:r.deltaCursor}:{},...r.omittedOversized?{omittedOversized:!0}:{},messages:projectSqliteHistoryEvents(r.events),displaySource:r.displaySource,...r.readWindow?{readWindow:r.readWindow}:{},...r.windowReset?{windowReset:!0}:{},totalMessages:r.totalMessages,transcriptPath:n,transcriptSource:`active`}}case`around-id`:{let r=V(e,t.options);if(!r.found)return{found:!1,hasOverreadContext:!1,messages:[],offset:0,totalMessages:r.totalMessages,transcriptPath:n};let i=capAnchorEventsByBytes(r.events,t.options);return{found:!0,...r.windowReset?{windowReset:!0}:{},...r.readWindow?{readWindow:r.readWindow}:{},displaySource:r.displaySource,hasOverreadContext:r.hasOverreadContext&&i[0]===r.events[0],messages:i.map(q).filter(e=>e!==void 0),offset:i.length?r.totalMessages-i.at(-1).seq:r.offset,totalMessages:r.totalMessages,transcriptPath:n}}case`by-id`:{let n=U(e,t.messageId,t.options,t.options?.historyVisibility?e=>T(q(e),t.options?.historyVisibility?.sessionStartedAt):void 0);return n?{found:!0,message:q(n),...t.options?.historyVisibility?{historyContext:{displaySource:n.displayPosition?.source,...n.preceding?{precedingMessage:q(n.preceding)}:{}}}:{},oversized:!1,seq:n.seq,...n.serializedBytes===void 0?{}:{serializedBytes:n.serializedBytes}}:{found:!1,oversized:!1}}case`source`:{let{events:r,...i}=readSessionTranscriptSourcePageFromProjection(e,t.options);return{...i,messages:projectSqliteHistoryEvents(r),transcriptPath:n}}case`lookup`:{let n=z(e,t.messageId);return{hasDisplayMessages:n.hasDisplayMessages,messages:filterSessionMessagesMatchingId(projectSqliteHistoryEvents(n.events),t.messageId)}}}throw Error(`Unsupported transcript history selection`)}function visitProjectionMessages(e,n){let r=0,i=j(e);for(let a of ne(e,0,i.total)){let e=t(a.event)?.message;e!==void 0&&(n(e,a.seq),r+=1)}return r}async function filterSessionMessageHistoryVisibility(e,t,n,r,i){let{historyContext:a,...o}=e;if(!r||!o.found)return o;if(!x(a?.precedingMessage===void 0?[o.message]:[a.precedingMessage,o.message],r.sessionStartedAt).includes(o.message))return{found:!1,oversized:!1,historyHidden:!0};if(o.oversized)return{found:!0,oversized:!0,...o.seq===void 0?{}:{seq:o.seq}};if(S(o.message)){let e=a?.transcriptPath?new ArchivedTranscriptReader({exactArchivePath:a.transcriptPath,sessionId:t.sessionId}):void 0,s={...i,readSessionMessagesAroundIdWithStatsAsync:e?(t,n)=>e.readAroundId(n):i.readSessionMessagesAroundIdWithStatsAsync},c=C({maxChars:G,subagentCoordination:i.subagentCoordination});c.append([o.message]);let l=await ue({messages:[o.message],createRecovery:()=>c,readers:s,readScope:t,displaySource:a?.displaySource,maxBytes:G,sessionStartedAt:r.sessionStartedAt}),u=w([o.message,...l],{maxChars:G,subagentCoordination:i.subagentCoordination,resolveCronJobName:()=>void 0}).messages.find(e=>K(e)===n);return u?{...o,message:u}:{found:!1,oversized:!1,historyHidden:!0}}if(r.requireVisible){let e=w([o.message],{maxChars:G,includeCommentaryFallbacks:!0,subagentCoordination:i.subagentCoordination,resolveCronJobName:()=>void 0}).messages.find(e=>K(e)===n);return e?{...o,message:e}:{found:!1,oversized:!1,historyHidden:!0}}return o}function createSessionTranscriptReader(e){async function visitSessionMessagesAsync(t,n){let r=await e.resolveTarget(t);return e.readSnapshot(r,e=>visitProjectionMessages(e,n))}async function readSessionTranscriptSummaryAsync(t,n){let r=await prepareSessionTranscriptSummaryReader(n),i=await e.resolveTarget(t);return e.readSnapshot(i,e=>r(t=>{visitProjectionMessages(e,t)}))}async function readSnapshotIfPresent(t,n,r){try{return await e.readSnapshot(t,e=>selectSessionTranscriptProjection(e,n,t.sessionFile),r)}catch(e){if(e instanceof u&&e.reason===`database-missing`&&(r===void 0||r.allowResetArchiveFallback===!0)&&!r?.readOnly)return;throw e}}async function readSessionMessageCountAsync(t){return await readSnapshotIfPresent(await e.resolveTarget(t),{kind:`count`})??0}async function readSessionMessagesWithSourceAsync(t,n){let r=await e.resolveTarget(t);if(n.cursor?.kind===`archive`)return archivedTranscriptReader(r).readSourcePage(n,n.cursor.snapshot);let i=await readSnapshotIfPresent(r,{kind:`source`,options:n},n)??{messages:[]};return n.allowResetArchiveFallback===!0&&!n.cursor&&(i.snapshot?.totalMessages??0)===0?archivedTranscriptReader(r).readSourcePage(n,i.snapshot??{indexedSeq:-1,activeEventCount:0,totalMessages:0,generation:void 0,tailEventSeq:void 0,resetSeq:null}):i}async function readSessionMessageByIdAsync(n,r,i){let a=await e.resolveTarget(n),o=await readSnapshotIfPresent(a,{kind:`by-id`,messageId:r,options:i});return filterSessionMessageHistoryVisibility(o?.found?o:i?.allowResetArchiveFallback===!0&&!i.currentOnly?await archivedTranscriptReader(a).readById(r,i.historyVisibility):{found:!1,oversized:!1},n,r,i?.historyVisibility,{...t,subagentCoordination:e.subagentCoordination})}async function readSessionMessagesMatchingIdAsync(t,n){let r=await e.resolveTarget(t),i=await e.readSnapshot(r,e=>selectSessionTranscriptProjection(e,{kind:`lookup`,messageId:n}));return i.hasDisplayMessages?i.messages:filterSessionMessagesMatchingId(await archivedTranscriptReader(r).readMessageCandidatesById(n),n)}async function readMessagePage(t,n){let r=await e.resolveTarget(t),i=await readSnapshotIfPresent(r,n,n.options)??{messages:[],totalMessages:0};if(!i.windowReset&&i.totalMessages===0&&(n.kind===`page`||i.messages.length===0)&&n.options.allowResetArchiveFallback===!0){let e=archivedTranscriptReader(r);return n.kind===`recent`?e.readRecentWithStats(n.options):e.readPage(n.options)}return{...i,transcriptPath:r.sessionFile,transcriptSource:`active`}}let readRecentSessionMessagesWithStatsAsync=(e,t)=>readMessagePage(e,{kind:`recent`,options:t}),readSessionMessagesPageWithStatsAsync=(e,t)=>readMessagePage(e,{kind:`page`,options:t});async function readSessionMessagesAroundIdWithStatsAsync(t,n){let r=await e.resolveTarget(t),i=!t.sessionFile&&t.sessionEntry?.sessionId&&t.sessionEntry.sessionId!==t.sessionId?void 0:r.sessionFile,a=await readSnapshotIfPresent(r,{kind:`around-id`,options:n},n);return a?.found?a:n.allowResetArchiveFallback===!0?await new ArchivedTranscriptReader({agentId:r.agentId,sessionFile:i,sessionId:r.sessionId,storePath:r.storePath}).readAroundId(n):{found:!1,hasOverreadContext:!1,messages:[],offset:0,totalMessages:a?.totalMessages??0,transcriptPath:r.sessionFile}}let t={visitSessionMessagesAsync,readSessionTranscriptSummaryAsync,readSessionMessageCountAsync,readSessionMessagesWithSourceAsync,readSessionMessageByIdAsync,readSessionMessagesMatchingIdAsync,readRecentSessionMessagesWithStatsAsync,readSessionMessagesPageWithStatsAsync,readSessionMessagesAroundIdWithStatsAsync};return t}export{filterSessionMessageHistoryVisibility as n,he as r,createSessionTranscriptReader as t};