UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

5 lines • 6.79 kB
import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{c as iterateSqliteQuerySync}from"./kysely-sync-R08Pt8qn.mjs";import{a as tableExists,o as tableHasColumn}from"./openclaw-state-db-schema-helpers-rYTimzjJ.mjs";import{n as openNodeSqliteDatabase}from"./node-sqlite-DXyF1fBG.mjs";import{a as resolveSqliteInspectionSignal}from"./sqlite-readonly-worker-context-BjXXEC4m.mjs";import{r as beginUpdateDoctorHistoricalScan}from"./update-doctor-scan-receipts-c8yyWr4S.mjs";import"./transcript-payload-XgNI1bf4.mjs";import{n as readTranscriptPayload,r as transcriptEventJsonSql}from"./transcript-payload-read-aAg-1-ep.mjs";import{t as getSessionKysely}from"./session-accessor.sqlite-scope-helpers-_Zyjm1vW.mjs";import"./session-accessor.sqlite-scope-BHH23mIq.mjs";import{a as resolveAllAgentSessionStoreTargetsSync}from"./targets-DZpbOEi4.mjs";import{d as resolveTargetSqliteOptions,i as projectExistingAgentDatabaseTargets}from"./session-sqlite-migration-readers-Cc_cphZg.mjs";import{t as note}from"./note-e4DtVgg2.mjs"; //!src/commands/doctor-session-sqlite-transcript-readers.ts function resetReadIterator(e){try{e?.return?.()}catch{}}var ReadOnlySqliteTranscriptReader=class{constructor(e){this.database=e;this.compressed=tableHasColumn(e,`transcript_events`,`event_zstd`);this.eventJsonSql=this.compressed?transcriptEventJsonSql(e).compile(getSessionKysely(e)).sql:`event_json`;this.labelRowsSql=`SELECT ${this.eventJsonSql} AS event_json, seq FROM transcript_events WHERE session_id = ? ORDER BY seq ASC`;this.labelDetectionSql=this.compressed?`SELECT event_json, navigation_json, seq FROM transcript_events WHERE session_id = ? ORDER BY seq ASC`:this.labelRowsSql}sessionIds(){if(!tableExists(this.database,`transcript_events`))return[];const e=tableExists(this.database,`session_transcript_cold_archives`)?` WHERE session_id NOT IN (SELECT session_id FROM session_transcript_cold_archives)`:``;return this.database.prepare(`SELECT DISTINCT session_id FROM transcript_events${e} ORDER BY session_id ASC`).all().flatMap(e=>typeof e.session_id===`string`?[e.session_id]:[])}headerlessSessionIds(e){if(!tableExists(this.database,`transcript_events`))return[];const t=getSessionKysely(this.database);const n=t.selectFrom(`transcript_events`).$if(tableExists(this.database,`session_transcript_cold_archives`),e=>e.where(`session_id`,`not in`,e=>e.selectFrom(`session_transcript_cold_archives`).select(`session_id`))).select(`session_id`).select(e=>e.fn.min(`seq`).as(`seq`)).groupBy(`session_id`).as(`first`);const r=t.selectFrom(`transcript_events as event`).innerJoin(n,e=>e.onRef(`event.session_id`,`=`,`first.session_id`).onRef(`event.seq`,`=`,`first.seq`)).select([`event.session_id`,`event.event_json`]);const i=this.compressed?r.select([`event.event_zstd`,`event.event_utf8_bytes`]):r.select(e=>[e.val(null).as(`event_zstd`),e.val(null).as(`event_utf8_bytes`)]);const a=[];for(const t of iterateSqliteQuerySync(this.database,i)){if(typeof t.session_id!==`string`)continue;let n;try{n=this.compressed?readTranscriptPayload(t):t.event_json}catch(n){e(t.session_id,n);continue}if(typeof n!==`string`){a.push(t.session_id);continue}let r;try{r=JSON.parse(n)}catch{continue}if(isRecord(r)&&r.type!==`session`)a.push(t.session_id)}return a.toSorted((e,t)=>Buffer.compare(Buffer.from(e),Buffer.from(t)))}labelRepairSnapshot(e,t,n){let r;try{this.labelDetection??=this.database.prepare(this.labelDetectionSql);r=this.labelDetection.iterate(e);for(const i of r){if(typeof i.seq!==`number`)continue;let a=i.event_json;if(typeof a!==`string`){if(typeof i.navigation_json===`string`){const{navigation:e}=JSON.parse(i.navigation_json);if(!isRecord(e)||e.type!==`message`||!isRecord(e.message)||e.message.role!==`user`&&e.message.role!==`assistant`)continue}this.labelCandidate??=this.database.prepare(`SELECT ${this.eventJsonSql} AS event_json FROM transcript_events WHERE session_id = ? AND seq = ?`);a=this.labelCandidate.get(e,i.seq)?.event_json??null}if(typeof a!==`string`||!n(a))continue;let o;try{o=JSON.parse(a)}catch{continue}if(!t(o))continue;const s=[];this.labelSnapshot??=this.database.prepare(this.labelRowsSql);r=this.labelSnapshot.iterate(e);for(const e of r)if(typeof e.event_json===`string`&&typeof e.seq===`number`)s.push({eventJson:e.event_json,seq:e.seq});return{ok:true,rows:s}}return{ok:true,rows:[]}}catch(e){resetReadIterator(r);return{ok:false,error:e}}}headerlessSnapshot(e,t){let n;try{this.sessionKey??=this.database.prepare(`SELECT session_key FROM session_windows WHERE session_id = ? LIMIT 1`);const r=this.sessionKey.get(e);const i=[];this.headerSnapshot??=this.database.prepare(`SELECT created_at, ${this.eventJsonSql} AS event_json, seq FROM transcript_events WHERE session_id = ? ORDER BY seq ASC`);n=this.headerSnapshot.iterate(e);for(const r of n){if(typeof r.created_at!==`number`||typeof r.event_json!==`string`||typeof r.seq!==`number`)return{ok:false,error:/* @__PURE__ */ new Error(`Invalid transcript row metadata for session ${e}`)};const n={createdAt:r.created_at,eventJson:r.event_json,seq:r.seq};if(!t(n))return{ok:true,rows:[]};i.push(n)}return{ok:true,rows:i,...typeof r?.session_key===`string`?{sessionKey:r.session_key}:{}}}catch(e){resetReadIterator(n);return{ok:false,error:e}}}}; //!src/commands/doctor-session-transcript-scan.ts async function scanDoctorSessionTranscripts(e,t){const n=resolveSqliteInspectionSignal();n?.throwIfAborted();const reportError=(t,n)=>note(`${t}: ${formatErrorMessage(n).replace(/\s+/g,` `).trim()}`,e.title);for(const r of projectExistingAgentDatabaseTargets(resolveAllAgentSessionStoreTargetsSync(e.cfg,{env:e.env}),e.env,e.cfg)){const i=e.cleanScanIdentity?beginUpdateDoctorHistoricalScan(r.sqlitePath,e.cleanScanIdentity(r)):void 0;if(i?.reused){i.complete();continue}const a=i?{...r,sqlitePath:i.databasePath}:r;let o=true;const reportTargetError=(e,t)=>{o=false;reportError(e,t)};const s=resolveTargetSqliteOptions(a,e.env);let c;try{c=openNodeSqliteDatabase(a.sqlitePath,{readOnly:true});const r=new ReadOnlySqliteTranscriptReader(c);const i=e.selectSessionIds?e.selectSessionIds(r,(e,t)=>reportTargetError(`- Failed to read transcript ${e} (${a.agentId})`,t)):r.sessionIds();for(const e of i){n?.throwIfAborted();if(await t({reader:r,sessionId:e,target:a,databaseOptions:s,reportError:reportTargetError})===false)o=false;n?.throwIfAborted()}}catch(t){n?.throwIfAborted();reportTargetError(`- ${e.failureLabel} for ${a.agentId} (${a.sqlitePath})`,t)}finally{c?.close()}if(o)i?.complete()}}function transcriptSnapshotsMatch(e,t,n=false){return e.length===t.length&&e.every((e,r)=>e.seq===t[r]?.seq&&(!n||e.createdAt===t[r]?.createdAt)&&e.eventJson===t[r]?.eventJson)}export{transcriptSnapshotsMatch as n,scanDoctorSessionTranscripts as t};