UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

8 lines • 18 kB
import{M as e}from"./transcript-chat-message-content-Cx-VPFHv.mjs";import{i as t,t as n}from"./transcript-openclaw-agent-search-schema-BQwqsKhe.mjs";import{U as r,W as i,Y as a}from"./transcript-sqlite-database-admission-Cro6ZHgY.mjs";import{n as o}from"./transcript-sql-connection-CRz-dHXM.mjs";import{a as s,c,i as l,m as u,r as d,t as f,u as p}from"./transcript-kysely-sync-DQ_Yn8jW.mjs";import"./transcript-sqlite-transaction-BxeoS_ke.mjs";import{c as m}from"./transcript-session-entry-codec-CvLNFJN0.mjs";import{a as h,h as g,u as _}from"./transcript-json-values-CmANsVU4.mjs";import"./transcript-session-actor-transaction-D7al_TuX.mjs";import{f as v,i as y,t as b}from"./transcript-transcript-payload-C58U6XNI.mjs";import{r as x}from"./transcript-transcript-payload-read-BfcV5CyI.mjs";import{t as S}from"./transcript-transcript-tree-BBaX4q0_.mjs";import{r as C}from"./transcript-session-transcript-projection-append-DNJQ7iP1.mjs";import{r as w}from"./transcript-session-transcript-read-bytes-C7AU5F9V.mjs";function transcriptDependencyFactsProjectableSql(e,t){let n=u.ref(`${t}.event_json`),r=u.ref(`${t}.navigation_json`);return o(e)?u`${r} IS NOT NULL OR ${h(e,n)}`:u`CASE WHEN ${r} IS NOT NULL THEN 1 WHEN NOT ${h(e,n)} THEN 0 WHEN ${_(e,n,u.lit(`$.type`))} = 'custom' AND ${_(e,n,u.lit(`$.customType`))} = ${m} AND ${g(e,n,u.lit(`$.data`))} = 'text' THEN 0 ELSE 1 END`}function buildSessionTranscriptActiveFactsInsert(e,t,n,r,i=!1,a=!1){let c=s(e),readNavigation=e=>{let t=e.facts;return`dependencyNavigationJson`in t?t.dependencyNavigationJson:null};if(a&&!i)return c.insertInto(`session_transcript_active_event_facts`).values(Array.from({length:n},(e,n)=>({session_id:t,seq:r(e=>e[n].eventSeq),serialized_bytes:r(e=>e[n].facts.serializedBytes),dependency_navigation_json:r(e=>readNavigation(e[n]))})));let l=o(e),d={seq:e=>e.eventSeq,context_eligible:e=>e.contextEligible,serialized_bytes:e=>e.facts.serializedBytes,dependency_navigation_json:readNavigation,event_json:e=>e.facts&&`payload`in e.facts?e.facts.payload.event_json:null,navigation_json:e=>e.facts&&`payload`in e.facts?e.facts.payload.navigation_json:null,navigation_type:e=>e.facts&&`payload`in e.facts?e.facts.payload.navigation_type:null,navigation_valid:e=>e.facts&&`payload`in e.facts?e.facts.payload.navigation_valid:null,message_role:e=>e.facts&&`payload`in e.facts?e.facts.payload.message_role:null},f=a?[`seq`,`serialized_bytes`,`dependency_navigation_json`]:[`seq`,`context_eligible`,`serialized_bytes`,`dependency_navigation_json`,`event_json`,`navigation_json`,`navigation_type`,`navigation_valid`,`message_role`],p=/* @__PURE__ */ new Set([`seq`,`context_eligible`,`serialized_bytes`,`navigation_valid`]),m=u`(values ${u.join(Array.from({length:n},(e,t)=>u`(${u.join(f.map(e=>{let n=r(n=>d[e](n[t]));return l?u`${n}::${u.raw(p.has(e)?`bigint`:`text`)}`:n}))})`))})`;return c.with(a?`active_fact_input(seq, serialized_bytes, dependency_navigation_json)`:`active_fact_input(seq, context_eligible, serialized_bytes, dependency_navigation_json, event_json, navigation_json, navigation_type, navigation_valid, message_role)`,()=>m).insertInto(`session_transcript_active_event_facts`).columns([`session_id`,`seq`,`serialized_bytes`,`dependency_navigation_json`]).expression(n=>n.selectFrom(`active_fact_input as event`).select(n=>[typeof t==`string`?n.val(t).as(`session_id`):t.as(`session_id`),`event.seq`,`event.serialized_bytes`,a?u`event.dependency_navigation_json`.as(`dependency_navigation_json`):u`CASE WHEN event.dependency_navigation_json IS NOT NULL THEN event.dependency_navigation_json ELSE ${y(e,n.ref(`event.context_eligible`),`event`)} END`.as(`dependency_navigation_json`)]).$if(!a,t=>t.where(t=>t.or([t(`event.dependency_navigation_json`,`is not`,null),transcriptDependencyFactsProjectableSql(e,`event`)]))).$if(i,e=>e.where(u`event.seq IN (SELECT event_seq FROM projection_active)`)))}const T=f(e=>{let prepare=(t,n)=>c(e,r=>buildSessionTranscriptActiveFactsInsert(e,r(e=>e.sessionId),t,e=>r(t=>e(t.rows)),!1,n)),t=[],n=[];return{forCount(e,r){let i=+!!r;return e===1?t[i]??=prepare(e,r):e===512?n[i]??=prepare(e,r):prepare(e,r)}}});function createSessionTranscriptActiveFactsInserter(e,t){let n=T(e);return r=>{if(b(e))return;let i=r.filter(e=>e.facts!==void 0);if(i.length!==0)for(let e=0;e<i.length;e+=512){let r=i.slice(e,e+512),a=r.every(e=>e.facts&&`dependencyNavigationJson`in e.facts);n.forCount(r.length,a)({sessionId:t,rows:r})}}}function withPostgresSessionTranscriptFtsRows(e,t,n){return buildPostgresSessionTranscriptFtsRows(s(e),t,n)}function buildPostgresSessionTranscriptFtsRows(e,t,n){return e.with(`entries(position, message_id, text, role, timestamp)`,()=>n).with(e=>e(`ids`).materialized(),e=>e.selectFrom(`entries`).select(e=>e.fn(`nextval`,[e.fn(`pg_get_serial_sequence`,[u.lit(`session_transcript_fts_rows`),u.lit(`id`)])]).as(`id`))).with(e=>e(`allocated`).materialized(),e=>e.selectFrom(e.selectFrom(`entries`).selectAll().select(e=>e.fn.agg(`row_number`,[]).over(e=>e.orderBy(`position`)).as(`rn`)).as(`ordered_entries`)).innerJoin(e.selectFrom(`ids`).select(`id`).select(e=>e.fn.agg(`row_number`,[]).over(e=>e.orderBy(`id`)).as(`rn`)).as(`ordered_ids`),`ordered_ids.rn`,`ordered_entries.rn`).selectAll(`ordered_entries`).select(`ordered_ids.id`)).with(`inserted`,e=>e.insertInto(`session_transcript_fts_rows`).columns([`id`,`session_id`,`message_id`]).expression(e=>e.selectFrom(`allocated`).select(e=>[`id`,e.val(t).as(`session_id`),`message_id`]).orderBy(`position`)).returning(`id`)).with(`inserted_content`,e=>e.insertInto(`session_transcript_fts`).columns([`rowid`,`text`,`session_id`,`message_id`,`role`,`timestamp`]).expression(e=>e.selectFrom(`inserted`).innerJoin(`allocated`,`allocated.id`,`inserted.id`).select(e=>[`allocated.id`,`allocated.text`,e.val(t).as(`session_id`),`allocated.message_id`,`allocated.role`,e.cast(`allocated.timestamp`,`double precision`).as(`timestamp`)]).orderBy(`allocated.position`)).returning(`rowid`))}function createSessionTranscriptFtsInserter(e,i){let l=s(e),d=o(e),f=d?void 0:t(e,n);if(f&&!f.fullText)throw Error(f.diagnostics.join(`; `));let prepare=t=>{let n=Array.from({length:t},(e,t)=>t),r=c(e,r=>{let a=u`(values ${u.join(n.map(e=>u`(${u.lit(e)}, ${r(t=>t[e].messageId)}, ${r(t=>t[e].text)}, ${r(t=>t[e].role)}, ${r(t=>t[e].timestamp)})`))})`;return d?withPostgresSessionTranscriptFtsRows(e,i,a).selectNoFrom(u.lit(1).as(`written`)):l.with(`entries(position, message_id, text, role, timestamp)`,()=>a).with(e=>e(`allocated`).materialized(),e=>e.selectNoFrom(f.fullText.allocatedIdentity(f.text.transcript).as(`last_id`))).insertInto(`session_transcript_fts`).columns([`rowid`,`text`,`session_id`,`message_id`,`role`,`timestamp`]).expression(e=>e.selectFrom(`entries`).crossJoin(`allocated`).select(e=>[e(e(`allocated.last_id`,`-`,u.lit(t-1)),`+`,e.ref(`entries.position`)).as(`rowid`),`entries.text`,e.val(i).as(`session_id`),`entries.message_id`,`entries.role`,`entries.timestamp`]).orderBy(`entries.position`))});if(d)return r;let a=c(e,e=>l.insertInto(`session_transcript_fts_rows`).values(n.map(t=>({session_id:i,message_id:e(e=>e[t].messageId)}))));return e=>{a(e),r(e)}},p=/* @__PURE__ */ new Map;return t=>{r(e,[a(i)],()=>{for(let e=0;e<t.length;e+=512){let n=t.slice(e,e+512),r=p.get(n.length)??prepare(n.length);p.set(n.length,r),r(n)}})}}function deleteSessionTranscriptFtsRowsInTransaction(e,t,n={}){let i=s(e),o=i.selectFrom(`session_transcript_fts_rows`).select(`id`);return o=typeof t==`string`?o.where(`session_id`,`=`,t):o.where(`session_id`,`in`,p(t)),n.messageIds&&(o=o.where(`message_id`,`in`,n.messageIds.length<=400?n.messageIds:p(n.messageIds))),n.maxRows!==void 0&&(o=o.limit(n.maxRows)),Number(r(e,(typeof t==`string`?[t]:t).map(a),()=>d(e,i.deleteFrom(`session_transcript_fts_rows`).where(`id`,`in`,o)).numAffectedRows)??0n)}function getProjectionKysely(e){return s(e)}function projectionFactsColumns(e){return[u`${w()} + 1`.as(`serialized_bytes`),u`CASE WHEN ${transcriptDependencyFactsProjectableSql(e,`transcript_events`)} THEN ${y(e,u.lit(0),`transcript_events`)} ELSE NULL END`.as(`dependency_navigation_json`),v(e,`navigation_type`).as(`navigation_type`)]}function projectionRowFacts(e,t){return e.serialized_bytes===void 0||e.dependency_navigation_json==null?void 0:{serializedBytes:e.serialized_bytes,dependencyNavigationJson:e.navigation_type===`message`&&t!==0?`{}`:e.dependency_navigation_json}}function readCanonicalEventId(e){return!S(e)||typeof e.id!=`string`?null:e.id.trim()||null}function readProjectionSession(e,t){return l(e,getProjectionKysely(e).selectFrom(`session_windows as session`).leftJoin(`transcript_rewrite_watermarks as rewrite`,`rewrite.session_id`,`session.session_id`).select([`session.transcript_updated_at`,`rewrite.generation`]).where(`session.session_id`,`=`,t))}function readProjectionSourceSnapshot(e,t){let n=getProjectionKysely(e),r=readProjectionSession(e,t),i=l(e,n.selectFrom(`transcript_events`).select(`seq`).where(`session_id`,`=`,t).orderBy(`seq`,`desc`).limit(1));return{generation:r?.generation??null,latestSeq:i?.seq,transcriptUpdatedAt:r?.transcript_updated_at??null}}function sourceSnapshotMatches(e,t){return e.generation===t.sourceTranscriptGeneration&&e.latestSeq===t.sourceIndexedSeq&&e.transcriptUpdatedAt===t.sourceTranscriptUpdatedAt}function projectionTailFitsCatchUpBounds(e,t,n){if(t.sourceTranscriptGeneration===null||n.generation!==t.sourceTranscriptGeneration||n.latestSeq===void 0||n.latestSeq<t.sourceIndexedSeq)return!1;let r=n.latestSeq-t.sourceIndexedSeq;if(r>512)return!1;let i=d(e,getProjectionKysely(e).selectFrom(`transcript_events`).select([`seq`,w().as(`event_bytes`)]).where(`session_id`,`=`,t.sessionId).where(`seq`,`>`,t.sourceIndexedSeq).orderBy(`seq`,`asc`).limit(513)).rows;return i.length===r&&(i.at(-1)?.seq??t.sourceIndexedSeq)===n.latestSeq&&i.reduce((e,t)=>e+t.event_bytes,0)<=262144}function claimPreparedSessionTranscriptProjectionInTransaction(e,t,n){let r=getProjectionKysely(e),i={active_event_count:0,active_message_count:0,indexed_seq:-1,leaf_event_id:null,needs_rebuild:1,updated_at:n},a=d(e,r.insertInto(`session_transcript_index_state`).columns([`session_id`,`active_event_count`,`active_message_count`,`indexed_seq`,`leaf_event_id`,`needs_rebuild`,`updated_at`]).expression(r.selectFrom(`session_windows`).select(e=>[`session_id`,e.val(i.active_event_count).as(`active_event_count`),e.val(i.active_message_count).as(`active_message_count`),e.val(i.indexed_seq).as(`indexed_seq`),e.val(i.leaf_event_id).as(`leaf_event_id`),e.val(i.needs_rebuild).as(`needs_rebuild`),e.val(i.updated_at).as(`updated_at`)]).where(`session_id`,`=`,t.sessionId)).onConflict(e=>e.column(`session_id`).doUpdateSet(i)));return Number(a.numAffectedRows??0n)>0}function deletePreparedSessionTranscriptProjectionChunkInTransaction(e,t){let n=getProjectionKysely(e),r=o(e)?`event_seq`:`rowid`,i=Number(d(e,n.deleteFrom(`session_transcript_active_events`).$if(o(e),e=>e.where(`session_id`,`=`,t.sessionId)).where(r,`in`,n.selectFrom(`session_transcript_active_events`).select(r).where(`session_id`,`=`,t.sessionId).limit(t.maxRowsPerTable))).numAffectedRows??0n),a=deleteSessionTranscriptFtsRowsInTransaction(e,t.sessionId,{maxRows:t.maxRowsPerTable});return{hasMore:i===t.maxRowsPerTable||a===t.maxRowsPerTable}}function appendPreparedSessionTranscriptProjectionChunkInTransaction(e,t){insertPreparedSessionTranscriptProjectionRows(e,t)}function insertPreparedSessionTranscriptProjectionRows(e,t){let n=getProjectionKysely(e);t.activeRows&&t.activeRows.length>0&&d(e,n.insertInto(`session_transcript_active_events`).values(t.activeRows.map(e=>({active_position:e.activePosition,context_eligible:e.contextEligible,event_seq:e.eventSeq,message_position:e.messagePosition,session_id:t.sessionId})))),t.activeRows&&t.activeRows.length>0&&createSessionTranscriptActiveFactsInserter(e,t.sessionId)(t.activeRows),t.ftsRows&&t.ftsRows.length>0&&createSessionTranscriptFtsInserter(e,t.sessionId)(t.ftsRows)}function prepareProjectionTailCatchUp(e,t,n){let r=n.latestSeq;if(t.sourceHasInvalidLeafControl||r===void 0||!projectionTailFitsCatchUpBounds(e,t,n))return;let i=d(e,getProjectionKysely(e).selectFrom(`transcript_events`).select([x(e).as(`event_json`),`seq`,`created_at`]).select(projectionFactsColumns(e)).where(`session_id`,`=`,t.sessionId).where(`seq`,`>`,t.sourceIndexedSeq).where(`seq`,`<=`,r).orderBy(`seq`,`asc`)).rows,a=[],o=[],s={activeEventCount:t.activeEventCount,activeMessageCount:t.activeMessageCount,indexedSeq:t.sourceIndexedSeq,leafEventId:t.leafEventId};for(let e of i){let t=JSON.parse(e.event_json);if(S(t)&&t.type===`reset`)return;let n=C({createdAt:e.created_at,cursor:s,event:t,eventId:readCanonicalEventId(t),seq:e.seq});if(!n)return;s=n.cursor,n.activeRow&&(n.activeRow.facts=projectionRowFacts(e,n.activeRow.contextEligible),a.push(n.activeRow)),n.ftsRow&&o.push(n.ftsRow)}return{...t,activeEventCount:s.activeEventCount,activeMessageCount:s.activeMessageCount,activeRows:a,ftsRows:o,leafEventId:s.leafEventId,sourceIndexedSeq:s.indexedSeq,sourceTranscriptUpdatedAt:n.transcriptUpdatedAt}}function finalizePreparedSessionTranscriptProjectionInTransaction(e,t,n){let r=readProjectionSourceSnapshot(e,t.sessionId),i=sourceSnapshotMatches(r,t),a=i?void 0:prepareProjectionTailCatchUp(e,t,r);if(!i&&!a)return!1;let o=a??t;a&&insertPreparedSessionTranscriptProjectionRows(e,{activeRows:a.activeRows,ftsRows:a.ftsRows,sessionId:a.sessionId});let s=d(e,getProjectionKysely(e).updateTable(`session_transcript_index_state`).set({active_event_count:o.activeEventCount,active_message_count:o.activeMessageCount,indexed_seq:o.sourceIndexedSeq,leaf_event_id:o.leafEventId,needs_rebuild:0,updated_at:Date.now()}).where(`session_id`,`=`,o.sessionId).where(`needs_rebuild`,`!=`,0).where(`updated_at`,`=`,n));return Number(s.numAffectedRows??0n)>0}var E=/* @__PURE__ */ e({SYNC_REBUILD_MAX_BYTES:()=>SYNC_REBUILD_MAX_BYTES,SYNC_REBUILD_MAX_ROWS:()=>SYNC_REBUILD_MAX_ROWS,deleteOrphanedTranscriptIndexRowsInTransaction:()=>deleteOrphanedTranscriptIndexRowsInTransaction,listSessionsNeedingTranscriptIndexReconcile:()=>listSessionsNeedingTranscriptIndexReconcile,selectSessionTranscriptIndexStatus:()=>selectSessionTranscriptIndexStatus,selectSessionTranscriptProjectionState:()=>selectSessionTranscriptProjectionState,sessionTranscriptIndexNeedsReconcile:()=>sessionTranscriptIndexNeedsReconcile});function getIndexKysely(e){return s(e)}function selectSessionTranscriptProjectionState(e,t){return getIndexKysely(e).selectFrom(`session_transcript_index_state`).select([`active_event_count`,`active_message_count`,`indexed_seq`,`leaf_event_id`,`needs_rebuild`]).select(e=>e.exists(e.selectFrom(`session_transcript_active_events`).select(`session_id`).where(`session_id`,`=`,t).where(`context_eligible`,`is`,null).limit(1)).as(`has_unclassified`)).where(`session_id`,`=`,t)}function selectSessionTranscriptIndexStatus(e,t){let n=getIndexKysely(e),r=o(e),i=r?`is distinct from`:`is not`;return n.selectFrom(n.selectFrom(`transcript_events`).select(`seq`).where(`session_id`,`=`,t).orderBy(`seq`,`desc`).limit(1).as(`latest`)).leftJoin(selectSessionTranscriptProjectionState(e,t).as(`state`),e=>e.onTrue()).select(`latest.seq as latestSeq`).select(e=>e.or([e(`state.needs_rebuild`,i,0),e(`state.indexed_seq`,i,e.ref(`latest.seq`)),e(`state.has_unclassified`,`=`,r?u.lit(!0):1)]).as(`needs_reconcile`))}function readSessionTranscriptIndexStatus(e,t){let n=l(e,selectSessionTranscriptIndexStatus(e,t));return n?{needsReconcile:!!n.needs_reconcile}:void 0}function sessionTranscriptIndexNeedsReconcile(e,t){return readSessionTranscriptIndexStatus(e,t)?.needsReconcile??!1}function selectSessionsNeedingTranscriptIndexReconcile(e){return getIndexKysely(e).selectFrom(`session_windows`).innerJoin(`transcript_events as latest`,e=>e.onRef(`latest.session_id`,`=`,`session_windows.session_id`).on(e=>e(`latest.seq`,`=`,e.selectFrom(`transcript_events as candidate`).select(`candidate.seq`).whereRef(`candidate.session_id`,`=`,`session_windows.session_id`).orderBy(`candidate.seq`,`desc`).limit(1)))).leftJoin(`session_transcript_index_state as st`,`st.session_id`,`session_windows.session_id`).select(`session_windows.session_id`).where(e=>e.or([e(e.fn.coalesce(`st.needs_rebuild`,e.val(1)),`!=`,0),e(`latest.seq`,`>`,e.fn.coalesce(`st.indexed_seq`,e.val(-1))),e.and([e.exists(e.selectFrom(`session_transcript_active_events as any_pending`).select(`any_pending.session_id`).where(`any_pending.context_eligible`,`is`,null).limit(1)),e.exists(e.selectFrom(`session_transcript_active_events as pending`).select(`pending.session_id`).whereRef(`pending.session_id`,`=`,`session_windows.session_id`).where(`pending.context_eligible`,`is`,null))])])).orderBy(`session_windows.session_id`)}function listSessionsNeedingTranscriptIndexReconcile(e,t){let n=selectSessionsNeedingTranscriptIndexReconcile(e);return d(e,t===void 0?n:n.limit(t)).rows.flatMap(e=>typeof e.session_id==`string`?[e.session_id]:[])}const D=[`session_transcript_active_events`,`session_transcript_fts_rows`,`session_transcript_index_state`];function selectOrphanedTranscriptOwners(e,t){let n=getIndexKysely(e);return n.selectFrom(t).select(`session_id`).distinct().except(n.selectFrom(`transcript_events`).select(`session_id`).distinct()).orderBy(`session_id`)}function deleteOrphanedTranscriptIndexRowsInTransaction(e){let t=getIndexKysely(e);for(let n of D)i(e,()=>d(e,t.deleteFrom(n).where(`session_id`,`in`,selectOrphanedTranscriptOwners(e,n))))}export{E as a,deletePreparedSessionTranscriptProjectionChunkInTransaction as c,sessionTranscriptIndexNeedsReconcile as i,finalizePreparedSessionTranscriptProjectionInTransaction as l,listSessionsNeedingTranscriptIndexReconcile as n,appendPreparedSessionTranscriptProjectionChunkInTransaction as o,selectSessionTranscriptIndexStatus as r,claimPreparedSessionTranscriptProjectionInTransaction as s,deleteOrphanedTranscriptIndexRowsInTransaction as t,transcriptDependencyFactsProjectableSql as u};