openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1 lines • 12.6 kB
JavaScript
import{gn as e,ln as t,n,t as r}from"./sqlite-readonly-node-sqlite-u3RAlsBE.mjs";import{_ as i,f as a,h as o,m as s,n as c,o as l,p as u,r as d,s as f,t as p,u as m}from"./sqlite-readonly-schemas-3bx9g-nF.mjs";import{i as h}from"./sqlite-readonly-sqlite-transaction-CZJn2Fa5.mjs";import{i as g,n as _}from"./sqlite-readonly-kysely-sync-DYhhbB39.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(i,a,o,s){if(a.assertIdentity(),b.statSync(i).size===0)throw Error(`Existing SQLite storage is empty.`);let c=s?.database,l=c??r(i,{readOnly:!0,timeout:a.busyTimeoutMs});s&&!s.database&&(e(l),s.database=l);let u,d=!1,f=!1,releaseReader=()=>{if(l.isOpen)try{d&&l.isTransaction&&(l.exec(`ROLLBACK`),f&&l.exec(`PRAGMA page_count`)),d=!1}finally{s||l.close()}};try{l.exec(`PRAGMA locking_mode = EXCLUSIVE`),l.exec(`BEGIN`),d=!0;let e=l.prepare(`PRAGMA journal_mode`).get()?.journal_mode;if(![`delete`,`truncate`,`persist`].includes(String(e)))throw Error(`Existing SQLite storage requires rollback journal mode.`);if(l.exec(`PRAGMA locking_mode = NORMAL`),f=!0,c||a.validate?.(l),!a.write)return o(l,()=>{throw Error(`Read-only SQLite observation cannot admit a writer.`)});u=r(n(i),{timeout:a.busyTimeoutMs});let s=u;return o(s,(e,n)=>t(s,0,t=>h(s,()=>(d&&releaseReader(),t(),a.assertIdentity(),e()),n)))}finally{try{u?.isOpen&&u.close()}finally{releaseReader()}}}const x=s().min(1).max(4096).refine(e=>v.resolve(e)===e),S=s().regex(/^\d+:\d+$/u),C=u({digest:s().regex(/^[a-f0-9]{64}$/u),identity:S,version:s().min(1).max(256)}),w=s().min(1).max(1048576),T=s().min(1).max(255).refine(e=>e!==`.`&&e!==`..`&&!/[\\/\0]/u.test(e)),E=p([`anchor`,`helper`,`candidate`,`launchers`,`previous-launchers`]);u({layout:f(`external-helper`),version:f(1),operationId:i(),recoveryNodePath:x,authority:u({databasePath:x,databaseIdentity:S,parentIdentity:S,installKey:x,owner:s().min(1).max(4096)}),anchorIdentity:S,journalIdentity:S,journalParentIdentity:S,parentIdentity:S,binDir:x,binIdentity:S,originalStageRoot:x,previous:C,candidate:o([C,C.omit({digest:!0})]),launcherRootIdentity:S,previousLauncherRootIdentity:S.nullable(),helperIdentity:S,preparation:c(u({name:E,source:x,sourceParentIdentity:S,identity:S})).min(4).max(5),helperDigest:s().regex(/^[a-f0-9]{64}$/u),launchers:c(u({name:T,previous:s().max(4096).nullable(),candidate:s().max(4096),previousIdentity:S.nullable(),candidateIdentity:S})).max(64)}),p([`preparing`,`prepared`,`publishing`,`publication-complete`,`rollback-in-progress`,`rolled-back`,`aborted`,`retiring`,`anchor-retired`,`superseded`]),o([u({kind:f(`publication-settled-external-change`),replacementIdentity:S,settled:d(),detail:w}),u({kind:p([`publication-not-started`,`superseded-by-manual-install`,`recovery-lease-identity-changed`,`recovery-lease-missing`]),replacementIdentity:S,settled:d(),detail:w.optional()}),u({kind:f(`prepare`),completed:c(E).max(5),moving:E.nullable()}),u({kind:p([`remove-anchor`,`unlink-helper`]),identity:S,selected:p([`previous`,`candidate`])}),u({kind:p([`displace`,`publish`])}),u({kind:f(`copy-previous`),identity:S}),u({kind:f(`displace-copy`),source:C,removing:d()}),u({kind:f(`launcher`),name:T,identity:S}),u({kind:f(`retire`),selected:p([`previous`,`candidate`])}),u({kind:f(`remove`),name:p([`previous`,`candidate`,`previous.candidate`,`launchers`,`previous-launchers`]),identity:S,selected:p([`previous`,`candidate`])})]).nullable();const D=s().min(1).max(4096).refine(e=>v.resolve(e)===e&&!e.includes(`\0`)),O=u({root:D,path:D,sha:s().regex(/^[a-f0-9]{40}$/u),identity:S,buildDigest:s().regex(/^[a-f0-9]{64}$/u),helperPath:D,helperIdentity:S,helperDigest:s().regex(/^[a-f0-9]{64}$/u)}),k=l(()=>o([s().regex(/^fp:[a-f0-9]{12}$/u),c(k),a(s(),k)])),A=s().min(1).refine(e=>v.resolve(e)===e),j=s().regex(/^[a-f0-9]{64}$/u),M=u({dev:s(),ino:s(),mode:m().int(),nlink:f(1),uid:m().int(),gid:m().int()}),N=u({targetPath:A,entries:c(o([u({path:A,kind:f(`missing-directory`)}),u({path:A,kind:f(`existing`),dev:s(),ino:s(),link:s().optional()})]))}),P=u({capturedAtMs:m().int().nonnegative(),auditBoundary:j.nullable(),state:u({path:A,identity:M,pathProof:N,key:s(),birthtime:s().optional()}),config:c(u({path:A,identity:M,pathProof:N,hash:j,fingerprint:k,policyFingerprint:j})).min(1)}),F=s().min(1).max(4096).refine(e=>v.resolve(e)===e&&!e.includes(`\0`)),I=u({sha:s().regex(/^[a-f0-9]{40}$/u),path:F,identity:S,buildDigest:s().regex(/^[a-f0-9]{64}$/u)}),L=u({account:s().regex(/^[a-z_][a-z0-9_-]{0,31}$/u).refine(e=>e!==`root`),uid:m().int().positive().max(2147483647),gid:m().int().positive().max(2147483647),toolchainPath:F,resources:u({memoryMaxBytes:m().int().positive().safe(),tasksMax:m().int().positive().max(65536),buildFreeBytes:m().int().positive().safe(),runtimeFreeBytes:m().int().positive().safe()})}),R=u({version:f(1),mode:f(`inspect`),keepVerifiedGenerations:f(3),pins:c(u({sha:I.shape.sha,identity:I.shape.identity}))}),z=I.extend({publishedRevision:m().int().nonnegative(),verifiedRevision:m().int().nonnegative().nullable()}),B=u({version:o([f(1),f(2),f(3)]),activationEnabled:f(!0).optional(),releaseRetention:R.optional(),kind:f(`immutable`),root:F,rootIdentity:S,releasesIdentity:S,current:I.extend({pointerIdentity:S}),service:u({unit:s().min(1).max(256),scope:f(`system`),account:s().min(1).max(256),stateDir:F,configPath:F,profile:s().min(1).max(256).nullable()}),runtime:u({path:F,identity:s().min(1).max(256)}),source:f(`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:m().int().nonnegative(),schemaVersions:a(s().min(1).max(256),m().int().nonnegative()).optional()}),H=p([`prepared`,`draining`,`stopping`,`stopped`,`publishing`,`starting`,`verifying`,`rollback-stopping`,`rollback-publishing`,`rollback-starting`,`rolled-back`,`recovery-required`]),U=u({databasePath:F,databaseIdentity:S,parentIdentity:S,installKey:F,owner:s().min(1).max(4096)}),W=u({version:f(1),operationId:i(),authority:U,phase:H,previous:I.extend({pointerIdentity:S}),candidate:V,serviceDigest:s().regex(/^[a-f0-9]{64}$/u),protection:P,recovery:O,startedAtMs:m().int().nonnegative(),candidateStartedAtMs:m().int().nonnegative().optional(),servingStartedAtMs:m().int().nonnegative().optional(),stoppedService:u({controlGroup:s().min(1).max(4096),pid:m().int().positive(),processStartTicks:s().min(1).max(128)}).optional(),pointerIntent:u({fromIdentity:S,targetSha:s().regex(/^[a-f0-9]{40}$/u),temporaryIdentity:S}).optional(),failure:s().max(2048).optional()}),G=u({operation:W.optional(),previous:I.optional(),lastResult:u({operationId:i(),outcome:p([`succeeded`,`rolled-back`]),selectedSha:s().regex(/^[a-f0-9]{40}$/u),verifiedAtMs:m().int().nonnegative(),gateway:u({pid:m().int().positive(),bootId:s().min(1).max(256),version:s().min(1).max(256),buildId:s().min(1).max(256)}).optional()}).optional()}),K=u({revision:m().int().nonnegative(),descriptor:B,prepared:V.nullable(),activation:G.optional(),releases:c(z).optional()}),q=1048576,queries=e=>g(e);function readReleaseInventory(e,t){if(!t.descriptor.releaseRetention)return;let n=_(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=_(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};