openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1 lines • 12.6 kB
JavaScript
import{f as e,g as t,m as n,n as r,o as i,p as a,r as o,s,t as c,u as l,v as u}from"./sqlite-readonly-schemas-CQ3oYUYf.mjs";import{G as d,R as f,n as p,t as m}from"./sqlite-readonly-node-sqlite-C-jA8uc4.mjs";import{A as h,M as g}from"./sqlite-readonly-location.worker.js";import{i as _}from"./sqlite-readonly-sqlite-transaction-8ZzF2aMT.mjs";import v from"node:path";import{createHash as y}from"node:crypto";import b from"node:fs";import"node:util";import"node:child_process";function resolvePackageActivationAnchor(e){let t=y(`sha256`).update(e).digest(`hex`).slice(0,24);return v.join(v.dirname(e),`.openclaw.package-activation-${t}`)}function resolvePackageActivationControl(e){return`${e}.control`}function resolvePackageActivationJournalPath(e){return v.join(resolvePackageActivationControl(e),`operation.sqlite`)}function assertPackageActivationLayout(e){if([v.join(e,`operation.sqlite`),`${e}.sqlite`,`${e}.recovery.mjs`].some(e=>b.lstatSync(e,{throwIfNoEntry:!1})))throw Error(`Legacy package activation artifacts require their original recovery owner; no migration is performed.`)}function withExistingSqliteRollbackDatabase(e,t,n,r){if(t.assertIdentity(),b.statSync(e).size===0)throw Error(`Existing SQLite storage is empty.`);let i=r?.database,a=i??m(e,{readOnly:!0,timeout:t.busyTimeoutMs});r&&!r.database&&(d(a),r.database=a);let o,s=!1,c=!1,releaseReader=()=>{if(a.isOpen)try{s&&a.isTransaction&&(a.exec(`ROLLBACK`),c&&a.exec(`PRAGMA page_count`)),s=!1}finally{r||a.close()}};try{a.exec(`PRAGMA locking_mode = EXCLUSIVE`),a.exec(`BEGIN`),s=!0;let r=a.prepare(`PRAGMA journal_mode`).get()?.journal_mode;if(![`delete`,`truncate`,`persist`].includes(String(r)))throw Error(`Existing SQLite storage requires rollback journal mode.`);if(a.exec(`PRAGMA locking_mode = NORMAL`),c=!0,i||t.validate?.(a),!t.write)return n(a,()=>{throw Error(`Read-only SQLite observation cannot admit a writer.`)});o=m(p(e),{timeout:t.busyTimeoutMs});let l=o;return n(l,(e,n)=>f(l,0,r=>_(l,()=>(s&&releaseReader(),r(),t.assertIdentity(),e()),n)))}finally{try{o?.isOpen&&o.close()}finally{releaseReader()}}}const x=n().min(1).max(4096).refine(e=>v.resolve(e)===e),S=n().regex(/^\d+:\d+$/u),C=a({digest:n().regex(/^[a-f0-9]{64}$/u),identity:S,version:n().min(1).max(256)}),w=n().min(1).max(1048576),T=n().min(1).max(255).refine(e=>e!==`.`&&e!==`..`&&!/[\\/\0]/u.test(e)),E=c([`anchor`,`helper`,`candidate`,`launchers`,`previous-launchers`]);a({layout:s(`external-helper`),version:s(1),operationId:u(),recoveryNodePath:x,authority:a({databasePath:x,databaseIdentity:S,parentIdentity:S,installKey:x,owner:n().min(1).max(4096)}),anchorIdentity:S,journalIdentity:S,journalParentIdentity:S,parentIdentity:S,binDir:x,binIdentity:S,originalStageRoot:x,previous:C,candidate:t([C,C.omit({digest:!0})]),launcherRootIdentity:S,previousLauncherRootIdentity:S.nullable(),helperIdentity:S,preparation:r(a({name:E,source:x,sourceParentIdentity:S,identity:S})).min(4).max(5),helperDigest:n().regex(/^[a-f0-9]{64}$/u),launchers:r(a({name:T,previous:n().max(4096).nullable(),candidate:n().max(4096),previousIdentity:S.nullable(),candidateIdentity:S})).max(64)}),c([`preparing`,`prepared`,`publishing`,`publication-complete`,`rollback-in-progress`,`rolled-back`,`aborted`,`retiring`,`anchor-retired`,`superseded`]),t([a({kind:s(`publication-settled-external-change`),replacementIdentity:S,settled:o(),detail:w}),a({kind:c([`publication-not-started`,`superseded-by-manual-install`,`recovery-lease-identity-changed`,`recovery-lease-missing`]),replacementIdentity:S,settled:o(),detail:w.optional()}),a({kind:s(`prepare`),completed:r(E).max(5),moving:E.nullable()}),a({kind:c([`remove-anchor`,`unlink-helper`]),identity:S,selected:c([`previous`,`candidate`])}),a({kind:c([`displace`,`publish`])}),a({kind:s(`copy-previous`),identity:S}),a({kind:s(`displace-copy`),source:C,removing:o()}),a({kind:s(`launcher`),name:T,identity:S}),a({kind:s(`retire`),selected:c([`previous`,`candidate`])}),a({kind:s(`remove`),name:c([`previous`,`candidate`,`previous.candidate`,`launchers`,`previous-launchers`]),identity:S,selected:c([`previous`,`candidate`])})]).nullable();const D=n().min(1).max(4096).refine(e=>v.resolve(e)===e&&!e.includes(`\0`)),O=a({root:D,path:D,sha:n().regex(/^[a-f0-9]{40}$/u),identity:S,buildDigest:n().regex(/^[a-f0-9]{64}$/u),helperPath:D,helperIdentity:S,helperDigest:n().regex(/^[a-f0-9]{64}$/u)}),k=i(()=>t([n().regex(/^fp:[a-f0-9]{12}$/u),r(k),e(n(),k)])),A=n().min(1).refine(e=>v.resolve(e)===e),j=n().regex(/^[a-f0-9]{64}$/u),M=a({dev:n(),ino:n(),mode:l().int(),nlink:s(1),uid:l().int(),gid:l().int()}),N=a({targetPath:A,entries:r(t([a({path:A,kind:s(`missing-directory`)}),a({path:A,kind:s(`existing`),dev:n(),ino:n(),link:n().optional()})]))}),P=a({capturedAtMs:l().int().nonnegative(),auditBoundary:j.nullable(),state:a({path:A,identity:M,pathProof:N,key:n(),birthtime:n().optional()}),config:r(a({path:A,identity:M,pathProof:N,hash:j,fingerprint:k,policyFingerprint:j})).min(1)}),F=n().min(1).max(4096).refine(e=>v.resolve(e)===e&&!e.includes(`\0`)),I=a({sha:n().regex(/^[a-f0-9]{40}$/u),path:F,identity:S,buildDigest:n().regex(/^[a-f0-9]{64}$/u)}),L=a({account:n().regex(/^[a-z_][a-z0-9_-]{0,31}$/u).refine(e=>e!==`root`),uid:l().int().positive().max(2147483647),gid:l().int().positive().max(2147483647),toolchainPath:F,resources:a({memoryMaxBytes:l().int().positive().safe(),tasksMax:l().int().positive().max(65536),buildFreeBytes:l().int().positive().safe(),runtimeFreeBytes:l().int().positive().safe()})}),R=a({version:s(1),mode:s(`inspect`),keepVerifiedGenerations:s(3),pins:r(a({sha:I.shape.sha,identity:I.shape.identity}))}),z=I.extend({publishedRevision:l().int().nonnegative(),verifiedRevision:l().int().nonnegative().nullable()}),B=a({version:t([s(1),s(2),s(3)]),activationEnabled:s(!0).optional(),releaseRetention:R.optional(),kind:s(`immutable`),root:F,rootIdentity:S,releasesIdentity:S,current:I.extend({pointerIdentity:S}),service:a({unit:n().min(1).max(256),scope:s(`system`),account:n().min(1).max(256),stateDir:F,configPath:F,profile:n().min(1).max(256).nullable()}),runtime:a({path:F,identity:n().min(1).max(256)}),source:s(`https://github.com/openclaw/openclaw.git`),build:L.optional()}).refine(e=>e.version!==1==(e.activationEnabled===!0),{message:`Immutable activation requires an explicitly enabled version-2 or version-3 adoption.`}).refine(e=>!e.releaseRetention||e.version===3,{message:`Immutable release retention requires an explicitly adopted version-3 bridge.`}),V=I.extend({preparedAtMs:l().int().nonnegative(),schemaVersions:e(n().min(1).max(256),l().int().nonnegative()).optional()}),H=c([`prepared`,`draining`,`stopping`,`stopped`,`publishing`,`starting`,`verifying`,`rollback-stopping`,`rollback-publishing`,`rollback-starting`,`rolled-back`,`recovery-required`]),U=a({databasePath:F,databaseIdentity:S,parentIdentity:S,installKey:F,owner:n().min(1).max(4096)}),W=a({version:s(1),operationId:u(),authority:U,phase:H,previous:I.extend({pointerIdentity:S}),candidate:V,serviceDigest:n().regex(/^[a-f0-9]{64}$/u),protection:P,recovery:O,startedAtMs:l().int().nonnegative(),candidateStartedAtMs:l().int().nonnegative().optional(),servingStartedAtMs:l().int().nonnegative().optional(),stoppedService:a({controlGroup:n().min(1).max(4096),pid:l().int().positive(),processStartTicks:n().min(1).max(128)}).optional(),pointerIntent:a({fromIdentity:S,targetSha:n().regex(/^[a-f0-9]{40}$/u),temporaryIdentity:S}).optional(),failure:n().max(2048).optional()}),G=a({operation:W.optional(),previous:I.optional(),lastResult:a({operationId:u(),outcome:c([`succeeded`,`rolled-back`]),selectedSha:n().regex(/^[a-f0-9]{40}$/u),verifiedAtMs:l().int().nonnegative(),gateway:a({pid:l().int().positive(),bootId:n().min(1).max(256),version:n().min(1).max(256),buildId:n().min(1).max(256)}).optional()}).optional()}),K=a({revision:l().int().nonnegative(),descriptor:B,prepared:V.nullable(),activation:G.optional(),releases:r(z).optional()}),q=1048576,queries=e=>g(e);function readReleaseInventory(e,t){if(!t.descriptor.releaseRetention)return;let n=h(e,queries(e).selectFrom(`immutable_release_generations`).select(e=>[[`sha`,`=`,40],[`path`,`<=`,4096],[`identity`,`<=`,256],[`build_digest`,`=`,64]].map(([t,n,r])=>e.case().when(e.fn(`length`,[e.cast(t,`blob`)]),n,r).then(e.ref(t)).end().as(t))).select([`published_revision`,`verified_revision`]).orderBy(`published_revision`).orderBy(`sha`).limit(4097)).rows;if(n.length>4096)throw Error(`Immutable release inventory exceeds its admission budget; nothing removed.`);if(t.releases=n.map(e=>{let n=z.parse({sha:e.sha,path:e.path,identity:e.identity,buildDigest:e.build_digest,publishedRevision:e.published_revision,verifiedRevision:e.verified_revision});if(n.path!==v.join(t.descriptor.root,`releases`,n.sha)||n.publishedRevision>t.revision||n.verifiedRevision!==null&&(n.verifiedRevision<n.publishedRevision||n.verifiedRevision>t.revision))throw Error(`Immutable release inventory has invalid path or revision evidence.`);return n}),Buffer.byteLength(JSON.stringify(t))>q)throw Error(`Immutable installation and release inventory exceed 1 MiB; nothing removed.`)}function rootOwnedIdentity(e,t){let n=b.lstatSync(e,{bigint:!0});if(n.uid!==0n||n.ino===0n||(t?!n.isDirectory():!n.isFile()||n.nlink!==1n)||(n.mode&18n)!=0n||b.realpathSync(e)!==e)throw Error(`Immutable installation control has unsafe ownership or permissions: ${e}`);return`${n.dev}:${n.ino}`}function validateRecord(e){let t=K.parse(e);for(let e of[t.descriptor.current,t.prepared,t.activation?.previous,t.activation?.operation?.previous,t.activation?.operation?.candidate])if(e&&e.path!==v.join(t.descriptor.root,`releases`,e.sha))throw Error(`Immutable generation is outside its recorded release root.`);if(Buffer.byteLength(JSON.stringify(t))>q)throw Error(`Immutable installation record exceeds 1 MiB.`);if(t.activation?.operation&&(!t.descriptor.activationEnabled||t.activation.operation.authority.installKey!==t.descriptor.root))throw Error(`Immutable activation does not match its enabled installation owner.`);let n=t.activation?.operation?.recovery;if(n){let e=resolvePackageActivationControl(resolvePackageActivationAnchor(t.descriptor.root));if(n.root!==t.descriptor.root||n.path!==v.join(e,`recovery-${n.sha}`)||n.helperPath!==v.join(e,`recovery.mjs`))throw Error(`Immutable recovery artifact is outside its installation control.`)}return t}function readRecord(e,t,n){let r=h(e,queries(e).selectFrom(`immutable_installation`).selectAll().where(e=>e.fn(`length`,[e.cast(`descriptor_json`,`blob`)]),`<=`,q).where(e=>e.fn(`length`,[e.cast(`prepared_json`,`blob`)]),`<=`,q).limit(2)).rows,i=r[0];if(r.length!==1||!i||i.slot!==1)throw Error(`Immutable installation control must contain one bounded record.`);if(i.activation_json&&Buffer.byteLength(i.activation_json)>q)throw Error(`Immutable activation record exceeds 1 MiB.`);let a=validateRecord({revision:i.revision,descriptor:JSON.parse(i.descriptor_json),prepared:JSON.parse(i.prepared_json),...i.activation_json&&i.activation_json!==`null`?{activation:JSON.parse(i.activation_json)}:{}});if(a.descriptor.root!==t||a.descriptor.rootIdentity!==n)throw Error(`Immutable installation control does not match the installation.`);return readReleaseInventory(e,a),a}function captureImmutableControl(e){let t=resolvePackageActivationAnchor(e);assertPackageActivationLayout(t);let n=resolvePackageActivationControl(t),r=resolvePackageActivationJournalPath(t),i=rootOwnedIdentity(e,!0),a=[e,v.dirname(e),n,r].map((e,t)=>rootOwnedIdentity(e,t!==3));return{control:n,journal:r,assertIdentity:()=>{if([e,v.dirname(e),n,r].some((e,t)=>rootOwnedIdentity(e,t!==3)!==a[t]))throw Error(`Immutable installation control identity changed.`)},assertFileSafe:e=>{rootOwnedIdentity(e,!1)},validate:e=>{if(e.prepare(`SELECT name FROM sqlite_schema WHERE type = 'table' AND name = 'package_activation'`).get())throw Error(`An existing package activation journal remains with its recovery owner.`)},read:t=>readRecord(t,e,i)}}function withImmutableControl(e,t,n){let{journal:r,assertIdentity:i,validate:a,read:o}=captureImmutableControl(e);return withExistingSqliteRollbackDatabase(r,{write:t,busyTimeoutMs:0,assertIdentity:i,validate:a},(e,r)=>(t&&e.exec(`PRAGMA synchronous = EXTRA`),n(e,(e,t)=>r(e,{...t,withCommit(e){i(),t?.withCommit?t.withCommit(e):e()}}),()=>o(e))))}const J={"immutableInstall.read":(e,t)=>{if(resolvePackageActivationJournalPath(resolvePackageActivationAnchor(e.root))!==t.path)throw Error(`Immutable installation read names another control database.`);return withImmutableControl(e.root,!1,(e,t,n)=>n())}};export{J as immutableInstallReadOperations};