UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

2 lines • 11.2 kB
import{i as e}from"./transcript-record-coerce-CPLgmAk9.mjs";import{n as t}from"./transcript-state-dir-DEo0wD2Q.mjs";import{u as n}from"./transcript-sqlite-post-commit-B_pko32i.mjs";import{t as r}from"./transcript-session-transcript-cold-error-B2vVZQFT.mjs";import{n as i}from"./transcript-agent-id-DmscQLD6.mjs";import{f as a,m as o}from"./transcript-store-entry-Ch3rW6qd.mjs";import{o as s}from"./transcript-sqlite-transaction-CBQXI8WC.mjs";import{n as c,o as l,t as u}from"./transcript-artifacts-BcxHhf8q.mjs";import{n as d}from"./transcript-openclaw-agent-db-readonly-BfbPmTwU.mjs";import{i as f}from"./transcript-session-accessor.sqlite-scope-helpers-LCM13IZK.mjs";import{s as p}from"./transcript-chat-message-content-DeOIjx3p.mjs";import{D as m,L as h,V as g}from"./transcript-chat-display-projection.canvas-BVwGQyPV.mjs";import{o as _}from"./transcript-internal-runtime-context-Blo7FWkI.mjs";import{y as v}from"./transcript-tool-call-xml-BuZjCNyQ.mjs";import{i as y,r as b,t as x}from"./transcript-session-accessor.sqlite-export-read-BEguUhTu.mjs";import"./transcript-session-accessor.sqlite-scope-6_lvO2un.mjs";import{c as S}from"./transcript-session-accessor.sqlite-read-scope-B5jiReWs.mjs";import{t as C}from"./transcript-session-accessor.sqlite-transcript-stats-C5izCjEb.mjs";import{r as w}from"./transcript-session-transcript-read-fence-Fb_G9Rx1.mjs";import{t as T}from"./transcript-session-reset-recall-CCEdU9Hm.mjs";import"./transcript-bash-tools.exec-output-DxYULvv8.mjs";import{a as E,i as D,n as O,r as k,t as A}from"./transcript-session-entry-projection-6y7WYDIH.mjs";import{t as j}from"./transcript-session-provenance-B1NPzgd1.mjs";import{channel as M}from"node:diagnostics_channel";import N from"node:path";const P=/^\[cron:[^\]]+\]\s*/,F=Symbol.for(`openclaw.memory.sessionResetRecallCutoff`);function readSessionEntryResetRecallCutoff(e){let t=Object.getOwnPropertyDescriptor(e,F)?.value;return!t||typeof t!=`object`||!(`state`in t)?{state:`invalid`}:t.state===`absent`||t.state===`invalid`?{state:t.state}:t.state===`valid`&&`cutoffLine`in t&&typeof t.cutoffLine==`number`?{state:`valid`,cutoffLine:t.cutoffLine}:{state:`invalid`}}function attachSessionEntryResetRecallCutoff(e,t){return Object.defineProperty(e,F,{configurable:!1,enumerable:!1,value:t,writable:!1}),e}function isUsageCountedSessionArchiveTranscriptPath(e){let t=N.basename(e);return c(t)&&u(t)&&l(t)!==null}function hasDreamingNarrativeIdentity(e){return typeof e==`string`&&o(e)}function isDreamingNarrativeGeneratedRecord(t){let n=e(t);if(!n)return!1;let r=e(n.data);if(n.type===`custom`&&n.customType===`openclaw:bootstrap-context:full`&&typeof r?.runId==`string`&&r.runId.startsWith(`dreaming-narrative-`))return!0;let i=n.type===`message`?e(n.message):void 0,a=e(i?.__openclaw);return hasDreamingNarrativeIdentity(n.runId)||hasDreamingNarrativeIdentity(n.sessionKey)||hasDreamingNarrativeIdentity(r?.runId)||hasDreamingNarrativeIdentity(r?.sessionKey)||(i?.role===`assistant`||i?.role===`toolResult`)&&hasDreamingNarrativeIdentity(a?.runId)}function hasCronRunSessionKey(e){return typeof e==`string`&&a(e)}function isCronRunGeneratedRecord(t){let n=e(t);return hasCronRunSessionKey(n?.sessionKey)||hasCronRunSessionKey(e(n?.data)?.sessionKey)}function sessionPathForSessionIdentity(e,t){return N.join(`sessions`,i(e),`${t}.jsonl`).replace(/\\/g,`/`)}function normalizeSessionText(e){return e.replace(/\s+/g,` `).trim()}const I=/^System(?: \(untrusted\))?: \[[^\]]+\]\s*/;function sanitizeSessionText(e,t){let n=t===`user`?v(e):e,r=normalizeSessionText(_(n));return!r||t===`user`&&(I.test(r)||P.test(r)||h({role:t,content:r},g))||t===`assistant`&&r===`HEARTBEAT_OK`||isExecCompletionEvent(r.replace(I,``).trim())?null:r}function resolveSessionEntryParseYieldLines(e){let t=e.parseYieldEveryLines;return typeof t==`number`&&Number.isFinite(t)?Math.max(1,Math.floor(t)):250}function sqliteSessionFileState(e,t,n,r){return{absPath:e,path:sessionPathForSessionIdentity(t.agentId,t.sessionId),mtimeMs:r??n.maxSeq,revisionMs:n.lastMutationAtMs??n.maxSeq,size:n.sizeBytes}}async function yieldSessionEntryParseIfNeeded(e,t){e>0&&e%t===0&&await new Promise(e=>{setImmediate(e)})}function isExecCompletionEvent(e){let t=e.trim();if(/^exec finished(?::|\s*\()/i.test(t))return!0;let n=/^exec (?:completed|failed) \([a-z0-9_-]{1,64}, (?:code -?\d+|signal [^),]+)(?:, [0-9a-z]+)?\)(?: :: [\s\S]*|(?:, last \d+ of \d+ output chars \([^)]*\))?: [\s\S]*| with no output\.(?: ([\s\S]+))?|\n\n([\s\S]+))?$/i.exec(t);return!!(n&&[n[1],n[2]].every(e=>e===void 0||e===`The command was terminated, but external side effects may already have completed. Verify the resulting state before retrying. Do not automatically rerun commands unless repeating them is safe. Use a higher timeout only when the command is known to be safe to retry.`))}function renderSessionEntrySnapshot(e,t,n,r={}){return renderSessionEntry(e,t,{...sqliteSessionFileState(e,t,n.stats,t.updatedAtMs),kind:`sqlite`,records:n.events,sessionKey:n.sessionKey},r)}async function renderSessionEntry(t,n,r,i={}){let{mtimeMs:s,size:c,path:l}=r,u=r.kind===`sqlite`?r:null,d=r.kind===`file`?r.raw:``,f=r.kind===`file`?r.classification:null,h=O(i.prefixLineCount),g=u?T():void 0,_=/* @__PURE__ */ new Set,v,y=0,b=0,x=!1,openPage=()=>v??={startLine:b,lines:[],lineMap:[],messageTimestampsMs:[],lineProvenance:[]},flushPage=async e=>{if(!v||!e&&y<524288)return;let t=v;v=void 0,y=0,(t.lines.length>0||t.messages?.length)&&(x||=t.lines.length>0,await i.page?.(t))},S=i.pageMessages?(e,t)=>{let n=openPage();(n.messages??=[]).push({message:e,observedAt:t}),y+=JSON.stringify(e)?.length??0}:n.onTranscriptMessage,C=resolveSessionEntryParseYieldLines(n),w=n.sessionKey?void 0:u?.sessionKey,D=n.generatedByDreamingNarrative??(w?o(w):void 0)??f?.generatedByDreamingNarrative??!1,M=n.generatedByCronRun??(w?a(w):void 0)??f?.generatedByCronRun??!1,N=n.sessionKind??`unknown`,P=isUsageCountedSessionArchiveTranscriptPath(t),F=!1,I=!1,L=`untrusted`,R=u?u.records[Symbol.iterator]():void 0;for(let t=0,n=0;;t++){await yieldSessionEntryParseIfNeeded(t,C);let r;if(R){let e=R.next();if(e.done)break;r=e.value,g.observe(r)}else{if(n>d.length)break;let e=d.indexOf(` `,n),t=e===-1?d.length:e,i=d.slice(n,t);if(n=e===-1?d.length+1:e+1,!i.trim())continue;try{r=JSON.parse(i)}catch{continue}}let a=!D&&isDreamingNarrativeGeneratedRecord(r),o=!M&&P&&isCronRunGeneratedRecord(r);(a||o)&&(D||=a,M||=o,h.reset(),_.clear(),b=0,v&&(v.lines.length=0,v.lineMap.length=0,v.messageTimestampsMs.length=0,v.lineProvenance.length=0,v.startLine=0),x&&(x=!1,await i.reset?.()));let c=e(r);if(c?.type!==`message`)continue;let l=e(c.message);if(!l||typeof l.role!=`string`||l.role!==`user`&&l.role!==`assistant`)continue;let u=k(c,l);S?.(l,Math.max(0,Math.floor(u||s)));let f=e(l.provenance),w=l.role===`user`&&f?.kind===`internal_system`&&f.sourceTool===`heartbeat`;if(l.role===`user`&&(F=w,I=f?.kind===`internal_system`&&(f.sourceTool===`memory_search`||f.sourceTool===`memory_get`),L=j(l,L)),l.role===`user`&&m(l)||F||I||l.role===`user`&&f?.kind===`internal_system`&&f.sourceTool===`exec`||D||M||`display`in l&&l.display===!1){await flushPage(!1);continue}let T=p(l,A(l.content)??void 0),O=T===void 0?null:sanitizeSessionText(T,l.role);if(!O){await flushPage(!1);continue}let z=l.role===`user`?`User`:`Assistant`,B=E(z,O),V={sourceLine:t+1,timestampMs:u,provenance:{originClass:j(l,L),sessionKind:N,observedAt:Math.max(0,Math.floor(u||s))}};h.append(B,V),B.length>0&&_.add(V.provenance.originClass);for(let e of B){let t=openPage();t.lines.push(e),t.lineMap.push(V.sourceLine),t.messageTimestampsMs.push(u),t.lineProvenance.push(V.provenance),b++,y+=e.length+32,await flushPage(!1)}}await flushPage(!0);let z=g?.current()??{state:`absent`},{hash:B,prefixHash:V}=h.finish(z);return attachSessionEntryResetRecallCutoff({path:l,absPath:t,mtimeMs:s,...u?{revisionMs:u.revisionMs}:{},size:c,hash:B,...V?{prefixHash:V}:{},lineCount:h.lineCount,lineOriginClasses:[..._].toSorted(),sessionKind:N,...D?{generatedByDreamingNarrative:!0}:{},...M?{generatedByCronRun:!0}:{}},z)}const L=new t(16,{maxBytes:8388608,sizeOf:e=>e.stats.sizeBytes});M(`openclaw.memory.critical`).subscribe(()=>L.clear());const R=4194304;async function deliverSessionMemoryEntries(e,t,n){if(!t)throw Error(`Session exports require their host delivery channel`);return t.consumeInput(),await streamSessionMemoryEntries(e,async e=>{n.throwIfCancelled(),(await t.request({kind:`session-entries`,...e})).consumed(),n.throwIfCancelled()}),{entries:[]}}async function streamSessionMemoryEntries(e,t){let r=/* @__PURE__ */ new Map;for(let[t,{options:n}]of e.entries()){let e=S(n),i=JSON.stringify([e.databaseAgentId??e.agentId,e.path]),a=r.get(i)??[];a.push({index:t,resolved:e}),r.set(i,a)}for(let i of r.values()){let r=i.length>1?d(e=>({sizes:C(e,i.map(({resolved:e})=>e.sessionId)),deferAboveBytes:n(e.db)?1/0:R}),f(i[0].resolved)):void 0,batchBytes=e=>{if(!r?.found)return 0;let t=r.value.sizes[e].sizeBytes;return t>r.value.deferAboveBytes?0:t};for(let n=0;n<i.length;){let r=n,a=0;for(;r<i.length&&r-n<32&&(r===n||a+batchBytes(r)<=R);)a+=batchBytes(r),r++;let o=i.slice(n,r),c=o.map(({index:t,resolved:n})=>{let r=e[t],i=r.messages?void 0:L.peek(snapshotKey(r));return{resolved:n,scope:r.options,admission:r.admission,options:{projectEvent:r.messages?void 0:projectEvent,previous:i?.generation!=null&&i.throughSeq!==void 0?{events:i.events,generation:i.generation,throughSeq:i.throughSeq}:null}}}),l=d(e=>s(e.db,()=>b(e,c,{deferAboveBytes:R}),{operationLabel:`session transcript export batch`}),f(i[0].resolved));for(let[n,{index:r}]of o.entries()){let i=e[r],a=l.found?l.value.shift():null;a!==`cold`&&!i.messages&&retainSnapshot(snapshotKey(i),a),await t({index:r,value:await streamSessionMemoryEntry(r,i,c[n].options,a,t)})}n=r}}}function projectEvent(e){return D(e,p)}async function streamSessionMemoryEntry(e,t,n,i,a){let o=!1,reset=async()=>{o&&(o=!1,await a({index:e,reset:!0,resetMessages:!0}))},s={prefixLineCount:t.prefixLineCount,pageMessages:t.messages,page:t.pages||t.messages?async n=>{let r=t.pages&&n.lines.length>0;o=!0,await a({index:e,page:r?n:{startLine:n.startLine,lines:[],lineMap:[],messageTimestampsMs:[],lineProvenance:[],...n.messages?{messages:n.messages}:{}}})}:void 0,reset:async()=>{o&&await a({index:e,reset:!0})}};if(i===`cold`)return{cold:!0};for(let e=1;;e++)try{let r=e===1&&!i?.deferred?i&&{snapshot:i,events:i.events}:openDeferredExport(t,n,e===1?i??void 0:void 0),a=r?await renderSessionEntrySnapshot(t.absPath,t.options,{...r.snapshot,events:r.events},s):null;return{summary:a,resetRecallCutoff:a?readSessionEntryResetRecallCutoff(a):{state:`absent`}}}catch(t){if(t instanceof r)return await reset(),{cold:!0};if(!(t instanceof y)||e>=3)throw t;await reset()}}function openDeferredExport(e,t,n){let r=w(e.admission,()=>x(e.options,t,n));if(!r||!e.admission)return r;let i=r.events,a=e.admission;return{snapshot:r.snapshot,events:{[Symbol.iterator]:()=>({next:()=>w(a,()=>i.next())})}}}function snapshotKey({options:e}){return JSON.stringify([e.storePath,e.agentId,e.sessionId])}function retainSnapshot(e,t){L.delete(e),t&&t.stats.sizeBytes<=R&&L.set(e,t)}export{deliverSessionMemoryEntries};