clawdi 0.13.57 → 0.13.58
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -665,7 +665,7 @@ if (action === "inspect") {
|
|
|
665
665
|
`,{mode:384,dirMode:448}),Q.afterWrite?.($,xh$($)),W}function QL($){if(!$)return null;return{nativeProfileId:$.nativeProfileId,credentialRevision:$.credentialRevision,state:$.state,...$.operation?{operation:$.operation}:{},...$.credentialFingerprint?{credentialFingerprint:$.credentialFingerprint}:{},...$.beforeCredentialFingerprint?{beforeCredentialFingerprint:$.beforeCredentialFingerprint}:{},...$.targetCredentialFingerprint?{targetCredentialFingerprint:$.targetCredentialFingerprint}:{}}}var PC="clawdi.oauthCredentialOwnership.v2",AC,vh$;var b4$=F(()=>{J6();t4();AC=L.object({schemaVersion:L.literal(PC),runtime:L.enum(["hermes","openclaw"]),providerId:L.string().min(1),nativeProfileId:L.string().min(1),credentialRevision:L.string().min(1).max(64),state:L.enum(["intent","seeded","adopted","revoked","retired"]),operation:L.enum(["seed","upsert","remove"]).optional(),credentialFingerprint:L.string().regex(/^sha256:[a-f0-9]{64}$/).optional(),beforeCredentialFingerprint:L.string().regex(/^sha256:[a-f0-9]{64}$/).optional(),targetCredentialFingerprint:L.string().regex(/^sha256:[a-f0-9]{64}$/).optional()}).strict().superRefine(($,J)=>{if($.state==="intent"&&!$.operation)J.addIssue({code:"custom",message:"intent ledger requires an operation"});if($.state==="intent"&&($.operation==="seed"||$.operation==="upsert")&&!$.targetCredentialFingerprint)J.addIssue({code:"custom",message:"credential write intent requires target evidence"});if($.state==="intent"&&($.operation==="upsert"||$.operation==="remove")&&!$.beforeCredentialFingerprint)J.addIssue({code:"custom",message:"credential mutation intent requires before evidence"});if($.state!=="intent"&&$.operation)J.addIssue({code:"custom",message:"stable ledger cannot carry an operation"});if($.state!=="intent"&&($.beforeCredentialFingerprint||$.targetCredentialFingerprint))J.addIssue({code:"custom",message:"stable ledger cannot carry intent evidence"})}),vh$=L.object({schemaVersion:L.literal("clawdi.runtimeOAuthCredential.v1"),runtime:L.enum(["hermes","openclaw"]),providerId:L.string().min(1),nativeProfileId:L.string().min(1),credentialRevision:L.string().min(1).max(64),state:L.enum(["seeded","adopted","revoked"]),credentialFingerprint:L.string().regex(/^sha256:[a-f0-9]{64}$/).optional()}).strict()});import{spawnSync as _w}from"node:child_process";import{chmodSync as fh$,existsSync as gh$,lstatSync as TC,mkdtempSync as yh$,readdirSync as uh$,rmSync as hh$}from"node:fs";import{join as P4$}from"node:path";function p3($,J){let X=_w($,J,{encoding:"utf8",maxBuffer:65536,timeout:30000});if(X.status!==0){let Q=[X.error?.message,X.stderr,X.stdout].filter((W)=>typeof W==="string"&&W.trim().length>0).join(`
|
|
666
666
|
`).trim().slice(-2000);throw Error(`Files service isolation command failed: ${$}${Q?`: ${Q}`:""}`)}return X.stdout.trim()}function I4$($){let J=_w("getent",["group",$],{encoding:"utf8"});if(J.status!==0)return null;let X=J.stdout.trim().split(":"),Q=Number.parseInt(X[2]??"",10);if(!Number.isInteger(Q)||Q<=0)throw Error(`Files service group ${$} has an invalid gid`);return Q}function _4$($){let J=_w("getent",["passwd",$],{encoding:"utf8"});if(J.status!==0)return null;let X=J.stdout.trim().split(":"),Q=Number.parseInt(X[2]??"",10),W=Number.parseInt(X[3]??"",10);if(!Number.isInteger(Q)||Q<=0||!Number.isInteger(W)||W<=0)throw Error(`Files service user ${$} has an invalid filesystem identity`);return{uid:Q,gid:W,home:X[5]??"",shell:X[6]??""}}function WL($){let X=p3("id",["-G",$]).split(/\s+/).map((Q)=>Number.parseInt(Q,10));if(X.length===0||X.some((Q)=>!Number.isInteger(Q)||Q<=0))throw Error(`Files service identity ${$} has invalid group membership`);return[...new Set(X)]}function mh$($){let J=_w("getent",["group",String($)],{encoding:"utf8"}),X=J.status===0?J.stdout.trim().split(":")[0]?.trim():"";if(!X)throw Error(`Files service identity group ${$} cannot be resolved`);return X}function A4$($,J){p3("gpasswd",["--delete",$,mh$(J)])}function ch$($){let J=I4$(n3);if(J===null)p3("groupadd",["--system",n3]),J=I4$(n3);if(J===null)throw Error("Files service group was not created");let X=_4$(M8);if(X===null)p3("useradd",["--system","--gid",n3,"--home-dir","/nonexistent","--no-create-home","--shell","/usr/sbin/nologin",M8]),X=_4$(M8);if(X===null)throw Error("Files service user was not created");let Q=H1($),W=S5($);if(X.uid===0||X.uid===Q||X.gid!==J||X.gid===W)throw Error("Files service identity is not distinct from the tenant runtime identity");if(X.home!=="/nonexistent"||!X.shell.endsWith("/nologin"))throw Error("Files service identity must be non-login with no home directory");if(WL($).includes(J))A4$($,J);for(let Y of WL(M8))if(Y!==J)A4$(M8,Y);if(WL($).includes(J)||WL(M8).some((Y)=>Y!==J))throw Error("Files service identity has unsafe supplementary group membership");return{uid:X.uid,gid:J}}function lh$($,J,X,Q){if(!gh$(J))throw Error(`Files source root does not exist: ${J}`);if(J!==$.userHome||/\s/.test(J))throw Error("Files source root must be the canonical tenant home path");if(!BQ("systemd-tmpfiles"))throw Error("Files service isolation requires systemd-tmpfiles");if(!/(?:^|\s)\+ACL(?:\s|$)/.test(p3("systemd-tmpfiles",["--version"])))throw Error("Files service isolation requires systemd-tmpfiles POSIX ACL support");let W=TC($.runRoot);if(!W.isDirectory()||W.isSymbolicLink()||W.uid!==0)throw Error("Files service isolation requires a trusted root-owned runtime directory");let Y=yh$($.fileBrowserAclTempPrefix);fh$(Y,448);try{let G=P4$(Y,"filebrowser.conf"),z=[`u:${X}:rwx`,`g:${Q.gid}:rwx`,"m::rwx",`d:u:${X}:rwx`,`d:g:${Q.gid}:rwx`,"d:m::rwx"].join(","),H=[`u:${X}:rw-`,`g:${Q.gid}:rw-`,"m::rwx"].join(","),w=dh$(J,X,Q.uid).map((V)=>`a+ ${nh$(V.path)} - - - - ${V.directory?z:H}`).join(`
|
|
667
667
|
`);Z$(G,`${w}
|
|
668
|
-
`,{mode:384,dirMode:448}),p3("systemd-tmpfiles",["--create",G])}finally{hh$(Y,{recursive:!0,force:!0})}for(let G of["-r","-w","-x"]){let z=DJ(M8,"/nonexistent","/usr/bin/test",[G,J],{currentUid:0,runtimeUid:Q.uid,runtimeGid:Q.gid});if(_w(z.command,z.args,{env:{...process.env,...z.env}}).status!==0)throw Error("Files service identity cannot access the tenant workspace ACL")}}function dh$($,J,X){let Q=TC($);if(!Q.isDirectory()||Q.isSymbolicLink())throw Error("Files source root must be a trusted directory");if(Q.uid!==J)throw Error("Files source root must be owned by the tenant runtime user");let W=[{path:$,directory:!0}],Y=(G)=>{for(let z of uh$(G,{withFileTypes:!0}).sort((H,w)=>H.name.localeCompare(w.name))){if(z.name.startsWith("."))continue;let H=P4$(G,z.name),w;try{w=TC(H)}catch(V){if(ph$(V)==="ENOENT")continue;throw V}if(w.isSymbolicLink())continue;if(w.uid===X)continue;if(w.uid!==J)continue;if(w.isFile()){W.push({path:H,directory:!1});continue}if(!w.isDirectory()||w.dev!==Q.dev)continue;W.push({path:H,directory:!0}),Y(H)}};return Y($),W}function nh$($){let J="";for(let X of Buffer.from($)){if(X===37){J+="%%";continue}if(X>=48&&X<=57||X>=65&&X<=90||X>=97&&X<=122||[45,46,47,95].includes(X)){J+=String.fromCharCode(X);continue}J+=`\\x${X.toString(16).padStart(2,"0")}`}return J}function ph$($){if(typeof $!=="object"||$===null||!("code"in $))return null;return typeof $.code==="string"?$.code:null}function R4$($,J){if(!Q6())throw Error("Files service isolation requires root reconciliation");let X=process.env.CLAWDI_RUNTIME_USER?.trim()||"clawdi";if(X==="root"||X==="0")throw Error("Files service isolation requires a non-root tenant runtime user");for(let W of["getent","gpasswd","groupadd","id","useradd"])if(!BQ(W))throw Error(`Files service isolation requires ${W}`);let Q=ch$(X);return lh$($,J,H1(X),Q),Q}var M8="clawdi-files",n3="clawdi-files";var EC=F(()=>{t4();V1()});import{spawnSync as E4$}from"node:child_process";import{createHash as oh$}from"node:crypto";import{chmodSync as CC,chownSync as xC,existsSync as S4$,lstatSync as $X,mkdirSync as rh$,mkdtempSync as ih$,readdirSync as C4$,readFileSync as x4$,renameSync as ah$,rmSync as YL}from"node:fs";import{basename as sh$,join as I8}from"node:path";function Aw($){return $.companions?.filebrowser??null}function e5($){return I8($.fileBrowserInstallRoot,th$)}function Pw($,J){return I8(e5($),J.toLowerCase())}function GL($,J){return I8(Pw($,J),k4$)}function zL($,J){if(J==="x64")return $.assets.amd64;if(J==="arm64")return $.assets.arm64;throw Error(`Files companion does not support runtime architecture ${J}`)}function g4$($){try{let J=$X($);if(!J.isFile()||J.isSymbolicLink())return null;return oh$("sha256").update(x4$($)).digest("hex")}catch{return null}}function HL($,J){try{let X=$X(Pw($,J));if(!X.isDirectory()||X.isSymbolicLink())return!1;let Q=b8();if(X.uid!==Q.uid||X.gid!==Q.gid||(X.mode&511)!==493)return!1}catch{return!1}try{let X=$X(GL($,J)),Q=b8();return X.isFile()&&!X.isSymbolicLink()&&X.uid===Q.uid&&X.gid===Q.gid&&(X.mode&511)===493&&g4$(GL($,J))===J.toLowerCase()}catch{return!1}}function y4$($,J,X=process.arch){let Q=Aw($);if(!Q)return{rootTrustedRoots:[],rootTargets:[]};let W=zL(Q,X),Y=Pw(J,W.sha256);return{rootTrustedRoots:[J.fileBrowserInstallRoot],rootTargets:[...HL(J,W.sha256)?[]:[Y],J.fileBrowserConfig]}}function $m$($,J){return R3({server:{listen:$.listen,port:$.port,baseURL:$.baseURL,database:I8(J.fileBrowserStateRoot,"filebrowser.db"),cacheDir:I8(J.fileBrowserStateRoot,"cache"),disableUpdateCheck:!0,disableWebDAV:!0,sources:[{path:$.sourceRoot,name:"Files",config:{defaultEnabled:!0,private:!0,rules:[{folderPath:"/",
|
|
668
|
+
`,{mode:384,dirMode:448}),p3("systemd-tmpfiles",["--create",G])}finally{hh$(Y,{recursive:!0,force:!0})}for(let G of["-r","-w","-x"]){let z=DJ(M8,"/nonexistent","/usr/bin/test",[G,J],{currentUid:0,runtimeUid:Q.uid,runtimeGid:Q.gid});if(_w(z.command,z.args,{env:{...process.env,...z.env}}).status!==0)throw Error("Files service identity cannot access the tenant workspace ACL")}}function dh$($,J,X){let Q=TC($);if(!Q.isDirectory()||Q.isSymbolicLink())throw Error("Files source root must be a trusted directory");if(Q.uid!==J)throw Error("Files source root must be owned by the tenant runtime user");let W=[{path:$,directory:!0}],Y=(G)=>{for(let z of uh$(G,{withFileTypes:!0}).sort((H,w)=>H.name.localeCompare(w.name))){if(z.name.startsWith("."))continue;let H=P4$(G,z.name),w;try{w=TC(H)}catch(V){if(ph$(V)==="ENOENT")continue;throw V}if(w.isSymbolicLink())continue;if(w.uid===X)continue;if(w.uid!==J)continue;if(w.isFile()){W.push({path:H,directory:!1});continue}if(!w.isDirectory()||w.dev!==Q.dev)continue;W.push({path:H,directory:!0}),Y(H)}};return Y($),W}function nh$($){let J="";for(let X of Buffer.from($)){if(X===37){J+="%%";continue}if(X>=48&&X<=57||X>=65&&X<=90||X>=97&&X<=122||[45,46,47,95].includes(X)){J+=String.fromCharCode(X);continue}J+=`\\x${X.toString(16).padStart(2,"0")}`}return J}function ph$($){if(typeof $!=="object"||$===null||!("code"in $))return null;return typeof $.code==="string"?$.code:null}function R4$($,J){if(!Q6())throw Error("Files service isolation requires root reconciliation");let X=process.env.CLAWDI_RUNTIME_USER?.trim()||"clawdi";if(X==="root"||X==="0")throw Error("Files service isolation requires a non-root tenant runtime user");for(let W of["getent","gpasswd","groupadd","id","useradd"])if(!BQ(W))throw Error(`Files service isolation requires ${W}`);let Q=ch$(X);return lh$($,J,H1(X),Q),Q}var M8="clawdi-files",n3="clawdi-files";var EC=F(()=>{t4();V1()});import{spawnSync as E4$}from"node:child_process";import{createHash as oh$}from"node:crypto";import{chmodSync as CC,chownSync as xC,existsSync as S4$,lstatSync as $X,mkdirSync as rh$,mkdtempSync as ih$,readdirSync as C4$,readFileSync as x4$,renameSync as ah$,rmSync as YL}from"node:fs";import{basename as sh$,join as I8}from"node:path";function Aw($){return $.companions?.filebrowser??null}function e5($){return I8($.fileBrowserInstallRoot,th$)}function Pw($,J){return I8(e5($),J.toLowerCase())}function GL($,J){return I8(Pw($,J),k4$)}function zL($,J){if(J==="x64")return $.assets.amd64;if(J==="arm64")return $.assets.arm64;throw Error(`Files companion does not support runtime architecture ${J}`)}function g4$($){try{let J=$X($);if(!J.isFile()||J.isSymbolicLink())return null;return oh$("sha256").update(x4$($)).digest("hex")}catch{return null}}function HL($,J){try{let X=$X(Pw($,J));if(!X.isDirectory()||X.isSymbolicLink())return!1;let Q=b8();if(X.uid!==Q.uid||X.gid!==Q.gid||(X.mode&511)!==493)return!1}catch{return!1}try{let X=$X(GL($,J)),Q=b8();return X.isFile()&&!X.isSymbolicLink()&&X.uid===Q.uid&&X.gid===Q.gid&&(X.mode&511)===493&&g4$(GL($,J))===J.toLowerCase()}catch{return!1}}function y4$($,J,X=process.arch){let Q=Aw($);if(!Q)return{rootTrustedRoots:[],rootTargets:[]};let W=zL(Q,X),Y=Pw(J,W.sha256);return{rootTrustedRoots:[J.fileBrowserInstallRoot],rootTargets:[...HL(J,W.sha256)?[]:[Y],J.fileBrowserConfig]}}function $m$($,J){return R3({server:{listen:$.listen,port:$.port,baseURL:$.baseURL,database:I8(J.fileBrowserStateRoot,"filebrowser.db"),cacheDir:I8(J.fileBrowserStateRoot,"cache"),disableUpdateCheck:!0,disableWebDAV:!0,sources:[{path:$.sourceRoot,name:"Files",config:{defaultEnabled:!0,private:!0,rules:[{folderPath:"/",ignoreSymlinks:!0}]}}]},frontend:{name:"Files",disableDefaultLinks:!0,disableUsedPercentage:!1},http:{trustedHeaders:[]},auth:{methods:{password:{enabled:!1,signup:!1},passkey:{enabled:!1},jwt:{enabled:!0,secret:$.auth.secret,algorithm:$.auth.algorithm,header:$.auth.header,userIdentifier:$.auth.userIdentifier,groupsClaim:$.auth.groupsClaim,userGroups:[$.auth.requiredGroup]}}},userDefaults:{sidebar:{sticky:!1},listing:{showHidden:!0},account:{lockPassword:!0,disableSettings:!1,disableUpdateNotifications:!0,loginMethod:"jwt",permissions:{admin:!1,api:!1,modify:!0,share:!1,realtime:!1,delete:!0,create:!0,download:!0}}}})}function b8(){if(Q6())return{uid:0,gid:0};return{uid:typeof process.geteuid==="function"?process.geteuid():0,gid:typeof process.getegid==="function"?process.getegid():0}}function SC($,J,X){if(!S4$($))rh$($,{recursive:!0,mode:X});let Q=$X($);if(!Q.isDirectory()||Q.isSymbolicLink())throw Error(`Files companion managed path is not a trusted directory: ${$}`);xC($,J.uid,J.gid),CC($,X)}function Jm$($,J,X){let Q=E4$("curl",["-fsSL","--proto","=https","--tlsv1.2","--retry","3","-o",J,$],{cwd:X.fileBrowserInstallRoot,encoding:"utf8",maxBuffer:65536,timeout:300000});if(Q.status!==0){let W=[Q.stderr,Q.stdout].filter((Y)=>typeof Y==="string"&&Y.trim().length>0).join(`
|
|
669
669
|
`).trim().slice(-2000);throw Error(`Files companion download failed${W?`: ${W}`:""}`)}}function Xm$($,J,X,Q){let W=Pw(J,X.sha256);if(HL(J,X.sha256))return;YL(W,{recursive:!0,force:!0});let Y=ih$(I8(e5(J),".staging-"));try{let G=I8(Y,k4$);if(Q.download)Q.download(X.url,G);else Jm$(X.url,G,J);let z=g4$(G);if(z!==X.sha256.toLowerCase())throw Error(`Files companion SHA256 mismatch: expected ${X.sha256.toLowerCase()}, got ${z??"unreadable"}`);if(CC(G,493),xC(G,b8().uid,b8().gid),CC(Y,493),Q.versionProbe){let H=Q.versionProbe(G);if(!H.includes($.version)||!H.includes($.commit.slice(0,7)))throw Error("Files companion version probe did not match the pinned release")}ah$(Y,W)}finally{YL(Y,{recursive:!0,force:!0})}}function Qm$($){let J=[];for(let X of C4$(e5($)).sort()){if(!X.startsWith(".staging-"))continue;let Q=I8(e5($),X),W=$X(Q);if(!W.isDirectory()||W.isSymbolicLink())throw Error(`Files companion staging entry is not a trusted directory: ${X}`);YL(Q,{recursive:!0}),J.push(Q)}return J}function u4$($,J){return $0({version:$.version,commit:$.commit,assets:$.assets,config:J})}function T4$($,J,X,Q,W){if(!HL(J,X))return null;try{let Y=b8(),G=$X(J.fileBrowserConfigRoot);if(!G.isDirectory()||G.isSymbolicLink()||G.uid!==Y.uid||G.gid!==W.gid||(G.mode&511)!==v4$)return null;let z=$X(J.fileBrowserConfig);if(!z.isFile()||z.isSymbolicLink()||z.uid!==Y.uid||z.gid!==W.gid||(z.mode&511)!==f4$)return null;if(x4$(J.fileBrowserConfig,"utf8")!==Q)return null}catch{return null}return u4$($,Q)}function h4$($,J,X,Q={}){let W=Aw($);if(!W)return null;let Y=zL(W,Q.arch??process.arch),G=$m$(W,J),z=u4$(W,G),H=(Q.serviceIsolation??R4$)(J,W.sourceRoot),w=T4$(W,J,Y.sha256,G,H),V=HL(J,Y.sha256),U=X?.desiredRevision===z&&X.currentRevision===w;if(SC(J.fileBrowserInstallRoot,b8(),493),SC(e5(J),b8(),493),SC(J.fileBrowserConfigRoot,{uid:b8().uid,gid:H.gid},v4$),Qm$(J),!U||w===null)Xm$(W,J,Y,Q),Z$(J.fileBrowserConfig,G,{mode:f4$,trustedRoot:J.runRoot}),xC(J.fileBrowserConfig,b8().uid,H.gid);let q=()=>T4$(W,J,Y.sha256,G,H),Z=q();if(Z!==z)throw Error("Files companion candidate did not pass activation verification");return{receiptKey:eh$,receiptTarget:{desiredRevision:z,currentRevision:q,expectedCurrentRevision:Z},activeBinary:GL(J,Y.sha256),installed:!V}}function m4$($,J){let X=Aw($);if(!X)return null;let Q=zL(X,process.arch);return{programKind:"file-browser",runtime:"files",service:null,command:GL(J,Q.sha256),args:["-c",J.fileBrowserConfig],cwd:X.sourceRoot,env:{},resolvedSecretEnv:{}}}function c4$($,J={}){let X=Aw($);if(!X)return;let Q=`http://127.0.0.1:${X.port}${X.healthPath}`;if(!(J.probe?J.probe(Q):E4$("curl",["-fsS","--retry","5","--retry-connrefused","--retry-delay","1","--max-time","2",Q],{encoding:"utf8",timeout:12000}).status===0))throw Error(`Files companion readiness failed at ${Q}`)}function l4$($,J,X=process.arch){let Q=Aw($);if(!Q||!S4$(e5(J)))return[];let W=Pw(J,zL(Q,X).sha256),Y=[];for(let G of C4$(e5(J)).sort()){let z=I8(e5(J),G);if(z===W)continue;let H=$X(z);if(!H.isDirectory()||H.isSymbolicLink())throw Error(`Files companion candidate is not a trusted directory: ${sh$(z)}`);YL(z,{recursive:!0}),Y.push(z)}return Y}var k4$="filebrowser",th$="candidates",eh$="filebrowser",v4$=488,f4$=288;var d4$=F(()=>{Hw();t4();H8();EC();V1()});import{createHash as Wm$}from"node:crypto";function n4$($){let J=$.egressProfiles!==void 0?mz.parse($.egressProfiles):{profiles:[]};return Km$(J,[...Gm$(),...Hm$($),...Ym$($)])}function Ym$($){if(typeof $.mcp!=="object"||$.mcp===null||Array.isArray($.mcp)||!Object.hasOwn($.mcp,"servers"))return[];let J=wQ.parse($.mcp),X=[];for(let[Q,W]of Object.entries(J.servers)){if(!("url"in W))continue;let Y=Object.entries(W.headers).filter((H)=>typeof H[1]!=="string");if(Y.length===0)continue;let G=new URL(W.url),z=G.port||(G.protocol==="https:"?"443":"80");X.push({id:`managed-mcp-${p4$(Q)}`,enabled:!0,kind:"provider",match:{scheme:G.protocol.slice(0,-1),host:`${G.hostname.toLowerCase()}:${z}`,path:{type:"equals",value:G.pathname||"/"},headers:Object.fromEntries(Y.map(([H,w])=>[H,{type:"equals",value:vC(Q,H),prefix:w.prefix}])),query:{}},rewrite:{preservePath:!0,setHeaders:Object.fromEntries(Y.map(([H,w])=>[H,{type:"secretRef",secretRef:w.secretRef,prefix:w.prefix}]))},logging:{redactHeaders:Y.map(([H])=>H),redactUrlPatterns:[]},priority:70,owner:"mcp-projection",description:`Managed remote MCP credentials for ${Q}.`})}return X}function vC($,J){let X=Wm$("sha256").update(`${$}\x00${J.toLowerCase()}`).digest("hex").slice(0,16);return`${VQ}-mcp-${X}`}function Gm$(){let $=(J,X,Q,W)=>({id:J,enabled:!0,kind:"passthrough",match:{scheme:"https",host:X,pathPrefix:Q,headers:{},query:{}},logging:{redactHeaders:[],redactUrlPatterns:[]},priority:200,owner:"runtime-installer",description:W});return[$("runtime-installer-openclaw-install","openclaw.ai","/install-cli.sh","OpenClaw official installer script."),$("runtime-installer-nodejs-dist","nodejs.org","/dist/","Node.js release artifacts used by the OpenClaw official installer."),$("runtime-installer-npm-registry","registry.npmjs.org","/","npm package metadata and tarballs used by the OpenClaw official installer."),$("runtime-installer-hermes-install","hermes-agent.nousresearch.com","/install.sh","Hermes official installer script."),$("runtime-installer-uv","astral.sh","/uv/","uv installer bootstrap."),$("runtime-installer-uv-releases","releases.astral.sh","/installers/uv/","uv installer release script."),$("runtime-installer-github","github.com","/","Installer release metadata."),$("runtime-installer-github-api","api.github.com","/","Installer release metadata API."),$("runtime-installer-github-raw","raw.githubusercontent.com","/","Installer release script assets."),$("runtime-installer-github-objects","objects.githubusercontent.com","/","Installer release binary assets."),$("runtime-installer-github-release-assets","release-assets.githubusercontent.com","/","Installer release binary assets."),$("runtime-installer-pypi","pypi.org","/simple/","Hermes Python package index."),$("runtime-installer-pythonhosted","files.pythonhosted.org","/","Hermes Python package artifacts.")]}function zm$($){return $==="openai_chat"||$==="openai_responses"}function Hm$($){let J=[],X=new Set;for(let[Q,W]of wm$($)){let Y=Vm$(Q,W);if(!Y)continue;let G=VL(W.apiKeySecretRef),z=[Y.match.scheme,Y.match.host,Y.match.pathPrefix??"",G??""].join(":");if(X.has(z))continue;X.add(z),J.push(Y)}return J}function wm$($){let J=qm$($.providers),X=kC($.terminalTooling),Q=kC(X?.codex),W=Zm$(Q?.provider),Y=wL(typeof Q?.provider_id==="string"?Q.provider_id:null);if(Y&&W)J.push([Y,W]);return J}function Vm$($,J){let X=Bm$(J?.baseUrl),Q=wL(J?.apiMode),W=VL(J?.apiKeySecretRef);if(!iQ(J)||!X||!W||!zm$(Q))return null;if(wL(J.status)&&wL(J.status)!=="ok")return null;let Y=new URL(X),G=Y9($)?x1:$;return{id:G==="default"?"managed-provider":`managed-provider-${p4$(G)}`,enabled:!0,kind:"provider",match:{scheme:Y.protocol.replace(/:$/,""),host:Y.host.toLowerCase(),pathPrefix:Um$(Y.pathname),headers:{authorization:{type:"equals",value:VQ,prefix:"Bearer "}},query:{}},rewrite:{preservePath:!0,setHeaders:{authorization:{type:"secretRef",secretRef:W,prefix:"Bearer "}}},logging:{redactHeaders:["authorization"],redactUrlPatterns:[]},priority:80,owner:"provider-projection"}}function Um$($){if($==="/")return $;return`${$.replace(/\/+$/,"")}/`}function VL($){let J=$?.trim();return J?.startsWith("secret://")&&J.length>9?J:null}function iQ($){return $.managed_by==="clawdi"}function qm$($){if(!$||typeof $!=="object"||Array.isArray($))return[];return Object.entries($).filter((J)=>{let[X,Q]=J;return X.trim().length>0&&typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}).sort(([J],[X])=>{if(J==="default")return-1;if(X==="default")return 1;return J.localeCompare(X)})}function Zm$($){let J=kC($);if(!J)return null;return{baseUrl:Rw(J.baseUrl),apiMode:Rw(J.apiMode),apiKeySecretRef:Rw(J.apiKeySecretRef),managed_by:Rw(J.managed_by),status:Rw(J.status)}}function kC($){return typeof $==="object"&&$!==null&&!Array.isArray($)?$:null}function wL($){return $?.trim()||null}function Rw($){return $===null||typeof $==="string"?$:void 0}function Bm$($){if(!$)return null;try{let J=new URL($);if(!["http:","https:","ws:","wss:"].includes(J.protocol))return null;return J.toString().replace(/\/+$/,"")}catch{return null}}function Km$($,J){let X=new Set(J.map((Q)=>Q.id));return{profiles:[...$.profiles.filter((Q)=>!X.has(Q.id)),...J]}}function p4$($){return $.toLowerCase().replace(/[^a-z0-9-_.]+/g,"-").replace(/^[^a-z0-9]+/,"").replace(/[^a-z0-9]+$/,"")||"provider"}var UL=F(()=>{B8();G8();n7();PB()});import{existsSync as o4$,rmSync as r4$}from"node:fs";import{join as ZL}from"node:path";function Lm$($,J){for(let X of[ZL(J,"venv","bin","hermes"),ZL($,".local","bin","hermes")])if(X6(X))return X;throw Error("installed Hermes Skill CLI is unavailable")}function i4$($,J,X){return{path:s4$($,J),schemaVersion:a4$,skillId:J,ownershipIdentity:X,target:qL($,J)}}function Nm$($){if($.source.type==="project")return $.source.installUrl;let J=new URL($.source.url),[X,Q]=J.pathname.slice(1).split("/");if(!X||!Q)throw Error("Hermes exact-source URL requires a canonical GitHub repository");let W=$.source.path.split("/").map((G)=>encodeURIComponent(G)).join("/"),Y=W?`${W}/SKILL.md`:"SKILL.md";return`https://raw.githubusercontent.com/${encodeURIComponent(X)}/${encodeURIComponent(Q)}/${$.source.commit}/${Y}`}function fC($,J){return V0(Lm$($.home,$.appRoot),J,$.home,$.appRoot,{timeoutMs:120000,maxBufferBytes:1048576})}function Fm$($){let J=E1($),X=J?.get("SKILL.md");if(!J||!X)return null;let Q=X.toString("utf8").replaceAll("\\","/");if(/(?:references|templates|scripts|assets|examples)\/(?:[^\s)`"'<>]*\/)?\.\.(?:\/|$)/m.test(Q))return null;let W=new Map([["SKILL.md",X]]);for(let Y of Q.matchAll(Dm$)){let G;try{G=decodeURIComponent((Y[1]??"").replace(/[.,;:]+$/,"").split(/[?#]/,1)[0]??"")}catch{return null}let z=G.split("/");if(!Om$.has(z[0]??"")||z.some((w)=>!w||w==="."||w===".."))return null;let H=J.get(G);if(!H)return null;W.set(G,H)}return W}function gC($,J){return sW(Fm$($),E1(J))}var a4$="clawdi.hermesManifestSkillReceipt.v2",qL=($,J)=>ZL($,".hermes","skills",J),s4$=($,J)=>ZL($,".hermes","skills",".clawdi-manifest-receipts",`${J}.json`),Om$,Dm$,t4$;var e4$=F(()=>{Kq();V1();Om$=new Set(["references","templates","scripts","assets","examples"]),Dm$=/(?:\]\(|`|(?:^|[\s"']))((?:references|templates|scripts|assets|examples)\/[^\s)`"'<>]+)/gm;t4$={install($){return tW($.skill,(J)=>{let X=qL($.home,$.skill.skillId),Q=i4$($.home,$.skill.skillId,$.skill.sourceIdentity),W=o4$(X);if(W&&!$.previouslyReserved)throw Error("Hermes Skill target is not paired with a manifest reservation");if(gC(J,X)&&dX(Q))return"unchanged";if(W&&!qh(Q))throw Error("refusing to replace a Hermes Skill without a matching Clawdi ownership receipt");return Bq({target:X,receipt:Q.path,operation:()=>{let Y=["skills","install",Nm$($.skill),"--name",$.skill.skillId,"--yes"];if($.previouslyReserved)Y.push("--force");let G=fC($,Y);if(G.status!==0)throw Error(`Hermes official Skill install failed: ${String(G.stderr||G.stdout).trim()||"unknown error"}`);if(!gC(J,X)){if(!W){let z=fC($,["skills","uninstall",$.skill.skillId,"--yes"]);if(z.status!==0)throw Error(`Hermes official install produced invalid Skill bytes and native rollback failed: ${String(z.stderr||z.stdout).trim()||"unknown error"}`)}throw Error("Hermes official install did not preserve the exact native catalog projection")}return Zq(Q),"installed"}})})},verifyOwned($){return tW($.skill,(J)=>gC(J,qL($.home,$.skill.skillId))&&dX(i4$($.home,$.skill.skillId,$.skill.sourceIdentity)))},uninstall($){let J=qL($.home,$.skillId),X={path:s4$($.home,$.skillId),schemaVersion:a4$,skillId:$.skillId,ownershipIdentity:$.ownershipIdentity,target:J};if(!o4$(J))return r4$(X.path,{force:!0}),"absent";if(!dX(X))throw Error("Hermes Skill bytes no longer match the manifest ownership receipt");let Q=fC($,["skills","uninstall",$.skillId,"--yes"]);if(Q.status!==0)throw Error(`Hermes official Skill uninstall failed: ${String(Q.stderr||Q.stdout).trim()||"unknown error"}`);return r4$(X.path,{force:!0}),"removed"}}});import{existsSync as $0$,rmSync as yC}from"node:fs";import{isAbsolute as jm$,join as LL,resolve as X0$}from"node:path";function Im$($){for(let J of[LL($,".local","bin","openclaw"),LL($,".openclaw","bin","openclaw")])if(X6(J))return J;return null}function Y0$($){let J=Im$($);if(J)return J;throw Error("installed OpenClaw Skill CLI is unavailable")}function BL($,J,X){return{path:_m$($,J),schemaVersion:bm$,skillId:J,ownershipIdentity:X,target:KL($,J),exclude:W0$}}function G0$($){let J=Y0$($),X=V0(J,["agents","list","--json"],$,$,{timeoutMs:15000,maxBufferBytes:1048576});if(X.status!==0)throw Error("OpenClaw official agent workspace roster is unavailable");let Q;try{Q=Jj(String(X.stdout))}catch{throw Error("OpenClaw official agent workspace roster is malformed")}let W=Q.filter((Y)=>Y.id===Q0$);if(W.length!==1||!jm$(W[0].workspace))throw Error("OpenClaw official agent workspace roster is malformed");return X0$(W[0].workspace)}function J0$($){if(G0$($.home)!==X0$($.workspaceRoot))throw Error("OpenClaw official agent workspace changed during Skill reconciliation")}function uC($,J){return sW(E1($),E1(J,{exclude:W0$}))}function Am$($){let J=[];if($.error)J.push(`spawn error: ${$.error.message}`);if($.signal)J.push(`terminated by signal ${$.signal}`);for(let X of[$.stderr,$.stdout])if(typeof X==="string"&&X.trim()){J.push(X.trim());break}if(J.length===0&&typeof $.status==="number")J.push(`exit code ${$.status} without output`);return J.join("; ")||"process failed without details"}var Q0$="main",Mm$=".openclaw/source-origin.json",W0$,bm$="clawdi.openclawManifestSkillReceipt.v2",KL=($,J)=>LL($,"skills",J),_m$=($,J)=>LL($,"skills",".clawdi-manifest-receipts",`${J}.json`),z0$;var H0$=F(()=>{Nq();Kq();V1();W0$=new Set([Mm$]);z0$={resolveWorkspace($){return G0$($.home)},installDirectory($){let J=KL($.workspaceRoot,$.skillId),X=BL($.workspaceRoot,$.skillId,$.ownershipIdentity);if(uC($.sourceDir,J)&&dX(X))return"unchanged";if($0$(J)&&!Uh(X))throw Error("refusing to replace an OpenClaw Skill without a matching Clawdi ownership receipt");return J0$($),Bq({target:J,receipt:X.path,operation:()=>{let Q=V0(Y0$($.home),["skills","install",$.sourceDir,"--agent",Q0$,"--as",$.skillId,"--force"],$.home,$.home,{timeoutMs:120000,maxBufferBytes:1048576});if(Q.status!==0)throw Error(`OpenClaw official Skill install failed: ${Am$(Q)}`);if(!uC($.sourceDir,J))throw Error(`OpenClaw installed Skill outside the configured agent workspace or changed exact source bytes: ${J}`);return J0$($),Zq(X),"installed"}})},install($){return tW($.skill,(J)=>this.installDirectory({home:$.home,workspaceRoot:$.workspaceRoot,skillId:$.skill.skillId,sourceDir:J,ownershipIdentity:$.skill.sourceIdentity}))},hasOwnershipReceipt($){return eF(BL($.workspaceRoot,$.skillId,$.ownershipIdentity))},verifyOwned($){return tW($.skill,(J)=>uC(J,KL($.workspaceRoot,$.skill.skillId))&&eF(BL($.workspaceRoot,$.skill.skillId,$.skill.sourceIdentity)))},cleanupManifestOwned($){let J=KL($.workspaceRoot,$.skillId),X=BL($.workspaceRoot,$.skillId,$.ownershipIdentity);if(!$0$(J))return yC(X.path,{force:!0}),"absent";if(!dX(X))throw Error("refusing manifest cleanup because OpenClaw Skill bytes no longer match the ownership receipt");return yC(J,{recursive:!0}),yC(X.path,{force:!0}),"removed"}}});function NL($,J){let X=$.projection?.providers;if(!X||Object.keys(X).length===0)return null;let Q=hC(X,J,$),W=Tm$($,J);if(!W)return null;let Y=Q.map(([G,z])=>{if(typeof z!=="object"||z===null||Array.isArray(z))return null;let H=z,w=typeof H.baseUrl==="string"?H.baseUrl:void 0,V=w0$(H),U=typeof H.apiKeySecretRef==="string"?H.apiKeySecretRef:void 0,q=cC(G,H,J);if(xm$(H))return null;if(!w)return null;let Z=Cm$(H,Boolean(U));if(!Z)return null;let K=Em$(H,G===W.provider_id?W:null);return{id:G,type:Sm$(H),base_url:w,api_mode:V,managed_by:Rm$(H),auth:Z,runtime_env_name:U||Z.type!=="none"?q:void 0,models:K}}).filter((G)=>G!==null);if(Y.length===0)return null;return{catalog:{schema_version:1,providers:Y,defaults:{chat_provider_id:W.provider_id}},primaryModel:W}}function Rm$($){let J=$.managed_by;return J==="clawdi"||J==="user"?J:void 0}function hC($,J,X){if(!J)return Object.entries($).sort(([W],[Y])=>W.localeCompare(Y));return(X?.runtimes?.[J]?.provider_ids??[]).filter((W)=>Object.hasOwn($,W)).map((W)=>[W,$[W]])}function Tm$($,J){return(J?$.runtimes[J]:void 0)?.primary_model??null}function Em$($,J){let X=w0$($),Q=EJ($.model),G=(Array.isArray($.models)?$.models:[]).map((z)=>aQ(z)?z:null).filter((z)=>z!==null).map((z)=>{let H=EJ(z.id);if(!H)return null;let w=EJ(z.api_mode);return{...z,id:H,...w&&rX(w)?{api_mode:w}:{}}}).filter((z)=>z!==null);if(Q&&!G.some((z)=>z.id===Q))G.unshift({id:Q,api_mode:X});if(J&&!G.some((z)=>z.id===J.model))G.unshift({id:J.model,api_mode:X});return G.filter((z,H,w)=>w.findIndex((V)=>V.id===z.id)===H)}function w0$($){let J=$.apiMode;if(typeof J==="string"&&rX(J))return J;return"openai_chat"}function Sm$($){let J=EJ($.type);return J&&oG(J)?J:"custom_openai_compatible"}function Cm$($,J){let X=aQ($.auth);if(X){let Q=EJ(X.type),W=EJ(X.tool),Y=EJ(X.profile);if(Q==="agent_profile"&&W==="codex"&&Y)return{type:"agent_profile",tool:"codex",profile:Y};if(Q==="api_key"||Q==="secret_ref"){if(J)return{type:"api_key",source:"managed"};return null}if(Q&&Q!=="none")return null}if(J)return{type:"api_key",source:"managed"};if(mC($))return null;return{type:"none"}}function xm$($){let J=EJ($.status);return Boolean(J&&J!=="ok")}function mC($){if($.apiKeyRequired===!0)return!0;let J=aQ($.auth),X=J?EJ(J.type):null;return X==="api_key"||X==="secret_ref"}function cC($,J,X){if(X==="openclaw"&&iQ(J))return Pm$;let Q=typeof J.runtimeEnvName==="string"?J.runtimeEnvName:null;if(Q&&lC(Q))return Q;return`CLAWDI_PROVIDER_${$.toUpperCase().replace(/[^A-Z0-9]/g,"_")}_API_KEY`}function km$($,J){let X=aQ($.projection?.providers);if(!X)return{};let Q={};for(let[W,Y]of hC(X,J,$)){let G=aQ(Y);if(!G)continue;if(!iQ(G))continue;if(!EJ(G.apiKeySecretRef))continue;let H=cC(W,G,J);if(!lC(H))continue;Q[H]=VQ}return Q}function vm$($,J){let X=aQ($.projection?.providers);if(!X)return{};let Q={};for(let[W,Y]of hC(X,J,$)){let G=aQ(Y);if(!G)continue;if(iQ(G))continue;let z=EJ(G.apiKeySecretRef);if(!z)continue;let H=cC(W,G,J);if(!lC(H))continue;Q[H]=z}return Q}function Tw($,J,X={}){let Q=km$($,J),W=vm$($,J);if(X.validateOverlap)fm$(J??"default",Q,W);return{placeholderEnv:Q,secretEnv:W}}function fm$($,J,X){for(let Q of Object.keys(J)){if(X[Q]===void 0)continue;throw Error(`runtime ${$} provider env ${Q} is both managed and BYOK-backed`)}}function OL($,J,X){if(Object.keys(X).length===0)return J;let Q=J?.env??{};for(let W of Object.keys(X))if(J?.secretEnv?.[W]!==void 0)throw Error(`runtime ${$} provider placeholder ${W} conflicts with secretEnv`);return{...J??{},prependPath:J?.prependPath??[],env:{...Q,...X}}}function V0$($,J,X,Q){if(Object.keys(Q).length===0)return X;for(let W of Object.keys(Q))if(X.secretEnv?.[W]!==void 0)throw Error(`runtime ${$} service ${J} provider placeholder ${W} conflicts with secretEnv`);return{...X,env:{...X.env??{},...Q}}}function aQ($){return typeof $==="object"&&$!==null&&!Array.isArray($)?$:null}function EJ($){return typeof $==="string"&&$.trim()?$.trim():null}function lC($){return/^[A-Za-z_][A-Za-z0-9_]*$/.test($)}var Pm$="CLAWDI_OPENCLAW_API_KEY";var U0$=F(()=>{B8();G8();UL()});import{lstatSync as gm$,readFileSync as ym$}from"node:fs";function B0$(){return{schemaVersion:"clawdi.runtimeInstallReceipts.v1",officialServices:{},channelPlugins:{},companions:{}}}function o3($){return $.installReceipts}function pC($){let J=o3($),X;try{X=gm$(J)}catch(Y){if(Y.code==="ENOENT")return null;throw nC("could not be inspected",Y)}if(!X.isFile())throw Error("runtime install receipts are not a trusted regular file");if((X.mode&511)!==384)throw Error("runtime install receipts do not have private file permissions");if(typeof process.getuid==="function"&&X.uid!==process.getuid())throw Error("runtime install receipts do not have the expected file owner");let Q;try{Q=JSON.parse(ym$(J,"utf8"))}catch(Y){throw nC("could not be decoded",Y)}let W=Z0$.safeParse(Q);if(!W.success)throw Error("runtime install receipts do not match the expected schema");return W.data}function K0$($,J){let X=Z0$.parse($);try{e4(J,o3(J),`${JSON.stringify(X,null,2)}
|
|
670
670
|
`,{mode:384,dirMode:493})}catch(W){throw nC("could not be persisted",W)}let Q=pC(J);if(!Q||JSON.stringify(Q)!==JSON.stringify(X))throw Error("runtime install receipts did not pass post-write verification")}function nC($,J){let X=typeof J==="object"&&J!==null&&"code"in J&&typeof J.code==="string"?` (${J.code})`:"";return Error(`runtime install receipts ${$}${X}`)}var q0$,dC,Z0$;var oC=F(()=>{J6();e6();q0$=L.string().regex(/^[a-f0-9]{64}$/),dC=L.object({desiredRevision:q0$,currentRevision:q0$}).strict(),Z0$=L.object({schemaVersion:L.literal("clawdi.runtimeInstallReceipts.v1"),officialServices:L.record(L.string().min(1),dC),channelPlugins:L.record(L.string().min(1),dC),companions:L.object({filebrowser:dC.optional()}).strict().default({})}).strict()});import{chmodSync as rC,chownSync as um$,existsSync as aC,lchownSync as hm$,lstatSync as r3,mkdirSync as iC,readdirSync as tC,readFileSync as O0$,readlinkSync as mm$,rmSync as L0$,symlinkSync as cm$,writeFileSync as lm$}from"node:fs";import{basename as dm$,dirname as Ew,isAbsolute as nm$,join as SJ,relative as pm$,resolve as FL}from"node:path";function D0$($,J){let X=new Set([J.managedConfig,J.syncState,J.providerHealthStatus,J.egressEngineStatus,J.manifestLastGood,J.managedSecretCacheFile,J.appliedState,J.oauthCredentialRoot,o3(J),J.runConfigRoot,J.egressProfileBundle,J.installInventory,J.managedResourceRoot,J.projectionRoot,SJ(J.instanceRoot,$.instanceId),J.daemonAuthToken,SJ(J.managedSecretRoot,"egress-secrets.json"),J.instanceData,J.sensitiveInstanceData,J.egressAddon,J.egressTransparentEnv,J.egressSystemCaFile,J.liveSyncEnvironmentIndex]);for(let Q of["clawdi-runtime-watch","clawdi-daemon","clawdi-runtime-sidecar"]){let W=`${Q}.service`;X.add(SJ(J.systemdSystemRoot,W)),X.add(SJ(J.systemdEnvRoot,`${W}.env`))}if($.companions?.filebrowser)X.add(SJ(J.systemdSystemRoot,"clawdi-files.service")),X.add(SJ(J.systemdEnvRoot,"clawdi-files.service.env"));return im$(J,X),[...X].sort()}function eC($){om$($.runtimeUserTargets,$.runtimeUserTrustedRoots,$.runtimeUserSymlinkTargets);let J=[...new Set($.rootTargets)].sort();for(let z of $.trustedRootDirectories)rm$(z);let X=[...new Set($.runtimeUserTargets)].sort(),Q=J.find((z)=>X.includes(z));if(Q)throw Error(`runtime mutation target has multiple owners: ${Q}`);let W=[...J,...X].sort();for(let[z,H]of W.entries()){let w=W.slice(z+1).find((V)=>V.startsWith(`${H}/`));if(w)throw Error(`runtime mutation targets overlap: ${H} and ${w}`)}let Y=[...new Set([...$.metadataTargets,...am$(W)])].sort(),G=Y.find((z)=>W.includes(z));if(G)throw Error(`runtime mutation target also used as metadata target: ${G}`);return{entries:new Map([...J.map((z)=>[z,sC(z,!0)]),...X.map((z)=>[z,sC(z,!1)]),...Y.map((z)=>[z,sm$(z)])])}}function om$($,J,X){let Q=[...new Set(J.map((G)=>FL(G)))].sort((G,z)=>z.length-G.length),W=[...new Set($.map((G)=>FL(G)))].sort(),Y=new Set(X.map((G)=>FL(G)));for(let G of Y)if(!W.includes(G))throw Error(`runtime-user symlink target is not a mutation target: ${G}`);for(let G of W){let z=Q.find((w)=>{let V=pm$(w,G);return V===""||!V.startsWith("..")&&!nm$(V)});if(!z)throw Error(`runtime-user mutation target is outside trusted roots: ${G}`);let H=G;while(!0){try{let V=r3(H);if(V.isSymbolicLink()&&(H!==G||!Y.has(G)))throw Error(`runtime-user mutation path contains a symlink: ${H}`);if(H!==G&&!V.isDirectory())throw Error(`runtime-user mutation ancestor is not a directory: ${H}`)}catch(V){if(!(V instanceof Error&&("code"in V)&&V.code==="ENOENT"))throw V}if(H===z)break;let w=Ew(H);if(w===H)throw Error(`runtime-user mutation target has no trusted boundary: ${G}`);H=w}}}function F0$($,J){return[J.runConfigRoot,J.systemdEnvRoot,J.installInventory,J.oauthCredentialRoot,J.managedResourceRoot,J.projectionRoot,SJ(J.instanceRoot,$.instanceId)]}function rm$($){let J;try{J=r3($)}catch(X){if(X.code==="ENOENT")return;throw X}if(!J.isDirectory()||J.isSymbolicLink())throw Error(`runtime managed directory is not a real directory: ${$}`);if((J.mode&18)!==0&&!j0$($))throw Error(`runtime managed directory is group/world writable: ${$}`);if(Q6()&&J.uid!==0)throw Error(`runtime managed directory is not root-owned: ${$}`)}function j0$($){let J=process.geteuid?.()??process.getuid?.(),X=Ew(FL($));for(;;){let Q=r3(X);if(Q.isSymbolicLink()||!Q.isDirectory())return!1;if(Q.uid===J&&(Q.mode&63)===0)return!0;let W=Ew(X);if(W===X)return!1;X=W}}function i3($){for(let[X,Q]of $.entries)if(Q.kind!=="metadata")jL(X,Q);let J=[...$.entries].filter((X)=>X[1].kind==="metadata");for(let[X,Q]of J.filter(([,W])=>W.existed).sort(([W],[Y])=>W.length-Y.length))jL(X,Q);for(let[X,Q]of J.filter(([,W])=>!W.existed).sort(([W],[Y])=>Y.length-W.length))jL(X,Q)}function im$($,J){if(!aC($.systemdSystemRoot))return;for(let X of tC($.systemdSystemRoot)){let Q=SJ($.systemdSystemRoot,X);if(X.endsWith(".service")&&(X.startsWith("clawdi-")||N0$(Q)))J.add(Q);if(!X.endsWith(".service.d"))continue;let W=SJ(Q,"10-clawdi-hosted.conf");if(N0$(W))J.add(W)}}function N0$($){try{return O9(O0$($,"utf-8"))}catch{return!1}}function am$($){return[...new Set($.filter((J)=>dm$(J)==="10-clawdi-hosted.conf").map((J)=>Ew(J)))].sort()}function sC($,J){let X;try{X=r3($)}catch(W){if(W.code==="ENOENT")return{kind:"missing"};throw W}if(X.isSymbolicLink())return{kind:"symlink",target:mm$($),uid:X.uid,gid:X.gid};if(X.isFile())return{kind:"file",content:O0$($),mode:X.mode&511,uid:X.uid,gid:X.gid};if(!X.isDirectory())throw Error(`unsupported runtime live-state path: ${$}`);let Q=X.mode&511;if(J&&(Q&18)!==0&&!j0$($))throw Error(`runtime live-state snapshot directory is group/world writable: ${$}`);if(J&&Q6()&&X.uid!==0)throw Error(`runtime live-state snapshot directory is not root-owned: ${$}`);return{kind:"directory",mode:Q,uid:X.uid,gid:X.gid,entries:new Map(tC($).sort().map((W)=>[W,sC(SJ($,W),J)]))}}function sm$($){try{let J=r3($);if(!J.isDirectory()||J.isSymbolicLink())throw Error(`runtime mutation metadata target is not a real directory: ${$}`);return{kind:"metadata",existed:!0,mode:J.mode&511,uid:J.uid,gid:J.gid}}catch(J){if(J.code==="ENOENT")return{kind:"metadata",existed:!1};throw J}}function DL($,J,X,Q){let W=r3($);if(W.uid===J&&W.gid===X)return;if(Q)hm$($,J,X);else um$($,J,X)}function jL($,J){if(J.kind==="metadata"){if(!J.existed){if(aC($)&&tC($).length===0)L0$($,{recursive:!0});return}if(!aC($))iC($,{recursive:!0,mode:J.mode});rC($,J.mode),DL($,J.uid,J.gid,!1);return}if(L0$($,{recursive:!0,force:!0}),J.kind==="missing")return;if(iC(Ew($),{recursive:!0}),J.kind==="symlink"){cm$(J.target,$),DL($,J.uid,J.gid,!0);return}if(J.kind==="file"){lm$($,J.content,{mode:J.mode}),rC($,J.mode),DL($,J.uid,J.gid,!1);return}iC($,{recursive:!0,mode:J.mode}),rC($,J.mode);for(let[X,Q]of J.entries)jL(SJ($,X),Q);DL($,J.uid,J.gid,!1)}var M0$=F(()=>{oC();V1()});import{createHash as P0$,randomUUID as R0$}from"node:crypto";import{chmodSync as T0$,closeSync as s3,existsSync as JX,fsyncSync as $x,lstatSync as Sw,mkdirSync as tm$,openSync as AL,readFileSync as PL,readSync as em$,realpathSync as RL,renameSync as E0$,rmSync as TL,statSync as $c$,writeSync as S0$}from"node:fs";import{basename as C0$,dirname as EL,join as W0,relative as Jc$,resolve as l1}from"node:path";function v0$($){return W0($.installInventory,Xc$)}function f0$($){let J=Wx(v0$($.paths));if(J)r0$(J,$.home);let X=new Set;if($.desiredRuntime)X.add($.desiredRuntime);if(J)X.add(J.artifact.runtime);return[...X]}function g0$($){let J=u0$($);if($.runtime==="hermes"&&!JX(W0(J.root,"package.json")))return[W0(a3(J),"node_modules")];let X=J.targets.map((Q)=>W0(J.root,Q.relativePath));if($.runtime==="hermes")X.push(W0(a3(J),"node_modules",".hermes-pkg-hash"));return X}function y0$($){let J=v0$($.paths),X=Wx(J);if(X)r0$(X,$.home);if(!$.desiredRuntime)return I0$(J,$.home);if(!$.appRoot)throw Error(`managed WhatsApp ${$.desiredRuntime} artifact root is unavailable`);if($.desiredRuntime==="hermes")Qc$($.home,$.appRoot);let Q=u0$({runtime:$.desiredRuntime,home:$.home,appRoot:$.appRoot}),W=h0$(Q),Y=W.version,G=Q.targets.map((Z)=>m0$(Q,Z));if(l0$(Q,G),X&&!Qx(X.artifact,Q)){let Z=I0$(J,$.home);if(Z.status==="rollback-refused")throw Error(`managed WhatsApp compatibility could not recover the previous artifact: ${Z.errors.join(", ")}`);X=null}let z=G.flatMap((Z)=>Z.hunks);if(!X){if(z.every((Z)=>Z.state==="after")){if(Q.runtime==="hermes")ML(a3(Q));return{status:"compatible",receiptPath:J}}if(!z.every((Z)=>Z.state==="before"))throw Error(`managed WhatsApp compatibility refused mixed before/after hunks without an ownership receipt for ${Q.runtime}`)}let H=X?X.artifact.baileys.observedVersion!==Y:!1,w=z.filter((Z)=>Z.state==="before");if(X&&H&&w.length===0){if(i0$(J),Q.runtime==="hermes")ML(a3(Q));return{status:"compatible",receiptPath:J}}if(X&&w.length===0){if(Q.runtime==="hermes")ML(a3(Q));return{status:"already-patched",receiptPath:J}}let V=Wc$(G,X,H),U=G.map((Z)=>d0$(Z,new Set(Z.hunks.filter((K)=>K.state==="before").map((K)=>K.hunk.id)),"after")),q=wc$(Q,Y,U,V);if(zc$(J,q),n0$(U,[{path:W.path,expectedSha256:W.sha256}]),Q.runtime==="hermes")ML(a3(Q));return{status:"applied",receiptPath:J}}function I0$($,J){let X=Wx($);if(!X)return{status:"inert",receiptPath:$};let Q=_L(X.artifact.runtime,J),W=[];if(!Qx(X.artifact,Q))W.push("managed WhatsApp compatibility receipt does not match the audited artifact");else if(Vc$(Q.root)){let Y=null;try{Y=h0$(Q)}catch(z){W.push(String(z))}let G=[];if(W.length===0)for(let z of Q.targets)try{G.push(m0$(Q,z))}catch(H){W.push(String(H))}if(W.length===0)try{l0$(Q,G)}catch(z){W.push(String(z))}if(W.length>0)return{status:"rollback-refused",receiptPath:$,errors:W};if(Y?.version===X.artifact.baileys.observedVersion){let z=new Map(X.artifact.targets.map((w)=>[w.relativePath,w])),H=G.map((w)=>{let V=z.get(w.target.relativePath);if(!V)throw Error("managed WhatsApp receipt target is missing");return d0$(w,new Set(V.ownedHunkIds),"before")});n0$(H,[{path:Y.path,expectedSha256:Y.sha256}])}}return i0$($),{status:"rolled-back",receiptPath:$}}function Qc$($,J){let X=W0($,".hermes","hermes-agent");if(l1(J)!==l1(X))throw Error(`managed WhatsApp Hermes app root must be ${X}`);let Q=W0(J,"scripts","whatsapp-bridge"),W=W0(Q,"node_modules","@whiskeysockets","baileys","package.json");if(JX(W))return;for(let z of["package.json","package-lock.json"])if(!JX(W0(Q,z)))throw Error(`managed WhatsApp Hermes bridge is missing ${z}`);let Y=W0($,".local","bin","npm"),G=V0(JX(Y)?Y:"npm",["ci","--ignore-scripts","--silent"],$,Q,{timeoutMs:300000});if(G.status!==0){let z=String(G.stderr||G.stdout||"npm ci failed").trim().slice(-1000);throw Error(`managed WhatsApp Hermes dependency install failed: ${z}`)}if(!JX(W))throw Error("managed WhatsApp Hermes dependency install did not produce Baileys")}function ML($){let J=W0($,"package.json"),X=W0($,"node_modules",".hermes-pkg-hash"),Q=`${Yx(J).slice(0,16)}
|
|
671
671
|
`;if(JX(X)){if(!Sw(X).isFile()||RL(X)!==l1(X))throw Error(`managed WhatsApp Hermes dependency stamp must be a real file: ${X}`);if(PL(X,"utf8")===Q)return}p0$(X,Q,420,493),b4(X)}function u0$($){if($.runtime==="openclaw"){let X=W0($.home,".openclaw");if(l1($.appRoot)!==l1(X))throw Error(`managed WhatsApp OpenClaw app root must be ${X}`);return _L("openclaw",$.home)}let J=W0($.home,".hermes","hermes-agent");if(l1($.appRoot)!==l1(J))throw Error(`managed WhatsApp Hermes app root must be ${J}`);return _L("hermes",$.home)}function _L($,J){if($==="openclaw")return{runtime:$,root:W0(J,".openclaw","extensions","whatsapp","node_modules","baileys"),packageName:"baileys",targets:b0$};let X=W0(J,".hermes","hermes-agent","scripts","whatsapp-bridge");return{runtime:$,root:W0(X,"node_modules","@whiskeysockets","baileys"),packageName:"@whiskeysockets/baileys",targets:b0$,hermesBridgeRoot:X}}function a3($){if(!$.hermesBridgeRoot)throw Error("managed WhatsApp Hermes bridge root is missing");return $.hermesBridgeRoot}function h0$($){Hc$($.root);let J=W0($.root,"package.json");o0$($.root,J);let X=PL(J,"utf8"),Q;try{Q=JSON.parse(X)}catch(z){throw Error(`managed WhatsApp compatibility could not read ${J}: ${String(z)}`)}let W=Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:null,Y=W?Reflect.get(W,"name"):null,G=W?Reflect.get(W,"version"):null;if(Y!==$.packageName)throw Error(`managed WhatsApp compatibility requires package ${$.packageName}; found ${String(Y)}`);if(typeof G!=="string"||!n4(G)||!G.startsWith("7."))throw Error(`managed WhatsApp compatibility requires valid Baileys SemVer major 7; found ${String(G)}`);return{version:G,path:J,sha256:Gx(X)}}function m0$($,J){let X=W0($.root,J.relativePath);if(!JX(X))throw Error(`managed WhatsApp compatibility artifact is missing ${X}`);o0$($.root,X);let Q=PL(X,"utf8");return{target:J,path:X,content:Q,sha256:Gx(Q),hunks:J.hunks.map((W)=>c0$(Q,W))}}function c0$($,J){let X=_0$($,J.before),Q=_0$($,J.after);return{hunk:J,beforeMatches:X,afterMatches:Q,state:X.length===1&&Q.length===0?"before":X.length===0&&Q.length===1?"after":"unknown"}}function _0$($,J){let X=[],Q=0;while(Q<=$.length-J.length){let W=$.indexOf(J,Q);if(W<0)break;X.push(W),Q=W+1}return X}function l0$($,J){let X=J.flatMap((Q)=>Q.hunks.flatMap((W)=>W.state==="unknown"?[`${Q.path}#${W.hunk.id} (before=${W.beforeMatches.length}, after=${W.afterMatches.length})`]:[]));if(X.length>0)throw Error(`managed WhatsApp compatibility patch refused non-unique or changed ${$.runtime} hunks: ${X.join(", ")}`)}function Wc$($,J,X){let Q=new Map((J?.artifact.targets??[]).map((W)=>[W.relativePath,W]));return new Map($.map((W)=>{let Y=new Set;if(!X)for(let G of Q.get(W.target.relativePath)?.ownedHunkIds??[])Y.add(G);for(let G of W.hunks)if(G.state==="before")Y.add(G.hunk.id);return[W.target.relativePath,Y]}))}function d0$($,J,X){let Q=new Set($.hunks.map((z)=>z.hunk.id));for(let z of J)if(!Q.has(z))throw Error(`managed WhatsApp patch references unknown hunk ${z}`);let Y=[...$.hunks.flatMap((z)=>{if(!J.has(z.hunk.id)||z.state===X)return[];if(z.state==="unknown")throw Error(`managed WhatsApp patch cannot mutate unknown hunk ${z.hunk.id}`);let H=z.state==="before"?z.hunk.before:z.hunk.after,w=X==="after"?z.hunk.after:z.hunk.before,U=(z.state==="before"?z.beforeMatches:z.afterMatches)[0];if(U===void 0)throw Error(`managed WhatsApp hunk ${z.hunk.id} is missing`);return[{id:z.hunk.id,offset:U,source:H,replacement:w}]})].sort((z,H)=>z.offset-H.offset);for(let z=1;z<Y.length;z+=1){let H=Y[z-1],w=Y[z];if(H&&w&&H.offset+H.source.length>w.offset)throw Error(`managed WhatsApp patch hunks overlap: ${H.id} and ${w.id}`)}let G=$.content;for(let z of Y.reverse())G=`${G.slice(0,z.offset)}${z.replacement}${G.slice(z.offset+z.source.length)}`;for(let z of $.hunks){let H=c0$(G,z.hunk),w=J.has(z.hunk.id)?X:z.state;if(H.state!==w)throw Error(`managed WhatsApp hunk mutation verification failed for ${z.hunk.id}`)}return{state:$,content:G,observedBeforeSha256:$.sha256,observedAfterSha256:Gx(G)}}function n0$($,J=[]){let X=$.flatMap((Q)=>Q.content===Q.state.content?[]:[{path:Q.state.path,expectedSha256:Q.observedBeforeSha256,content:Q.content}]);Gc$(X,[...J,...$.map((Q)=>({path:Q.state.path,expectedSha256:Q.observedBeforeSha256}))]);for(let Q of $)if(Yx(Q.state.path)!==Q.observedAfterSha256)throw Error(`managed WhatsApp compatibility verification failed for ${Q.state.path}`)}function Yc$($,J){let X=W0(EL($),`.${C0$($)}.clawdi-stage-${R0$()}`),Q=$c$($).mode&511,W=null;try{W=AL(X,"wx",Q);let Y=Buffer.from(J),G=0;while(G<Y.length)G+=S0$(W,Y,G);return $x(W),s3(W),W=null,T0$(X,Q),b4(X),X}catch(Y){throw TL(X,{force:!0}),Y}finally{if(W!==null)s3(W)}}function Gc$($,J=$){let X=[];try{for(let Q of $)X.push({...Q,stagingPath:Yc$(Q.path,Q.content)});for(let Q of J)if(Yx(Q.path)!==Q.expectedSha256)throw Error(`managed WhatsApp compatibility artifact changed during reconcile: ${Q.path}`);for(let Q of X)E0$(Q.stagingPath,Q.path),b4(Q.path),Xx(EL(Q.path))}finally{for(let Q of X)TL(Q.stagingPath,{force:!0})}}function zc$($,J){p0$($,`${JSON.stringify(J,null,2)}
|