UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

4 lines • 5.35 kB
import{V as timestampMsToIsoString}from"./number-coercion-B3CfI447.mjs";import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{N as parseAgentSessionKey}from"./session-key-BPgKfU2m.mjs";import{f as resolveAgentWorkspaceDir}from"./agent-scope-config-CG9CFpGX.mjs";import{a as executeSqliteQueryTakeFirstSync}from"./kysely-sync-R08Pt8qn.mjs";import{W as backupDoctorSqliteRepair}from"./openclaw-state-db-BlgxYkYw.mjs";import"./agent-scope-Dw5XRSEh.mjs";import{s as runOpenClawAgentWriteTransaction}from"./openclaw-agent-db-BUym2U31.mjs";import{a as isIndexedSessionEntry}from"./session-entry-codec-aa6Rsx0o.mjs";import{t as createSessionTranscriptHeader}from"./transcript-header-CDC-8D8h.mjs";import{t as getSessionKysely}from"./session-accessor.sqlite-scope-helpers-_Zyjm1vW.mjs";import"./session-accessor.sqlite-scope-BHH23mIq.mjs";import{n as isSessionTranscriptLeafControl,t as isCanonicalSessionTranscriptEntry}from"./transcript-tree-Dwc2Zlw1.mjs";import{r as replaceSqliteTranscriptEventsInTransaction}from"./session-accessor.sqlite-transcript-store-CHxqudYm.mjs";import{T as readTranscriptStorageRows}from"./session-accessor.sqlite-read-B5RvcnvD.mjs";import"./session-manager-codec-D_PnvLVG.mjs";import{t as note}from"./note-e4DtVgg2.mjs";import{t as countLabel}from"./doctor-state-integrity-format-2pYQQBOH.mjs";import{n as transcriptSnapshotsMatch,t as scanDoctorSessionTranscripts}from"./doctor-session-transcript-scan-DcGdmgAQ.mjs"; //!src/commands/doctor-session-transcript-headers.ts const NOTE_TITLE=`Chat history headers`;function createCanonicalHeaderlessEventParser(e){const t=/* @__PURE__ */ new Set([e]);const n=[];let r=0;return{events:n,hasIndexedEntries:()=>r>0,parse(e){let i;try{i=JSON.parse(e.eventJson)}catch{return}if(!isRecord(i)||i.type===`session`)return;if(isCanonicalSessionTranscriptEntry(i)){if(!isIndexedSessionEntry(i))return;r+=1}else if(i.type===`leaf`&&!isSessionTranscriptLeafControl(i))return;if(typeof i.id===`string`){const e=i.id.trim();if(!e||t.has(e))return;t.add(e)}n.push(i);return i}}}function readHeaderRepairContext(e,t){const n=getSessionKysely(e.db);const r=executeSqliteQueryTakeFirstSync(e.db,n.selectFrom(`session_windows`).leftJoin(`session_nodes`,`session_nodes.session_key`,`session_windows.session_key`).select([`session_windows.session_key`,`session_nodes.current_session_id`,`session_nodes.entry_json`]).where(`session_windows.session_id`,`=`,t).limit(1));if(!r?.session_key)return;let i;if(r.current_session_id===t&&r.entry_json)try{const e=JSON.parse(r.entry_json);if(e.sessionId===t&&typeof e.spawnedCwd===`string`&&e.spawnedCwd.trim())i=e.spawnedCwd.trim()}catch{}return{sessionKey:r.session_key,...i?{spawnedCwd:i}:{}}}async function noteSessionTranscriptHeaderHealth(e){const t=e.env??process.env;let n=0;let r=0;const i=/* @__PURE__ */ new Set;await scanDoctorSessionTranscripts({cfg:e.cfg,env:t,title:NOTE_TITLE,failureLabel:`Failed to inspect chat history headers`,selectSessionIds:(e,t)=>e.headerlessSessionIds(t)},async({reader:a,target:o,databaseOptions:s,reportError:c,sessionId:l})=>{const u=o.sqlitePath;const d=createCanonicalHeaderlessEventParser(l);const f=a.headerlessSnapshot(l,e=>d.parse(e)!==void 0);if(!f.ok){c(`- Failed to read transcript ${l} (${o.agentId})`,f.error);return}if(!f.sessionKey||!d.hasIndexedEntries()||f.rows.length===0)return;const p=timestampMsToIsoString(f.rows[0]?.createdAt??NaN);if(!p){note(`- Failed to repair transcript ${l} (${o.agentId}): invalid first-row timestamp`,NOTE_TITLE);return}n+=1;if(!e.shouldRepair)return;const m=parseAgentSessionKey(f.sessionKey)?.agentId??o.agentId;const h=resolveAgentWorkspaceDir(e.cfg,m,t);try{if(!i.has(u)){const e=await backupDoctorSqliteRepair(u,`transcript-headers`);i.add(u);note(`- Saved pre-repair SQLite backup: ${e}`,NOTE_TITLE)}runOpenClawAgentWriteTransaction(e=>{const n=readTranscriptStorageRows(e,l);if(!transcriptSnapshotsMatch(f.rows,n,true))throw new Error(`transcript changed while preparing header repair for ${l}`);const r=readHeaderRepairContext(e,l);if(!r||r.sessionKey!==f.sessionKey)throw new Error(`session binding changed while preparing header repair for ${l}`);const i=createSessionTranscriptHeader({version:3,cwd:r.spawnedCwd??h,sessionId:l,timestamp:p});replaceSqliteTranscriptEventsInTransaction(e,{agentId:o.agentId,env:t,path:u,sessionId:l,sessionKey:r.sessionKey},[i,...d.events],{createdAtByIndex:[n[0]?.createdAt??Date.parse(p),...n.map(e=>e.createdAt)],preserveSessionWindowRecency:true})},s,{operationLabel:`doctor.session-transcript-headers`,repairAdmission:{integrityCheck:e.integrityCheck??`quick`,integrityTables:[`transcript_events`,`transcript_rewrite_watermarks`,`session_windows`,`session_transcript_index_state`,`session_transcript_active_events`,`session_transcript_fts_rows`,`session_transcript_fts`,`transcript_event_identities`,`session_reactions`,`session_nodes`]}});r+=1}catch(e){c(`- Failed to repair transcript ${l} (${o.agentId})`,e)}});if(e.shouldRepair&&r>0)note(`- Prepended missing headers to ${countLabel(r,`chat history file`)}.`,NOTE_TITLE);else if(!e.shouldRepair&&n>0)note([`- Found ${countLabel(n,`stored chat history file`)} without a header.`,`- Run "openclaw doctor --fix" to repair ${n===1?`it`:`them`} before resuming the session.`].join(` `),NOTE_TITLE);return{found:n,repaired:r}}export{noteSessionTranscriptHeaderHealth};