UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

118 lines • 24 kB
import{a as e,i as t}from"./transcript-record-coerce-CPLgmAk9.mjs";import{Q as n}from"./transcript-sqlite-database-admission-IPmtadyc.mjs";import{u as r}from"./transcript-sqlite-post-commit-B_pko32i.mjs";import{o as i}from"./transcript-sqlite-schema-facts-C1_zV4Yg.mjs";import{a,l as o,p as s,t as c}from"./transcript-kysely-sync-CAP5xe3V.mjs";import{r as l}from"./transcript-immutable-data-Dv9CHHEc.mjs";import{_ as u,a as d,c as f,f as p,g as m,h,n as g,r as _,s as v}from"./transcript-schemas-C_W5KYqZ.mjs";import{n as y,o as b,r as x,s as S}from"./transcript-session-entry-codec-C1BgT9Uk.mjs";import"./transcript-node-sqlite-RfCz-ZxM.mjs";import{_ as C,a as w,c as T,d as E,f as D,g as O,h as k,m as A,n as j,u as M,v as N}from"./transcript-json-values-C_3KtpDU.mjs";import{r as P}from"./transcript-transcript-events-BDUVmbAW.mjs";import{t as F}from"./transcript-zstd-codec-Bwg8OR0e.mjs";import{l as I,n as L,t as R}from"./transcript-tool-result-pairing-DrpmDHYa.mjs";const z=[`upstreamUserText`],B=l(e=>{let n=t(e.details);if(n?.openclawSyntheticMissingToolResult===!0&&Object.keys(n).length===1)return e;let r={...e};return n?.openclawSyntheticMissingToolResult===!0?r.details={[L]:!0}:delete r.details,r});function stripToolResultDetails(e){let n=!1,r=e.map(e=>{let r=t(e);if(r?.role!==`toolResult`||!(`details`in r))return e;let i=B(r);return n||=i!==e,i});return n?r:e}function projectModelContextMessages(e,n){let r=[];for(let i of stripToolResultDetails(e)){let e=t(i),a=t(e?.__openclaw);if(!a||!z.some(e=>e in a)){r.push(i);continue}let o={...a};for(let e of z)delete o[e];n?.(o),r.push({...e,__openclaw:o})}return r}function projectSessionModelContextEntry(e,{entry:t,omitCheckpoint:n,toolResultOmission:r}){let i={...e,parentId:t.parentId,...t.type===`compaction`||t.type===`reset`?{firstKeptEntryId:t.firstKeptEntryId}:{}};if(i.type!==`message`)return i;let[a]=projectModelContextMessages([i.message]),o={...i,message:a};return n&&o.message.role===`assistant`&&(o.message={...o.message},delete o.message.providerReplay),r!==void 0&&o.message.role===`toolResult`&&(o.message={...o.message,content:[{type:`text`,text:r}]}),o}function hydrateSessionModelContextEntry(e,t){let n=JSON.parse(e);return n.parentId=t.parentId,(t.type===`compaction`||t.type===`reset`)&&t.firstKeptEntryId!==void 0&&Object.assign(n,{firstKeptEntryId:t.firstKeptEntryId}),n}const V=[`type`,`id`,`parentId`,`targetId`,`appendParentId`,`appendMode`],H=[...V,`timestamp`,`version`,`cwd`,`firstKeptEntryId`,`reason`,`tokensBefore`,`thinkingLevel`,`provider`,`modelId`,`fromId`,`customType`,`display`,`excludeFromContext`,`label`,`name`],U=[`role`,`provider`,`model`,`timestamp`,`excludeFromContext`,`toolCallId`,`toolUseId`,`tool_call_id`,`tool_use_id`,`callId`,`call_id`,`toolName`,`isError`,`stopReason`,`customType`,`display`];function pickNavigation(e,t){return Object.fromEntries(t.filter(t=>Object.hasOwn(e,t)).map(t=>[t,e[t]]))}function projectSessionModelContextNavigation(t){let n={...pickNavigation({...t},H),type:t.type,id:t.id,parentId:t.parentId,timestamp:t.timestamp};if(t.type===`message`){let r=t.message,i={...r},a=`content`in r&&Array.isArray(r.content)?r.content.flatMap(t=>e(t)&&[`toolCall`,`toolUse`,`functionCall`].includes(t.type)?[pickNavigation(t,[`type`,`id`,`name`])]:[]):[],o=e(i.details)?i.details:{},s=i.customType===`openclaw.system-update`&&(o.kind===`prompt-update`||o.kind===`runtime-context`)?o.kind:void 0;n.message={...pickNavigation(i,U),content:a,command:``,output:``,providerReplay:{type:e(i.providerReplay)?i.providerReplay.type:null},details:{[L]:I({isError:i.isError,details:i.details,content:i.content}),...s?{kind:s}:{}}}}else t.type===`compaction`||t.type===`branch_summary`?n.summary=``:t.type===`custom_message`?(n.content=[],t.customType===`openclaw.system-update`&&e(t.details)&&(t.details.kind===`prompt-update`||t.details.kind===`runtime-context`)&&(n.details={kind:t.details.kind})):t.type===`custom`&&t.customType===`openclaw.system-prompt`&&(n.data={restart:e(t.data)&&t.data.restart===!0});return n}const W=/* @__PURE__ */ new WeakSet;function projectDeepModelContextSql(e,t,n,r=s.lit(0),i=s.lit(null)){let o=`openclaw_deep_model_context`;return W.has(e)||(e.function(o,{deterministic:!0,directOnly:!0},(e,t,n,r)=>{if(typeof e!=`string`)throw TypeError(`Deep transcript projection requires canonical JSON text`);let i=JSON.parse(e);return JSON.stringify(t===1?projectSessionModelContextNavigation(i):projectSessionModelContextEntry(i,{entry:i,omitCheckpoint:n===1,toolResultOmission:typeof r==`string`?r:void 0}))}),W.add(e)),a(e).fn(o,[t,s.lit(+!!n),r,i])}function projectModelContextEventSql(e,t,n,i,a=M(e,t,s.lit(`$.message.role`)),o=O(e,t)){if(r(e)){let r=postgresModelEventSql(t,a),o=i?s`CASE WHEN ${i} IS NOT NULL AND ${a} = 'toolResult' THEN jsonb_set(${r}, '{message,content}', jsonb_build_array(jsonb_build_object('type', 'text', 'text', ${i}::text))) ELSE ${r} END`:r;return s`CASE WHEN ${w(e,t)} THEN (CASE WHEN ${n} = 1 THEN ${o} #- '{message,providerReplay}' ELSE ${o} END)::text ELSE ${t}::text END`}let c=z.map(e=>`$.message.__openclaw.${e}`),l=D(e,t,c.map(e=>s.val(e))),u=s`CASE WHEN ${a} = 'toolResult' THEN ${D(e,l,[s.lit(`$.message.details`)])} ELSE ${l} END`,d=i?s`CASE WHEN ${i} IS NOT NULL AND ${a} = 'toolResult' THEN ${A(e,u,s.lit(`$.message.content`),j(e,[T(e,{type:s.lit(`text`),text:i})]),!0)} ELSE ${u} END`:u;return s`CASE WHEN NOT ${o} THEN ${projectDeepModelContextSql(e,t,!1,n,i)} WHEN ${n} = 1 THEN ${D(e,d,[s.lit(`$.message.providerReplay`)])} ELSE ${d} END`}function contentPropertySql(e,t){return s`CASE WHEN typeof(key) = 'integer' AND key < 8 THEN json_extract(${e}, fullkey || ${`.${t}`}) ELSE json_extract(value, ${`$.${t}`}) END`}function jsonMemberValue(e){let t=s.ref(`${e}.type`),n=s.ref(`${e}.value`);return s`CASE ${t} WHEN 'object' THEN json(${n}) WHEN 'array' THEN json(${n}) WHEN 'true' THEN json('true') WHEN 'false' THEN json('false') ELSE ${n} END`}function projectTranscriptPayloadNavigationSql(e,t){let n=s.ref(`message_member.value`),r=E(e,n,[`runId`,`steerTargetRunId`,`contextFreeCommand`]),i=s`(SELECT json_group_object(message_member.key, CASE WHEN message_member.key = '__openclaw' AND message_member.type = 'object' THEN json(${r}) ELSE ${jsonMemberValue(`message_member`)} END) FROM json_each(root_member.value) AS message_member WHERE message_member.key IN ('role', 'idempotencyKey', 'provenance', 'excludeFromContext', '__openclaw'))`;return s`(SELECT json_group_object(root_member.key, CASE WHEN root_member.key = 'message' AND root_member.type = 'object' THEN json(${i}) ELSE ${jsonMemberValue(`root_member`)} END) FROM json_each(${t}) AS root_member WHERE root_member.key IN (${s.join([...H,`message`])}))`}function projectTranscriptNavigationSql(e,t){return s`CASE WHEN ${w(e,t)} THEN ${E(e,t,V)} ELSE ${t} END`}function projectResetBoundaryNavigationSql(e,t){let n=E(e,t,[...V,`timestamp`,`firstKeptEntryId`,`customType`,`display`]);return s`CASE WHEN ${w(e,t)} THEN CASE WHEN ${k(e,t)} = 'object' THEN ${A(e,n,s.lit(`$.message`),T(e,{role:M(e,t,s.lit(`$.message.role`))}),!0)} ELSE ${t} END ELSE ${t} END`}function systemUpdateKindSql(e,t){return s`CASE WHEN ${M(e,t,s.lit(`$.customType`))} = 'openclaw.system-update' AND ${M(e,t,s.lit(`$.details.kind`))} IN ('prompt-update', 'runtime-context') THEN ${M(e,t,s.lit(`$.details.kind`))} ELSE NULL END`}function projectModelContextNavigationSql(e,t,i,a=O(e,t)){if(r(e)){let n=s.ref(`nav_parts.event`),r=s.ref(`nav_parts.message`),a=s.ref(`nav_parts.content`),o=i??s`${n} ->> 'type'`,c=w(e,t);return s`CASE WHEN ${c} THEN ( WITH nav_input AS MATERIALIZED (SELECT (CASE WHEN ${c} THEN ${t} END)::jsonb AS event), nav_parts AS MATERIALIZED (SELECT event, event -> 'message' AS message, event #> '{message,content}' AS content FROM nav_input) SELECT ${postgresModelNavigationSql(n,r,a,o)}::text FROM nav_parts) ELSE ${t} END`}let o=i??M(e,t,s.lit(`$.type`)),c=E(e,t,H),l=n()?s`jsonb_extract(${t}, '$.message')`:s`json_extract(${t}, '$.message')`,u=E(e,l,U),d=systemUpdateKindSql(e,l),f=systemUpdateKindSql(e,t),p=s`json_set(${c}, '$.content', json('[]'))`,m=s`(SELECT json_group_array(json_object( 'type', ${contentPropertySql(t,`type`)}, 'id', ${contentPropertySql(t,`id`)}, 'name', ${contentPropertySql(t,`name`)})) FROM json_each(${t}, '$.message.content') WHERE type = 'object' AND ${contentPropertySql(t,`type`)} IN ('toolCall', 'toolUse', 'functionCall'))`,h=s`COALESCE(json_extract(${t}, ${`$.message.details.${L}`}), 0) = 1 OR EXISTS ( SELECT 1 FROM json_each(${t}, '$.message.content') WHERE type = 'object' AND ${contentPropertySql(t,`type`)} = 'text' AND ${contentPropertySql(t,`text`)} = ${R})`,g=s`CASE ${o} WHEN 'message' THEN json_set(${c}, '$.message', json_set(${u}, '$.content', json(${m}), '$.command', '', '$.output', '', '$.providerReplay', json_object('type', json_extract(${t}, '$.message.providerReplay.type')), '$.details', json_patch(json_object(${L}, json(CASE WHEN (${h}) THEN 'true' ELSE 'false' END)), CASE WHEN ${d} IS NULL THEN json('{}') ELSE json_object('kind', ${d}) END))) WHEN 'custom_message' THEN CASE WHEN ${f} IS NULL THEN ${p} ELSE json_set(${p}, '$.details', json_object('kind', ${f})) END WHEN 'custom' THEN CASE WHEN ${M(e,t,s.lit(`$.customType`))} = 'openclaw.system-prompt' THEN json_set(${c}, '$.data', json_object('restart', json(CASE WHEN json_type(${t}, '$.data.restart') = 'true' THEN 'true' ELSE 'false' END))) ELSE ${c} END WHEN 'compaction' THEN json_set(${c}, '$.summary', '') WHEN 'branch_summary' THEN json_set(${c}, '$.summary', '') ELSE ${c} END`;return s`CASE WHEN ${a} THEN ${g} ELSE ${projectDeepModelContextSql(e,t,!0)} END`}function projectPostgresModelContextRowsSql(e){let t=s.ref(`context_projected.event`),n=s.ref(`context_projected.message`),r=s.ref(`context_projected.content`),i=s`${t} ->> 'type'`,a=postgresModelEventSql(s.ref(`context_parts.event`),s`context_parts.message ->> 'role'`);return s`( WITH context_input AS MATERIALIZED ( SELECT seq, CASE WHEN navigation_json IS NULL AND pg_input_is_valid(event_json, 'jsonb') THEN event_json::jsonb END AS event, navigation_json::jsonb AS metadata FROM (${e}) AS selected ), context_parts AS MATERIALIZED ( SELECT *, event -> 'message' AS message, event #> '{message,content}' AS content FROM context_input ), context_projected AS MATERIALIZED ( SELECT *, ${a} AS model FROM context_parts ) SELECT seq, CASE WHEN metadata IS NULL THEN ${postgresModelNavigationSql(t,n,r,i)}::text ELSE (metadata -> 'model')::text END AS navigation_json, CASE WHEN metadata IS NULL THEN octet_length(model::text) ELSE (metadata ->> 'modelBytes')::double precision END AS model_bytes, CASE WHEN metadata IS NULL THEN octet_length((model #- '{message,providerReplay}')::text) ELSE (metadata ->> 'modelWithoutCheckpointBytes')::double precision END AS retained_bytes FROM context_projected ORDER BY seq )`}function postgresModelEventSql(e,t){let n=e;for(let e of z)n=s`(${n}::jsonb #- ${s.lit(`{message,__openclaw,${e}}`)}::text[])`;return s`CASE WHEN ${t} = 'toolResult' THEN ${n} #- '{message,details}' ELSE ${n} END`}function postgresNavigationObjectSql(e,t){return s`( SELECT coalesce(jsonb_object_agg(key, value), '{}'::jsonb) FROM jsonb_each(CASE WHEN jsonb_typeof(${e}) = 'object' THEN ${e} ELSE '{}'::jsonb END) WHERE key IN (${s.join(t.map(e=>s.lit(e)))}) )`}function postgresModelNavigationSql(e,t,n,r){let i=postgresNavigationObjectSql(e,H),a=postgresNavigationObjectSql(t,U),o=s`jsonb_array_elements( CASE WHEN jsonb_typeof(${n}) = 'array' THEN ${n} ELSE '[]'::jsonb END)`,c=s`( SELECT coalesce(jsonb_agg(jsonb_build_object('type', value ->> 'type', 'id', value ->> 'id', 'name', value ->> 'name')), '[]'::jsonb) FROM ${o} WHERE jsonb_typeof(value) = 'object' AND value ->> 'type' IN ('toolCall', 'toolUse', 'functionCall'))`,l=s`coalesce((${t} #> ${s.lit(`{details,${L}}`)}::text[])::text, 'false') IN ('true', '1') OR EXISTS ( SELECT 1 FROM ${o} WHERE value ->> 'type' = 'text' AND value ->> 'text' = ${R})`,u=s`CASE WHEN ${t} ->> 'customType' = 'openclaw.system-update' AND ${t} #>> '{details,kind}' IN ('prompt-update', 'runtime-context') THEN ${t} #>> '{details,kind}' END`,d=s`CASE WHEN ${e} ->> 'customType' = 'openclaw.system-update' AND ${e} #>> '{details,kind}' IN ('prompt-update', 'runtime-context') THEN ${e} #>> '{details,kind}' END`;return s`CASE ${r} WHEN 'message' THEN ${i} || jsonb_build_object('message', ${a} || jsonb_build_object( 'content', ${c}, 'command', '', 'output', '', 'providerReplay', jsonb_build_object('type', ${t} #>> '{providerReplay,type}'), 'details', jsonb_build_object(${s.lit(L)}, (${l})) || CASE WHEN ${u} IS NULL THEN '{}'::jsonb ELSE jsonb_build_object('kind', ${u}) END)) WHEN 'custom_message' THEN ${i} || jsonb_build_object('content', '[]'::jsonb) || CASE WHEN ${d} IS NULL THEN '{}'::jsonb ELSE jsonb_build_object('details', jsonb_build_object('kind', ${d})) END WHEN 'custom' THEN CASE WHEN ${e} ->> 'customType' = 'openclaw.system-prompt' THEN ${i} || jsonb_build_object('data', jsonb_build_object('restart', coalesce((${e} #> '{data,restart}')::text, 'false') = 'true')) ELSE ${i} END WHEN 'compaction' THEN ${i} || jsonb_build_object('summary', '') WHEN 'branch_summary' THEN ${i} || jsonb_build_object('summary', '') ELSE ${i} END`}const G={id:h().min(1),parentId:m([h(),_()]).optional(),timestamp:h().optional(),appendMode:u().optional()},K=p({kind:f(`canonical`),hasParentId:d(),entry:v(`type`,[p({...G,type:f(`message`),assistantResponseId:h().optional(),assistantRunId:h().optional()}),p({...G,type:f(`custom_message`),customType:h().min(1)}),p({...G,type:f(`label`),targetId:h().min(1),label:h().optional()}),p({...G,type:g([`thinking_level_change`,`model_change`,`compaction`,`reset`,`branch_summary`,`custom`,`session_info`])})])}).refine(({entry:e,hasParentId:t})=>t===(e.parentId!==void 0));function projectSessionTranscriptReportFacts(e){let{entry:t,recognized:n}=y(e,3);if(!n||t.type===`session`){let t=b(e);if(t)return{kind:`leaf`,entry:t};let n=S(e);return n?{kind:`link`,...n}:{kind:`ignored`}}let r={id:t.id,parentId:t.parentId,timestamp:t.timestamp,appendMode:t.appendMode},i=Object.hasOwn(t,`parentId`);return t.type===`label`?{kind:`canonical`,hasParentId:i,entry:{...r,type:t.type,targetId:t.targetId,label:t.label}}:t.type===`custom_message`?{kind:`canonical`,hasParentId:i,entry:{...r,type:t.type,customType:t.customType}}:t.type===`message`?{kind:`canonical`,hasParentId:i,entry:{...r,type:t.type,...t.message.role===`assistant`?{assistantRunId:P(t.message),...typeof t.message.responseId==`string`?{assistantResponseId:t.message.responseId}:{}}:{}}}:{kind:`canonical`,hasParentId:i,entry:{...r,type:t.type}}}function decodeSessionTranscriptReportFacts(t){if(e(t))switch(t.kind){case`canonical`:{let e=K.safeParse(t);return e.success?e.data:void 0}case`leaf`:{if(!e(t.entry))return;let n=b({...t.entry,type:`leaf`});return n?{kind:`leaf`,entry:n}:void 0}case`link`:{let e=S(t);return e?{kind:`link`,...e}:void 0}case`ignored`:return{kind:`ignored`};default:return}}const q=4194304,J=`openclaw_transcript_payload_decode`,Y=/* @__PURE__ */ new WeakSet,X=new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});function registerDecoder(e){Y.has(e)||(e.function(J,{deterministic:!0,directOnly:!0},decodeCompressedTranscriptPayload),Y.add(e))}function decodeCompressedTranscriptPayload(e,t){if(!(e instanceof Uint8Array)||e.byteLength===0||e.byteLength>4194304||typeof t!=`number`||!Number.isSafeInteger(t)||t<1||t>4194304)throw Error(`Invalid compressed transcript payload bounds`);let n=F().decompress(e,t);if(n.byteLength!==t)throw Error(`Compressed transcript payload length does not match its recorded UTF-8 size`);return X.decode(n)}function readTranscriptPayload(e){return e.event_json??decodeCompressedTranscriptPayload(e.event_zstd,e.event_utf8_bytes)}function transcriptEventJsonSql(e,t=`transcript_events`){if(r(e))return s.ref(`${t}.event_json`);registerDecoder(e);let n=s.ref(`${t}.event_json`),i=s.ref(`${t}.event_zstd`),o=s.ref(`${t}.event_utf8_bytes`),c=a(e).fn(J,[i,o]);return s`coalesce(${n}, ${c})`}const Z=/* @__PURE__ */ new Set([`session`,`message`,`reset`,`compaction`,`custom_message`,`custom`]),Q=/* @__PURE__ */ new Set([`openclaw.runtime-context`,`openclaw.cache-ttl`]),$=/* @__PURE__ */ new Set([`user`,`assistant`,`toolResult`,`system`]);function discriminator(e,t){let n=C(e);return typeof n==`string`&&t.has(n)?n:null}function deriveTranscriptPredicateFields(e){let t=N(e,[`type`,`customType`,`display`,`message`]);if(!t.valid||t.maximumDepth>1e3)return{navigation_type:null,navigation_custom_type:null,navigation_display:0,message_role:null,navigation_last_type:null,navigation_last_custom_type:null,navigation_valid:0};let n=t.first.get(`message`),r=n?.kind===`object`?N(n.text,[`role`]).first.get(`role`):void 0;return{navigation_type:discriminator(t.first.get(`type`),Z),navigation_custom_type:discriminator(t.first.get(`customType`),Q),navigation_display:+(C(t.first.get(`display`))===!0),message_role:discriminator(r,$),navigation_last_type:discriminator(t.last.get(`type`),Z),navigation_last_custom_type:discriminator(t.last.get(`customType`),Q),navigation_valid:1}}function assertTranscriptNavigationValid(e){if(e===0)throw Error(`malformed JSON in transcript navigation; run openclaw doctor to inspect the agent database`)}function readTranscriptStorageEncoding(e){if(r(e))return`UTF-8`;let t=i(e);if(!t)throw Error(`Transcript payload preparation requires admitted SQLite schema facts`);return t.textEncoding}function navigationProjection(e,t,n,r){return s`CASE WHEN json_valid(${r}) AND json_valid(${n}) THEN CASE WHEN json_type(${t}) != 'object' OR coalesce(json_type(${t}, '$.message'), 'null') NOT IN ('object', 'null') THEN NULL ELSE json_object('version', 1, 'report', json(${n}), 'navigation', json(${projectTranscriptPayloadNavigationSql(e,t)}), 'reset', json(${projectResetBoundaryNavigationSql(e,r)}), 'model', json(${projectModelContextNavigationSql(e,t,void 0,s.lit(1))}), 'modelBytes', octet_length(${projectModelContextEventSql(e,t,s.lit(0),void 0,void 0,s.lit(1))}), 'modelWithoutCheckpointBytes', octet_length(${projectModelContextEventSql(e,t,s.lit(1),void 0,void 0,s.lit(1))}), 'withoutCustomDataBytes', octet_length(json_remove(${t}, '$.data'))) END ELSE NULL END`}const ee=c(e=>o(e,t=>{let r=a(e),i=r.selectFrom(r.selectNoFrom([t(e=>e.eventJson).as(`event_json`),t(e=>e.reportJson).as(`report_json`)]).as(`input`)).select([`input.event_json`,`input.report_json`]).select(e=>n()?s`CASE WHEN json_valid(${e.ref(`input.event_json`)}) THEN jsonb(${e.ref(`input.event_json`)}) ELSE ${e.ref(`input.event_json`)} END`.as(`event_projection`):e.ref(`input.event_json`).as(`event_projection`)),o=s`CASE WHEN json_valid(metadata.navigation_json) AND octet_length(metadata.navigation_json) <= ${16384} THEN metadata.navigation_json ELSE NULL END`;return r.with(e=>e(`source`).notMaterialized(),()=>i).with(e=>e(`metadata`).materialized(),t=>t.selectFrom(`source`).select(t=>navigationProjection(e,t.ref(`source.event_projection`),t.ref(`source.report_json`),t.ref(`source.event_json`)).as(`navigation_json`))).selectFrom(`metadata`).select(o.as(`navigation_json`))}));function prepareTranscriptPayload(e,t,n,i=readTranscriptStorageEncoding(e)){let a=Buffer.byteLength(t,`utf8`),o=i===`UTF-8`,s={...deriveTranscriptPredicateFields(t),event_json:t,event_zstd:null,event_utf8_bytes:o?a:null,navigation_json:null};if(r(e)||!o||a>4194304||t.includes(`\\u`)||t.includes(`\0`))return s;let c=F();if(a<1024||!t.isWellFormed())return s;let l=Buffer.from(t,`utf8`),u=c.compress(l,1,!0),d=a-Math.max(64,Math.ceil(a/10));if(u.byteLength>d)return s;let f;try{let e=n===void 0?JSON.parse(t):n;if(x([e]))return s;f=JSON.stringify(projectSessionTranscriptReportFacts(e))}catch{return s}let p=ee(e)({eventJson:t,reportJson:f})?.navigation_json??null;return p===null||u.byteLength+Buffer.byteLength(p,`utf8`)>d?s:{...s,event_json:null,event_zstd:u,navigation_json:p}}function transcriptEventNavigationSql(e,t=`transcript_events`){return storedProjectionSql(e,`navigation`,s.ref(`${t}.event_json`),t)}function transcriptPredicateSql(e,t,n=`transcript_events`){let i=s.ref(`${n}.${t}`);if(r(e))return i;let a=s.ref(`${n}.navigation_type`),o=s.ref(`${n}.navigation_valid`),c=s.ref(`${n}.event_json`),l=s.ref(`${n}.navigation_json`),u=s`coalesce(${c}, ${M(e,l,s.lit(`$.navigation`),`json`)})`,d=O(e,u),f=s`CASE WHEN ${d} THEN ${u} ELSE '{}' END`,p;if(t===`navigation_valid`)p=s`coalesce(${d}, 0)`;else if(t===`navigation_display`)p=s`CASE WHEN json_type(${f}, '$.display') = 'true' THEN 1 ELSE 0 END`;else{let n=t===`navigation_custom_type`||t===`navigation_last_custom_type`,r=t===`message_role`?`$.message.role`:n?`$.customType`:`$.type`,i=t===`navigation_last_type`||t===`navigation_last_custom_type`?s`(SELECT value FROM json_each(${f}) WHERE key = ${s.lit(n?`customType`:`type`)} ORDER BY id DESC LIMIT 1)`:M(e,f,s.lit(r)),a=t===`message_role`?[`user`,`assistant`,`toolResult`,`system`]:n?[`openclaw.runtime-context`,`openclaw.cache-ttl`]:[`session`,`message`,`reset`,`compaction`,`custom_message`,`custom`];p=s`CASE WHEN ${i} IN (${s.join(a.map(e=>s.lit(e)))}) THEN ${i} END`}return s`CASE WHEN ${a} IS NOT NULL OR ${o} = 0 THEN ${i} ELSE ${p} END`}function transcriptEventRunIdSql(e,t=`transcript_events`){let n=transcriptEventNavigationSql(e,t);return s`CASE WHEN ${w(e,n)} THEN ${M(e,n,s.lit(`$.message.__openclaw.runId`))} END`}function storedProjectionSql(e,t,n,r){let i=s.ref(`${r}.navigation_json`);return s`CASE WHEN ${i} IS NULL THEN ${n} ELSE ${M(e,i,s.val(`$.${t}`),`json`)} END`}function transcriptEventResetNavigationSql(e,t=`transcript_events`){return storedProjectionSql(e,`reset`,projectResetBoundaryNavigationSql(e,s.ref(`${t}.event_json`)),t)}function transcriptEventModelNavigationSql(e,t=`transcript_events`,n){return storedProjectionSql(e,`model`,projectModelContextNavigationSql(e,s.ref(`${t}.event_json`),n),t)}function transcriptEventModelBytesSql(e,t){let n=s.ref(`transcript_events.navigation_json`),r=s.ref(`transcript_events.event_json`);return s`CASE WHEN ${n} IS NULL THEN octet_length(${projectModelContextEventSql(e,r,t)}) ELSE ${M(e,n,s`CASE WHEN ${t} = 1 THEN '$.modelWithoutCheckpointBytes' ELSE '$.modelBytes' END`,`number`)} END`}function transcriptEventWithoutCustomDataBytesSql(e,t=`transcript_events`){let n=s.ref(`${t}.navigation_json`),r=s.ref(`${t}.event_json`);return s`CASE WHEN ${n} IS NULL THEN octet_length(${D(e,r,[s.lit(`$.data`)])}) ELSE ${M(e,n,s.lit(`$.withoutCustomDataBytes`),`number`)} END`}function transcriptEventUtf8BytesSql(e=`transcript_events`){return s.ref(`${e}.event_utf8_bytes`)}export{projectModelContextMessages as C,projectSessionModelContextEntry as S,projectModelContextEventSql as _,transcriptEventNavigationSql as a,projectSessionModelContextNavigation as b,transcriptEventUtf8BytesSql as c,assertTranscriptNavigationValid as d,q as f,projectSessionTranscriptReportFacts as g,decodeSessionTranscriptReportFacts as h,transcriptEventModelNavigationSql as i,transcriptEventWithoutCustomDataBytesSql as l,transcriptEventJsonSql as m,readTranscriptStorageEncoding as n,transcriptEventResetNavigationSql as o,readTranscriptPayload as p,transcriptEventModelBytesSql as r,transcriptEventRunIdSql as s,prepareTranscriptPayload as t,transcriptPredicateSql as u,projectPostgresModelContextRowsSql as v,stripToolResultDetails as w,hydrateSessionModelContextEntry as x,projectTranscriptNavigationSql as y};