UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1 lines • 13.7 kB
import{a as e,o as t}from"./transcript-record-coerce-CPLgmAk9.mjs";import{i as n}from"./transcript-global-singleton-DIJgobpU.mjs";import{c as r,m as i}from"./transcript-agent-creation-claim-Da8lP1e6.mjs";import"./transcript-worker-cpu-DFlTFgab.mjs";import{n as a}from"./transcript-path-guards-u0N7Z9_x.mjs";import{r as o}from"./transcript-sqlite-error-diagnostics-CLL4Z7ly.mjs";import"./transcript-config-env-vars-DvUkP5Hz.mjs";import"./transcript-state-dir-DEo0wD2Q.mjs";import{t as s}from"./transcript-errors-B-oBGrpW.mjs";import{a as c,d as l,f as u,o as d,p as f,s as p}from"./transcript-sqlite-post-commit-B_pko32i.mjs";import"./transcript-sqlite-schema-facts-C1_zV4Yg.mjs";import{n as m}from"./transcript-agent-id-DmscQLD6.mjs";import"./transcript-openclaw-agent-db.paths-DbFl2s5M.mjs";import"./transcript-session-key-MDDhuEG9.mjs";import"./transcript-agent-deletion-journal-status-BsvZaPJC.mjs";import{a as h,i as g,m as _,r as v}from"./transcript-kysely-sync-CAP5xe3V.mjs";import{o as y}from"./transcript-sqlite-transaction-CBQXI8WC.mjs";import{u as b}from"./transcript-agent-scope-config-l-KZcQvf.mjs";import{d as x}from"./transcript-openclaw-agent-db-resources-W6NYYBYU.mjs";import{m as S}from"./transcript-openclaw-quarantine-store-DP1LZEnM.mjs";import"./transcript-session-row-changes-DGiwEF1b.mjs";import{P as C}from"./transcript-openclaw-state-db-cache-kzfc9rd-.mjs";import{a as w,i as T}from"./transcript-openclaw-state-db-schema-helpers-B1k_oHgC.mjs";import"./transcript-sqlite-snapshot-staging-owner-B-Am-HqY.mjs";import"./transcript-sqlite-worker-operation-settlement-0iSUo9fw.mjs";import{r as E,t as D}from"./transcript-sqlite-commit-receipt-CIlkMK9M.mjs";import{o as O}from"./transcript-openclaw-state-db-readonly-DQQE4HMs.mjs";import{a as k,l as A}from"./transcript-openclaw-state-db-MJzYHUz2.mjs";import{u as j}from"./transcript-openclaw-agent-db-registry-listing-hSVmRkvc.mjs";import"./transcript-sqlite-worker-store-y0VcAwYV.mjs";import{serialize as M}from"node:v8";import N from"node:path";import{createHash as P,randomUUID as F}from"node:crypto";const I=[`template_package_refs`,`template_mcp_server_refs`,`template_cron_refs`];function readTemplateSecondaryReferenceTables(e,t){return I.filter(n=>T(e,n)?!!e.prepare(`SELECT 1 FROM ${n} WHERE agent_id = ? LIMIT 1`).get(t):!1)}function hasTemplateDeletionOwnership(e,t){let n=h(e.db);return[`template_installs`,`template_workspace_files`].some(r=>T(e.db,r)&&g(e.db,n.selectFrom(r).select(`agent_id`).where(`agent_id`,`=`,t).limit(1))!==void 0)||readTemplateSecondaryReferenceTables(e.db,t).length>0}const L=n(Symbol.for(`openclaw.stateDomainPublicationBatch`),()=>({current:void 0}));function createStateDomainPublication(e){let t=createKeyedStateDomainPublication({domain:e.domain,sourceIdentity:e.sourceIdentity,isFact:(t,n)=>n.kind===`absent`||n.kind===`postimage`&&e.isValue(n.value)&&e.keyOf(n.value)===t});return{...t,stagePostimages(n,r){t.stagePostimages(n,r.map(t=>[e.keyOf(t),t]))}}}function createKeyedStateDomainPublication(t){let r=n(Symbol.for(`openclaw.stateDomainPublication.${t.domain}`),()=>({sources:/* @__PURE__ */ new WeakMap,facts:/* @__PURE__ */ new Set,installingFacts:0})),sourceFor=e=>{let n=l(e),i=r.sources.get(n);return i||(i={identity:t.sourceIdentity?.(e)??C(e)?.key??Symbol(t.domain),incarnation:F()},r.sources.set(n,i)),i},receiptFor=(e,n)=>D({source:sourceFor(e),domain:t.domain,keys:[...n.keys()],readFact:e=>n.get(e)}),install=e=>{let n=[];r.installingFacts++;try{u(r.facts,e,e=>n.push(e))}finally{r.installingFacts--}if(n.length)throw AggregateError(n,t.installFailureMessage??`State domain fact installation failed`)},publication=e=>{let t={kind:`committed`,receipt:e};return{installFacts:()=>install(t),invalidate(){t={kind:`unknown`,identity:e.source.identity},install(t)},notify(){}}},stage=(e,n)=>{if(t.mutationDuringInstallMessage&&r.installingFacts)throw Error(t.mutationDuringInstallMessage);if(!n.size)return;let i=r.capture;if(i&&l(i.db)===l(e)){let t=new Map([...n.keys()].map(e=>[e,i.facts.get(e)]));if(!p(e,{stage(){for(let[e,t]of n)i.facts.set(e,t)},commit(){},rollback(){for(let[e,n]of t)n?i.facts.set(e,n):i.facts.delete(e)}}))throw Error(`State domain capture requires its owning transaction`)}let a=publication(receiptFor(e,n));!d(e,a)&&!e.isTransaction&&c(a)},readReceipt=(e,n=t.isFact)=>E(e,{domain:t.domain,isFact:n,invalidReceiptMessage:t.invalidReceiptMessage});return{receipt:receiptFor,readReceipt,stageFacts:stage,stagePostimages(e,t){stage(e,new Map(t.map(([e,t])=>[e,{kind:`postimage`,value:structuredClone(t)}])))},stageDeletions(e,t){stage(e,new Map(t.map(e=>[e,{kind:`absent`}])))},capture(e,t){let n=r.capture,i=n&&l(n.db)===l(e)?n:{db:e,facts:/* @__PURE__ */ new Map};r.capture=i;try{return{result:t(),receipt:receiptFor(e,i.facts)}}finally{r.capture=n}},bound(e){return M(e).byteLength<=8388608?e:{kind:`unknown`,identity:e.source.identity}},subscribeFacts:e=>f(r.facts,e),begin(n,i=t.isFact){let a=F(),o=/* @__PURE__ */ new Set,s=!1,l=!1,u=!1,d=!1,p=f(r.facts,e=>{if(!s){if(e.kind===`committed`&&e.receipt.source.identity===n.identity)for(let t of e.receipt.facts.keys())o.add(t);else e.kind===`unknown`&&e.identity===n.identity&&(l=!0)}});try{n.publishPending!==!1&&install({kind:`pending`,identity:n.identity,operationId:a})}catch(e){p();try{install({kind:`settled`,identity:n.identity,operationId:a})}catch{}throw e}return{committed(r,a){try{if(n.assertCurrent(),d)throw Error(t.closedMessage??`State domain publication owner is closed`);if(e(r)&&r.kind===`unknown`&&r.identity===n.identity)install({kind:`unknown`,identity:n.identity});else{let e=readReceipt(r,i);if(e.source.identity!==n.identity)throw Error(t.changedOwnerMessage??`State domain commit receipt changed owner`);let a=publication({...e,facts:new Map([...e.facts].map(([e,t])=>[e,l||o.has(e)?{kind:`unknown`}:t]))}),u={...a,installFacts(){s=!0;try{a.installFacts()}finally{s=!1}}};L.current?L.current.push(u):c(u)}u=!0,a?.()}catch(e){throw install({kind:`unknown`,identity:n.identity}),e}finally{s=!1}},finish(e,t=!1){if(!d){d=!0,p();try{(!e||!u&&!t)&&install({kind:`unknown`,identity:n.identity})}finally{n.publishPending!==!1&&install({kind:`settled`,identity:n.identity,operationId:a})}}}}}}}createStateDomainPublication({domain:`agent-provenance`,keyOf:e=>e.agentId,isValue:t=>e(t)&&typeof t.agentId==`string`&&(t.createdVia===`operator`||t.createdVia===`agent`||t.createdVia===`template`)&&(t.creatorAgentId===null||typeof t.creatorAgentId==`string`)&&typeof t.createdAtMs==`number`}),createStateDomainPublication({domain:`agent-deletion-journal`,keyOf:e=>e.agentId,isValue:t=>e(t)&&typeof t.agentId==`string`&&typeof t.operationId==`string`&&typeof t.cleanupCompleted==`boolean`});function resolveLegacyMigrationSourceKey(e,t,n){let r=P(`sha256`);return n!==void 0&&r.update(n).update(`\0`),`${e}:${r.update(N.resolve(t)).digest(`hex`)}`}function readLegacyMigrationReceiptFromDatabase(e,t){let n=g(e,h(e).selectFrom(`migration_sources`).select([`source_sha256`,`removed_source`,`report_json`]).where(`source_key`,`=`,t));return n?{sourceKey:t,sourceSha256:n.source_sha256,removedSource:n.removed_source===1,reportJson:n.report_json}:null}function parseHolds(t){return t.map(t=>{if(!e(t)||typeof t.agentId!=`string`||t.agentId!==m(t.agentId)||typeof t.path!=`string`||!t.path.trim())throw Error(`Invalid agent database hold in deletion journal reconstruction receipt.`);return{agentId:t.agentId,path:t.path}})}function readReport(t){let n=readLegacyMigrationReceiptFromDatabase(t.db,`agent-deletion-journal-reconstruction`);if(!n)return;let r=JSON.parse(n.reportJson);if(!e(r)||typeof r.description!=`string`||!Array.isArray(r.held))throw Error(`Invalid agent deletion journal reconstruction receipt.`);let i=parseHolds(r.held);if(r.missingJournal!==void 0&&!Array.isArray(r.missingJournal))throw Error(`Invalid missing-journal provenance in deletion journal reconstruction receipt.`);let a=Array.isArray(r.missingJournal)?parseHolds(r.missingJournal):r.description===`Reconstructed the missing agent deletion journal; held databases require explicit agent restore or delete.`?i:[];if(a.some(e=>!i.some(t=>t.agentId===e.agentId&&t.path===e.path)))throw Error(`Missing-journal provenance refers to an unheld agent database.`);return{...r,description:r.description,held:i,missingJournal:a}}function decodeHolds(e,t){return t.map(t=>({agentId:t.agentId,path:i(e.path,t.path)}))}function readAgentDeletionRecoveryHolds(e){return decodeHolds(e,readReport(e)?.held??[])}function parseAgentDeletionDatabasePaths(e){let n=JSON.parse(e);if(t(n))return n;throw Error(`Invalid agent deletion database path journal.`)}function readRetainedAgentDeletionsFromDatabase(e,t,n=`maintenance`,r){let i=[],a=!1,c;try{if(a=!T(e,`agent_deletion_journal`),!a){let t=_(),a=t.and([t(`cleanup_completed`,`=`,1),t(`delete_files`,`=`,0)]),o=n===`runtime`?a:t.or([a,t(`cleanup_completed`,`=`,0)]);i=v(e,h(e).selectFrom(`agent_deletion_journal`).select([`agent_id`,`cleanup_completed`]).select(w(e,`agent_deletion_journal`,`phase`)?`phase`:t.lit(null).as(`phase`)).select([t.case().when(o).then(t.ref(`agent_dir`)).else(null).end().as(`agent_dir`),t.case().when(o).then(t.ref(`database_paths_json`)).else(`[]`).end().as(`database_paths_json`)]).$if(!r,e=>e.where(o)).orderBy(`agent_id`,`asc`)).rows.flatMap(t=>{if(r?.push({agentId:t.agent_id,status:t.cleanup_completed===1?`complete`:`pending`}),t.agent_dir===null)return[];let i=[];try{i=parseAgentDeletionDatabasePaths(t.database_paths_json)}catch(e){n===`maintenance`&&(c??=s(e))}let a={agentId:t.agent_id,agentDir:t.agent_dir,databasePaths:[N.join(t.agent_dir,`openclaw-agent.sqlite`),...i],cleanupCompleted:t.cleanup_completed===1};return t.cleanup_completed===0&&t.phase==null&&hasTemplateDeletionOwnership({db:e},t.agent_id)&&(a.manualTemplateRemoval=!0),a})}}catch(e){if(o(e))throw e;c=s(e)}let l=[];try{T(e,`migration_sources`)&&(l=readAgentDeletionRecoveryHolds({db:e,path:t}))}catch(e){if(n===`maintenance`||o(e))throw e}return a&&l.length===0&&k(e)?{status:`empty`}:a||c!==void 0?{status:`unavailable`,cause:a?`missing`:`unreadable`,reason:a?`deletion journal missing`:`deletion journal unreadable: ${c}`,...i.length||l.length?{known:{entries:i,held:l}}:{}}:i.length||l.length?{status:`present`,entries:i,held:l}:{status:`empty`}}function readAgentDatabaseDeletionSnapshot(e,t=`maintenance`){return O(({db:e,path:n})=>y(e,()=>({retainedDeletions:readRetainedAgentDeletionsFromDatabase(e,n,t),registeredAgentDatabases:j(e,n,!1)}),{operationLabel:`agentDeletionJournal.snapshot`}),{env:e})}var AgentDatabaseDeletionRefusedError=class extends Error{};function assertAgentDeletionIdentityClaimAllowed(e,t){if(t&&m(e)===m(t))throw new AgentDatabaseDeletionRefusedError(`OpenClaw agent database is unavailable while agent ${m(t)} is deleted.`)}function readAgentDeletionPathFenceRows(e,t=`runtime`,n){t===`maintenance`&&A(e);try{let r=h(e),i=!0,a=r.selectFrom(`agent_deletion_journal`).selectAll();n!==void 0&&(a=a.where(`agent_id`,`=`,m(n)));let o=v(e,a).rows.map(e=>{let n=[],r=[];try{n=parseAgentDeletionDatabasePaths(e.database_paths_json),r=parseCleanupPaths(e.cleanup_paths_json)}catch(e){if(t===`maintenance`)throw e;i=!1}return Object.assign(e,{databasePaths:n,cleanupPaths:r})});return{known:i,rows:o}}catch(e){if(t===`maintenance`||o(e))throw e;return{known:!1,rows:[]}}}function prepareAgentDeletionPathFence(e,t={},n=e.fenceAgentId?`maintenance`:`runtime`){let r=t.env??process.env;return{env:r,purpose:n,claimAgentId:m(e.agentId),claimPath:N.resolve(e.path),...e.fenceAgentId?{fenceAgentId:m(e.fenceAgentId)}:{},targetPaths:S(e.path).map(e=>b(e,r))}}function assertAgentDeletionPathFence(e,t){let n=e.db,{rows:i,known:o}=readAgentDeletionPathFenceRows(n,t.purpose);if(!o&&i.length===0)return;let s=t.fenceAgentId?void 0:x({agentId:t.claimAgentId,path:t.claimPath,statePath:e.path});s?.assertCurrent();let c=s?.assertJournal(e.path,i.map(e=>({agentId:e.agent_id,operationId:e.operation_id,cleanupCompleted:e.cleanup_completed===1}))),l=t.fenceAgentId?void 0:r(t.claimAgentId,e.path);for(let e of i){if(t.fenceAgentId&&t.fenceAgentId!==e.agent_id||e.agent_id===c||e.cleanup_completed===1&&e.agent_id===l||e.phase===`draining`&&e.cleanup_completed!==1&&e.agent_id===t.claimAgentId&&!t.fenceAgentId||(assertAgentDeletionIdentityClaimAllowed(t.claimAgentId,e.agent_id),e.cleanup_completed===1))continue;let n=[...[e.agent_dir,e.workspace_dir,e.sessions_dir,...e.databasePaths].map(e=>({path:e,canonicalPath:b(e,t.env)})),...e.cleanupPaths.map(e=>({path:e.path,canonicalPath:b(e.canonicalPath,t.env)}))];for(let r of n){let n=t.targetPaths.find(e=>e===r.canonicalPath||a(r.canonicalPath,e));if(n)throw new AgentDatabaseDeletionRefusedError(`OpenClaw agent database ${n} is unavailable while agent ${e.agent_id} deletion owns ${r.path}.`)}}}function parseCleanupPaths(n){let r=JSON.parse(n);if(!Array.isArray(r)||!r.every(n=>e(n)&&typeof n.path==`string`&&typeof n.canonicalPath==`string`&&typeof n.parentPath==`string`&&(n.kind===`target`||n.kind===`symlink`)&&(n.dev===null||typeof n.dev==`number`&&Number.isInteger(n.dev)||typeof n.dev==`string`&&/^(0|-?[1-9][0-9]*)$/u.test(n.dev))&&(n.ino===null||typeof n.ino==`number`&&Number.isInteger(n.ino)||typeof n.ino==`string`&&/^(0|-?[1-9][0-9]*)$/u.test(n.ino))&&typeof n.coversDescendants==`boolean`&&typeof n.done==`boolean`&&(n.note===void 0||typeof n.note==`string`)&&t(n.sourcePaths)))throw Error(`Invalid agent deletion cleanup path journal.`);return r}export{readLegacyMigrationReceiptFromDatabase as a,readRetainedAgentDeletionsFromDatabase as i,prepareAgentDeletionPathFence as n,resolveLegacyMigrationSourceKey as o,readAgentDatabaseDeletionSnapshot as r,assertAgentDeletionPathFence as t};