clawdi 0.13.107 → 0.13.108
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 +5 -5
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -241,7 +241,7 @@ ${J.comment}`:J.comment}this.doc.range[2]=J.offset;break}default:this.errors.pus
|
|
|
241
241
|
`)}function _P$($=LV){return dN($,"table"),[`# ${ZY}`,`delete table inet ${$}`,""].join(`
|
|
242
242
|
`)}function wa($=process.env){let J=lN($),X=ZP$({table:J.nftTable,runtimeUid:J.runtimeUid,egressUid:J.egressUid,transparentPort:J.transparentPort,replaceExistingTable:La(J.nftTable)});return Ka(X,"apply"),{table:J.nftTable,runtimeUid:J.runtimeUid,egressUid:J.egressUid,transparentPort:J.transparentPort}}function qa($=process.env){let J=lN($);MP$(J.nftTable)}function MP$($=LV){if(!La($))return;Ka(_P$($),"cleanup")}function lN($=process.env){let J=IP$($.CLAWDI_EGRESS_ENV_FILE),Q={...J?bP$(J):{}};for(let[B,w]of Object.entries($))if(B.startsWith("CLAWDI_"))Q[B]=w;let W=Q1(Q,"CLAWDI_RUNTIME_USER"),Y=oC(Q,"CLAWDI_RUNTIME_UID"),G=oC(Q,"CLAWDI_RUNTIME_GID");ja(G,"CLAWDI_RUNTIME_GID");let z=Ua(Q,"CLAWDI_EGRESS_UID"),U=Ua(Q,"CLAWDI_EGRESS_GID"),H=oC(Q,"CLAWDI_EGRESS_TRANSPARENT_PORT"),V=Q1(Q,"CLAWDI_EGRESS_NFT_TABLE");return dN(V,"CLAWDI_EGRESS_NFT_TABLE"),{envFile:J,runtimeUser:W,runtimeUid:Y,runtimeGid:G,egressUid:z,egressGid:U,transparentPort:H,nftTable:V,profileBundlePath:Q1(Q,"CLAWDI_EGRESS_PROFILE_BUNDLE"),secretFilePath:Q.CLAWDI_EGRESS_SECRET_FILE?.trim()??"",caDir:Q1(Q,"CLAWDI_EGRESS_CA_DIR"),caCertPath:Q1(Q,"CLAWDI_EGRESS_CA_CERT"),systemCaBundle:Q1(Q,"CLAWDI_EGRESS_SYSTEM_CA_BUNDLE"),engineVersion:Q1(Q,"CLAWDI_EGRESS_ENGINE_VERSION"),engineUrl:Q1(Q,"CLAWDI_EGRESS_ENGINE_URL"),engineSha256:Q1(Q,"CLAWDI_EGRESS_ENGINE_SHA256").toLowerCase(),engineBinaryPath:Q1(Q,"CLAWDI_EGRESS_ENGINE_BINARY_PATH"),addonPath:Q1(Q,"CLAWDI_EGRESS_ADDON_PATH"),addonSha256:Q1(Q,"CLAWDI_EGRESS_ADDON_SHA256").toLowerCase()}}function bP$($){let J={};for(let X of DP$($,"utf-8").split(/\r?\n/)){let Q=X.trim();if(!Q||Q.startsWith("#")||!Q.includes("="))continue;let[W,...Y]=Q.split("="),G=W?.trim()??"";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(G))continue;J[G]=AP$(Y.join("=").trim())}return J}function rC($,J){if(!/^[0-9]+$/.test($))throw Error(`${J} must be a positive Linux UID/GID`);let X=Number($);if(!Number.isInteger(X)||X<1||X>4294967294)throw Error(`${J} must be a positive Linux UID/GID`);return X}function Ka($,J){let X=Va("nft",["-f","-"],{input:$,encoding:"utf8",stdio:["pipe","pipe","pipe"]});if(X.status!==0){let Q=[X.stdout,X.stderr].filter(Boolean).join(`
|
|
243
243
|
`).trim();throw Error(`nft ${J} failed${Q?`
|
|
244
|
-
${Q}`:""}`)}}function La($){return dN($,"table"),Va("nft",["list","table","inet",$],{encoding:"utf8",stdio:["ignore","ignore","ignore"]}).status===0}function Q1($,J){let X=$[J]?.trim();if(!X)throw Error(`${J} is required for transparent egress`);return X}function oC($,J){let X=Q1($,J),Q=Number.parseInt(X,10);if(!Number.isInteger(Q)||String(Q)!==X)throw Error(`${J} must be numeric`);return Q}function Ua($,J){return rC(Q1($,J),J)}function IP$($){let J=$?.trim();return J?J:void 0}function AP$($){if($.length>=2&&$[0]===$.at(-1)&&($[0]==='"'||$[0]==="'"))$=$.slice(1,-1);return $.replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function Ha($,J){ja($,J)}function ja($,J){if(!Number.isInteger($)||$<0||$>4294967295)throw Error(`${J} must be a numeric Linux id`)}function RP$($){if(!Number.isInteger($)||$<1||$>65535)throw Error("transparentPort must be a TCP port")}function dN($,J){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test($))throw Error(`${J} must be a safe nft identifier`)}var ZY="clawdi-transparent-egress-v1",LV="clawdi_transparent_egress",Ba=27212;var _Y=()=>{};import{execFileSync as PP$,spawnSync as UQ}from"node:child_process";import{accessSync as EP$,chownSync as TP$,constants as CP$}from"node:fs";import{isAbsolute as SP$,join as Na}from"node:path";function E0($){try{return EP$($,CP$.X_OK),!0}catch{return!1}}function pN($){return UQ("/bin/sh",["-c",'command -v "$1" >/dev/null 2>&1',"sh",$],{env:process.env,stdio:"ignore"}).status===0}function HQ($){return SP$($)?E0($):pN($)}function fP$($=pN){let J;return{resolve(X){if(X.currentUid===X.targetUid)return"none";if(X.currentUid!==0)throw Error(`cannot drop privileges to ${X.targetUser}: no supported mechanism`);if(J===void 0){J=null;for(let W of Oa)if($(W.mechanism)){J=W.mechanism;break}}let Q=Oa.find((W)=>W.mechanism===J);if(J===null||X.targetKind==="numeric"&&!Q?.supportsNumericIdentity)throw Error(`cannot drop privileges to ${X.targetUser}: no supported mechanism`);return J}}}function c8($,J,X,Q,W={}){let Y={...W.environment,HOME:J,USER:$,LOGNAME:$},G="env",z=[...Object.entries(Y).map(([V,B])=>`${V}=${B}`),X,...Q],U=W.runtimeUid??X9($),H=(W.resolver??Za).resolve({currentUid:W.currentUid??Ma(),targetUid:U,targetUser:$,targetKind:"named"});if(H==="none")return{command:X,args:Q,env:Y};if(H==="setpriv"){let V=W.runtimeGid??l8($);return{command:H,args:[`--reuid=${U}`,`--regid=${V}`,"--init-groups","--","env",...z],env:Y}}if(H==="runuser")return{command:H,args:["--preserve-environment","-u",$,"--","env",...z],env:Y};return{command:H,args:["--preserve-environment","--shell","/bin/sh","--command",'exec "$0" "$@"',$,"env",...z],env:Y}}function _a($,J,X,Q,W={}){let Y=`${$}:${J}`;if($===0||J===0)throw Error(`cannot drop privileges to ${Y}: target identity must be non-root`);let G=(W.resolver??Za).resolve({currentUid:W.currentUid??Ma(),targetUid:$,targetUser:Y,targetKind:"numeric"});if(G==="none")return{command:X,args:Q};if(G==="setpriv")return{command:G,args:[`--reuid=${$}`,`--regid=${J}`,"--clear-groups","--",X,...Q]};throw Error(`cannot drop privileges to ${Y}: no supported mechanism`)}function O6(){return typeof process.geteuid==="function"&&process.geteuid()===0}function Ma(){
|
|
244
|
+
${Q}`:""}`)}}function La($){return dN($,"table"),Va("nft",["list","table","inet",$],{encoding:"utf8",stdio:["ignore","ignore","ignore"]}).status===0}function Q1($,J){let X=$[J]?.trim();if(!X)throw Error(`${J} is required for transparent egress`);return X}function oC($,J){let X=Q1($,J),Q=Number.parseInt(X,10);if(!Number.isInteger(Q)||String(Q)!==X)throw Error(`${J} must be numeric`);return Q}function Ua($,J){return rC(Q1($,J),J)}function IP$($){let J=$?.trim();return J?J:void 0}function AP$($){if($.length>=2&&$[0]===$.at(-1)&&($[0]==='"'||$[0]==="'"))$=$.slice(1,-1);return $.replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function Ha($,J){ja($,J)}function ja($,J){if(!Number.isInteger($)||$<0||$>4294967295)throw Error(`${J} must be a numeric Linux id`)}function RP$($){if(!Number.isInteger($)||$<1||$>65535)throw Error("transparentPort must be a TCP port")}function dN($,J){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test($))throw Error(`${J} must be a safe nft identifier`)}var ZY="clawdi-transparent-egress-v1",LV="clawdi_transparent_egress",Ba=27212;var _Y=()=>{};import{execFileSync as PP$,spawnSync as UQ}from"node:child_process";import{accessSync as EP$,chownSync as TP$,constants as CP$}from"node:fs";import{isAbsolute as SP$,join as Na}from"node:path";function E0($){try{return EP$($,CP$.X_OK),!0}catch{return!1}}function pN($){return UQ("/bin/sh",["-c",'command -v "$1" >/dev/null 2>&1',"sh",$],{env:process.env,stdio:"ignore"}).status===0}function HQ($){return SP$($)?E0($):pN($)}function fP$($=pN){let J;return{resolve(X){if(X.currentUid===X.targetUid)return"none";if(X.currentUid!==0)throw Error(`cannot drop privileges to ${X.targetUser}: no supported mechanism`);if(J===void 0){J=null;for(let W of Oa)if($(W.mechanism)){J=W.mechanism;break}}let Q=Oa.find((W)=>W.mechanism===J);if(J===null||X.targetKind==="numeric"&&!Q?.supportsNumericIdentity)throw Error(`cannot drop privileges to ${X.targetUser}: no supported mechanism`);return J}}}function c8($,J,X,Q,W={}){let Y={...W.environment,HOME:J,USER:$,LOGNAME:$},G="env",z=[...Object.entries(Y).map(([V,B])=>`${V}=${B}`),X,...Q],U=W.runtimeUid??X9($),H=(W.resolver??Za).resolve({currentUid:W.currentUid??Ma(),targetUid:U,targetUser:$,targetKind:"named"});if(H==="none")return{command:X,args:Q,env:Y};if(H==="setpriv"){let V=W.runtimeGid??l8($);return{command:H,args:[`--reuid=${U}`,`--regid=${V}`,"--init-groups","--","env",...z],env:Y}}if(H==="runuser")return{command:H,args:["--preserve-environment","-u",$,"--","env",...z],env:Y};return{command:H,args:["--preserve-environment","--shell","/bin/sh","--command",'exec "$0" "$@"',$,"env",...z],env:Y}}function _a($,J,X,Q,W={}){let Y=`${$}:${J}`;if($===0||J===0)throw Error(`cannot drop privileges to ${Y}: target identity must be non-root`);let G=(W.resolver??Za).resolve({currentUid:W.currentUid??Ma(),targetUid:$,targetUser:Y,targetKind:"numeric"});if(G==="none")return{command:X,args:Q};if(G==="setpriv")return{command:G,args:[`--reuid=${$}`,`--regid=${J}`,"--clear-groups","--",X,...Q]};throw Error(`cannot drop privileges to ${Y}: no supported mechanism`)}function O6(){return typeof process.geteuid==="function"&&process.geteuid()===0}function Ma(){let $=process.getuid?.(),J=process.geteuid?.();if($===0||J===0)return 0;if($!==void 0&&J!==void 0&&$!==J)return;return J??$}function X9($){let J=nN(process.env.CLAWDI_RUNTIME_UID?.trim()??"");if(J!==null)return J;let X=nN($);if(X!==null)return X;let Q=UQ("id",["-u",$],{encoding:"utf8"});if(Q.status===0){let W=nN(Q.stdout.trim());if(W!==null)return W}if($==="clawdi")return 10001;throw Error(`could not resolve uid for ${$}`)}function nN($){if(!/^(0|[1-9]\d*)$/.test($))return null;let J=Number($);return Number.isInteger(J)&&J<=4294967295?J:null}function Da($,J){let Q=UQ("id",[J==="uid"?"-u":"-g",$],{encoding:"utf8",timeout:Fa});if(Q.error&&"code"in Q.error&&Q.error.code==="ETIMEDOUT")throw new m8(`runtime user ${J} probe for ${$}`,Fa);if(Q.status!==0)throw Error(`could not resolve ${J} for runtime user ${$}`);let W=nN(Q.stdout.trim());if(W===null)throw Error(`runtime user ${$} resolved an invalid ${J}`);return W}function ba($){return{uid:Da($,"uid"),gid:Da($,"gid")}}function Ia($,J,X={}){let Q=J===null?null:`/run/user/${J}`,W={...process.env,HOME:$,PATH:[Na($,".local","bin"),Na($,".openclaw","bin"),process.env.PATH].filter(Boolean).join(":"),...Q?{XDG_RUNTIME_DIR:Q,DBUS_SESSION_BUS_ADDRESS:`unix:path=${Q}/bus`}:{}};aC(W);for(let[Y,G]of Object.entries(X.environmentOverrides??{}))if(G===void 0)delete W[Y];else W[Y]=G;if(X.egressSystemCaFile)UX(W,{caFile:X.egressSystemCaFile});return W}function aC($){for(let J of["NPM_CONFIG_PREFIX","npm_config_prefix","NPM_CONFIG_CACHE","npm_config_cache","XDG_CONFIG_HOME","XDG_CACHE_HOME","XDG_DATA_HOME","XDG_STATE_HOME","HERMES_HOME","UV_CACHE_DIR","UV_PYTHON_INSTALL_DIR","UV_PYTHON_BIN_DIR","UV_TOOL_DIR","UV_TOOL_BIN_DIR","UV_MANAGED_PYTHON"])delete $[J]}function l8($){let J=Number.parseInt(process.env.CLAWDI_RUNTIME_GID?.trim()??"",10);if(Number.isInteger(J)&&J>=0&&J<=4294967295)return J;let X=UQ("id",["-g",$],{encoding:"utf8"});if(X.status===0){let Q=Number.parseInt(X.stdout.trim(),10);if(Number.isInteger(Q)&&Q>=0&&Q<=4294967295)return Q}if($==="clawdi")return 10001;throw Error(`could not resolve runtime gid for ${$}`)}function iN(){return Aa("CLAWDI_EGRESS_UID",10002)}function MY(){return Aa("CLAWDI_EGRESS_GID",10002)}function Aa($,J){let X=process.env[$]?.trim();return X?rC(X,$):J}function v4($){let J=process.env.CLAWDI_RUNTIME_USER?.trim()??"";if(!O6()||!J||J==="root")return;let X=UQ("id",["-u",J],{encoding:"utf8"}),Q=UQ("id",["-g",J],{encoding:"utf8"});if(X.status!==0||Q.status!==0)return;let W=Number.parseInt(X.stdout.trim(),10),Y=Number.parseInt(Q.stdout.trim(),10);if(!Number.isFinite(W)||!Number.isFinite(Y))return;TP$($,W,Y)}function Y0($){let J=process.env.CLAWDI_RUNTIME_USER?.trim();if(!O6()||!J||J==="root")return $();let X=X9(J),Q=l8(J);if((X===0||Q===0)&&J!=="0")throw Error(`runtime user ${J} resolved to a root filesystem identity`);return cN({uid:X,gid:Q},$)}function s$($,J,X,Q,W={}){let Y=W.runtimeUser??process.env.CLAWDI_RUNTIME_USER?.trim(),G=Boolean(Y&&Y!=="root"),z=G?W.runtimeUid??X9(Y??""):null,U=G?c8(Y??"",X,$,J,{runtimeUid:z??void 0,runtimeGid:W.runtimeGid,resolver:W.resolver}):{command:$,args:J,env:{}};return UQ(U.command,U.args,{env:{...Ia(X,z,W),...U.env,...W.environment},cwd:Q,encoding:"utf8",input:W.input,maxBuffer:W.maxBufferBytes,timeout:W.timeoutMs})}function Q9($,J,X,Q,W,Y={}){let G=Y.runtimeUser??process.env.CLAWDI_RUNTIME_USER?.trim(),z=Boolean(G&&G!=="root"),U=z?Y.runtimeUid??X9(G??""):null,H=z?c8(G??"",Q,$,J,{runtimeUid:U??void 0,runtimeGid:Y.runtimeGid,resolver:Y.resolver}):{command:$,args:J,env:{}};try{PP$(H.command,H.args,{input:X,env:{...Ia(Q,U,Y),...H.env},cwd:W,stdio:"pipe",timeout:Y.timeoutMs})}catch(V){if(Y.timeoutMs!==void 0&&V instanceof Error&&"code"in V&&V.code==="ETIMEDOUT")throw new m8(`runtime command ${$} ${J.join(" ")}`.trim(),Y.timeoutMs);throw V}}var Fa=5000,m8,Oa,Za;var p0=D(()=>{iC();v8();_Y();m8=class m8 extends Error{operation;timeoutMs;constructor($,J){super(`${$} timed out after ${J}ms`);this.operation=$;this.timeoutMs=J;this.name="RuntimeUserCommandTimeoutError"}};Oa=[{mechanism:"setpriv",supportsNumericIdentity:!0},{mechanism:"runuser",supportsNumericIdentity:!1},{mechanism:"su",supportsNumericIdentity:!1}];Za=fP$()});import{createHash as Ca}from"node:crypto";import{chmodSync as xP$,existsSync as kP$,lstatSync as W9,mkdirSync as Ra,mkdtempSync as Sa,readdirSync as tC,readFileSync as oN,rmSync as rN,writeFileSync as vP$}from"node:fs";import{validateHeaderName as gP$,validateHeaderValue as yP$}from"node:http";import{isIP as hP$}from"node:net";import{tmpdir as fa}from"node:os";import{dirname as aN,join as P1}from"node:path";import{createGunzip as uP$}from"node:zlib";function jV($){let J=Ca("sha256");for(let X of[...$].sort((Q,W)=>Buffer.compare(Buffer.from(Q.path,"utf8"),Buffer.from(W.path,"utf8"))))J.update(`${X.mode.toString(8)}\x00${X.path}\x00${X.bytes.length}\x00${NV(X.bytes)}
|
|
245
245
|
`,"utf8");return`sha256-tree-v1:${J.digest("hex")}`}function zE$($){let[J,X=""]=$.split(":");return[Number.parseInt(J??"",16),X.split(",").map((Q)=>String.fromCodePoint(Number.parseInt(Q,16))).join("")]}function ca($){let J="";for(let X of $){let Q=X.codePointAt(0);if(Q===void 0)continue;let W=UE$.get(Q);if(W!==void 0)J+=W;else if(Q>=5024&&Q<=5109||Q>=5112&&Q<=5117||Q>=43888&&Q<=43967)J+=X.toUpperCase();else J+=X.toLowerCase()}return J}function NV($){return Ca("sha256").update($).digest("hex")}function la($,J){let X=J.source.type==="github"?[J.source.type,J.source.url,J.source.path,J.source.commit]:[J.source.type,J.source.url,J.source.archiveDigest];return NV(JSON.stringify([J.installationId,$,J.version,J.agentPluginsSchema,...X,J.contentDigest]))}function HE$($,J){return eC.parse({...J,ownershipIdentity:la($,J)})}function sN($){return P1($.statusRoot,"runtime-agent-plugin-receipts.json")}function VQ($){let J=sN($),X;try{X=W9(J)}catch(Q){if(Q instanceof Error&&"code"in Q&&Q.code==="ENOENT")return null;throw Error("Agent Plugin receipts could not be inspected")}if(!X.isFile()||X.isSymbolicLink()||X.size>oP$)throw Error("Agent Plugin receipts are not a trusted regular file");if((X.mode&511)!==384)throw Error("Agent Plugin receipts do not have private file permissions");if(typeof process.getuid==="function"&&X.uid!==process.getuid())throw Error("Agent Plugin receipts do not have the expected file owner");try{let Q=JSON.parse(oN(J,"utf8"));return ma.parse(Q)}catch{throw Error("Agent Plugin receipts do not match the expected schema")}}function da($,J){let X=sN(J);if(!$||Object.keys($.installations).length===0){rN(X,{force:!0});return}let Q=ma.parse($),W=VQ(J);if(W&&JSON.stringify(W)===JSON.stringify(Q))return;p4(J,X,`${JSON.stringify(Q,null,2)}
|
|
246
246
|
`,{mode:384,dirMode:493});let Y=VQ(J);if(JSON.stringify(Y)!==JSON.stringify(Q))throw Error("Agent Plugin receipts did not pass post-write verification")}function tN($,J){let X=P1($.cacheRoot,"agent-plugins",J);return{archive:P1(X,"source.tar.gz"),receipt:P1(X,"receipt.json")}}function na($){return P1($.cacheRoot,"agent-plugins")}function Pa($,J){try{return W9(aN(tN($,J).archive)),!0}catch(X){if(X instanceof Error&&"code"in X&&X.code==="ENOENT")return!1;throw X}}function FV($,J,X={}){if(!/^[a-f0-9]{64}$/.test(J))return!1;let Q=na($),W=P1(Q,J);if(aN(W)!==Q)return!1;try{let Y=W9(Q);if(!Y.isDirectory()||Y.isSymbolicLink())return!1;let G=W9(W);if(!G.isDirectory()||G.isSymbolicLink())return!1;let z=tC(W);if(X.allowIncomplete!==!0&&oa($,J)===null)return!1;for(let U of z){if(U!=="source.tar.gz"&&U!=="receipt.json")return!1;let H=W9(P1(W,U));if(!H.isFile()||H.isSymbolicLink())return!1}return rN(W,{recursive:!0}),!0}catch(Y){if(Y instanceof Error&&"code"in Y&&Y.code==="ENOENT")return!1;throw Y}}function VE$($,J){let{archive:X}=tN($,J),Q=aN(X);try{let W=W9(Q);if(!W.isDirectory()||W.isSymbolicLink())throw Error("Agent Plugin cache ownership path is not a trusted directory")}catch(W){if(W instanceof Error&&"code"in W&&W.code==="ENOENT")return;throw W}}function pa($,J){if(!$)return;for(let X of $.transientCacheOwnerships)FV(J,X,{allowIncomplete:!0})}function ia($,J,X=[]){let Q=new Set(Object.values($?.installations??{}).map((G)=>G.ownershipIdentity));for(let G of X)Q.add(G);let W=na(J),Y;try{let G=W9(W);if(!G.isDirectory()||G.isSymbolicLink())return;Y=tC(W)}catch(G){if(G instanceof Error&&"code"in G&&G.code==="ENOENT")return;throw G}for(let G of Y)if(/^[a-f0-9]{64}$/.test(G)&&!Q.has(G))FV(J,G)}function oa($,J){let X=tN($,J);try{let Q=W9(X.archive),W=W9(X.receipt);if(!Q.isFile()||Q.isSymbolicLink()||Q.size>ka||(Q.mode&511)!==384||!W.isFile()||W.isSymbolicLink()||W.size>rP$||(W.mode&511)!==384||typeof process.getuid==="function"&&(Q.uid!==process.getuid()||W.uid!==process.getuid()))return null;let Y=JSON.parse(oN(X.receipt,"utf8")),G=tP$.parse(Y),z=oN(X.archive);if(G.ownershipIdentity!==J||NV(z)!==G.archiveSha256)return null;return z}catch{return null}}function BE$($,J,X){VE$($,J);let Q=tN($,J),W=NV(X);try{p4($,Q.archive,X,{mode:384,dirMode:448}),p4($,Q.receipt,`${JSON.stringify({schemaVersion:xa,ownershipIdentity:J,archiveSha256:W},null,2)}
|
|
247
247
|
`,{mode:384,dirMode:448})}catch(Y){throw FV($,J,{allowIncomplete:!0}),Y}}function OV($){let J=$.split("/");return $.length>0&&Buffer.byteLength($,"utf8")<=pP$&&!s7($)&&!$.includes("\\")&&J.every((X)=>X&&X!=="."&&X!=="..")}function Ea($){return $==="File"||$==="OldFile"||$==="ContiguousFile"}async function wE$($){await new Promise((J,X)=>{let Q=0,W=!1,Y=uP$(),G=(z)=>{if(W)return;W=!0,Y.destroy(),X(z)};Y.on("error",G),Y.on("data",(z)=>{if(Q+=z.length,Q>nP$)G(Error("Agent Plugin repository archive exceeds the expansion limit"))}),Y.on("end",()=>{if(W)return;W=!0,J()}),Y.end($)})}async function qE$($,J,X){await wE$(J);let Q=null,W=0,Y=0,G=0;if(await new Promise((U,H)=>{let V=kW({cwd:$,gzip:!0,filter:(B,w)=>{let q=B.replace(/\/$/,"").split("/");if(B.startsWith("/")||B.includes("\\")||q.some((_)=>_==="."||_===".."||s7(_)))throw Error("Agent Plugin repository archive contains an unsafe path");let L=q[0];if(!L)return!1;if(Q===null)Q=L;if(Q!==L)throw Error("Agent Plugin repository archive has multiple roots");let N=q.slice(1).join("/");if(X!==""&&N!==X&&!N.startsWith(`${X}/`))return!1;let F=X===""?N:N.slice(X.length).replace(/^\//,"");if(F&&!OV(F))throw Error("Agent Plugin package contains an unsafe path");if(W+=1,W>va)throw Error("Agent Plugin package exceeds 2000 entries");let O="type"in w?w.type:void 0;if(O!=="Directory"&&!Ea(O))throw Error("Agent Plugin package contains a non-regular entry");if(Ea(O)){if(Y+=1,Y>ga)throw Error("Agent Plugin package exceeds 1000 files");if(!Number.isSafeInteger(w.size)||w.size<0||w.size>ha)throw Error("Agent Plugin package file exceeds 10 MiB");if(G+=w.size,G>ya)throw Error("Agent Plugin package exceeds 50 MiB")}return!0}});V.on("close",U),V.on("error",H),V.end(J)}),!Q)throw Error("Agent Plugin repository archive is empty");let z=P1($,Q,...X.split("/"));if(!kP$(z)||!W9(z).isDirectory())throw Error("Agent Plugin package path does not exist in the pinned source");return z}function ra($,J={}){let X=W9($);if(!X.isDirectory()||X.isSymbolicLink())throw Error("Agent Plugin package root is not a trusted directory");let Q=[],W=new Set,Y=0,G=0,z=(U,H)=>{for(let V of tC(U).sort((B,w)=>Buffer.compare(Buffer.from(B,"utf8"),Buffer.from(w,"utf8")))){if(J.ignoreTopLevelGitMetadata&&H===""&&V===".git")continue;let B=H?`${H}/${V}`:V;if(!OV(B))throw Error("Agent Plugin package contains an unsafe path");let w=ca(B);if(W.has(w))throw Error("Agent Plugin package contains a case-fold path collision");if(W.add(w),Y+=1,Y>va)throw Error("Agent Plugin package exceeds 2000 entries");let q=P1(U,V),L=W9(q);if(L.isDirectory()&&!L.isSymbolicLink()){z(q,B);continue}if(!L.isFile()||L.isSymbolicLink())throw Error("Agent Plugin package contains a non-regular entry");if(Q.length>=ga)throw Error("Agent Plugin package exceeds 1000 files");if(L.size>ha)throw Error("Agent Plugin package file exceeds 10 MiB");if(G+=L.size,G>ya)throw Error("Agent Plugin package exceeds 50 MiB");let N=oN(q);if(N.length!==L.size)throw Error("Agent Plugin package changed while reading");Q.push({path:B,mode:(L.mode&73)!==0?33261:33188,bytes:N})}};return z($,""),Q.sort((U,H)=>Buffer.compare(Buffer.from(U.path,"utf8"),Buffer.from(H.path,"utf8"))),{digest:jV(Q),tree:Q}}function $S($,J={}){return ra($,J).digest}function aa($,J){if(!$)throw Error(`${J} must be a regular file at the package root`);if($.bytes.length>iP$)throw Error(`${J} is too large`);try{let X=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode($.bytes));return eP$.parse(X)}catch{throw Error(`${J} must be a valid JSON object`)}}function KE$($,J){try{return new TextDecoder("utf-8",{fatal:!0}).decode($.bytes)}catch{throw Error(`${J} must be valid UTF-8`)}}function LE$($){let J=$.filter((Q)=>Q.path.startsWith("skills/")),X=new Set;for(let Q of J){let W=Q.path.split("/"),Y=W[1];if(!Y||!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(Y)||W.length<3)throw Error("Agent Plugin contains an invalid Skill path");X.add(Y)}for(let Q of X){let W=$.find((H)=>H.path===`skills/${Q}/SKILL.md`);if(!W)throw Error("Agent Plugin Skill is missing SKILL.md");let G=KE$(W,"Agent Plugin SKILL.md").replace(/^\uFEFF/,"").match(/^---\r?\n([\s\S]*?)\r?\n---(?:\s*\r?\n|$)/);if(!G)throw Error("Agent Plugin SKILL.md has invalid frontmatter");let z=qV(G[1]??"",{uniqueKeys:!0});if(z.errors.length>0)throw Error("Agent Plugin SKILL.md has invalid frontmatter");let U=K.object({name:K.string().min(1).max(64),description:K.string().min(1).max(1024).refine((H)=>H.trim().length>0),license:K.string().optional(),compatibility:K.string().min(1).max(500).optional(),metadata:K.record(K.string(),K.string()).optional(),"allowed-tools":K.string().optional()}).strict().safeParse(z.toJS());if(!U.success||U.data.name!==Q)throw Error("Agent Plugin SKILL.md frontmatter does not match its Skill directory")}return X.size}function jE$($){let J;if($.startsWith("./"))J=$.slice(2);else if($===bY||$===IY)return;else if($.startsWith(`${bY}/`))J=$.slice(bY.length+1);else if($.startsWith(`${IY}/`))J=$.slice(IY.length+1);else throw Error("Agent Plugin MCP path is outside the portable package boundary");if(!OV(J))throw Error("Agent Plugin MCP path is outside the portable package boundary")}function NE$($,J){if($==="./"||$===bY||$===IY)return;let X,Q=!1;if($.startsWith("./"))X=$.slice(2),Q=!0;else if($.startsWith(`${bY}/`))X=$.slice(bY.length+1),Q=!0;else if($.startsWith(`${IY}/`))X=$.slice(IY.length+1);else throw Error("Agent Plugin MCP cwd is outside the portable package boundary");if(!OV(X)||oj(X))throw Error("Agent Plugin MCP cwd is outside the portable package boundary");if(Q&&!J.some((W)=>W.path.startsWith(`${X}/`)))throw Error("Agent Plugin MCP cwd is not a package directory")}function sa($){let J=$.indexOf("://");if(J<0)return null;let X=$.slice(J+3),Q=X.search(/[/?#]/);return(Q<0?X:X.slice(0,Q))||null}function FE$($){let J=sa($);if(!J||J.includes("@"))return null;if(J.startsWith("[")){let Q=J.indexOf("]");if(Q<0||!/^(?::[0-9]+)?$/.test(J.slice(Q+1)))return null;return J.slice(1,Q)}let X=J.lastIndexOf(":");if(X<0)return J;if(J.indexOf(":")!==X||!/^[0-9]+$/.test(J.slice(X+1)))return null;return J.slice(0,X)}function OE$($){let J=FE$($)?.toLowerCase();if(!J)return!1;return J==="localhost"||J==="::1"||J==="0:0:0:0:0:0:0:1"||hP$(J)===4&&J.split(".")[0]==="127"}function DE$($){if(oj($.url))throw Error("Agent Plugin remote MCP URL cannot contain credential templates");if($.url.includes("\\")||/[\s\u0085]/u.test($.url)||[...$.url].some((W)=>W.charCodeAt(0)<32))throw Error("Agent Plugin remote MCP URL is invalid");let J;try{J=new URL($.url)}catch{throw Error("Agent Plugin remote MCP URL is invalid")}let X=sa($.url);if(J.protocol!=="https:"&&J.protocol!=="http:"||!X||X.includes("@")||$.url.includes("#")||J.username!==""||J.password!==""||J.hash!==""||!J.hostname)throw Error("Agent Plugin remote MCP URL is invalid");if(J.protocol==="http:"){if(!OE$($.url))throw Error("Agent Plugin remote MCP URL must use HTTPS")}let Q=new Set;if(Object.keys($.headers??{}).length>128)throw Error("Agent Plugin remote MCP headers are invalid");for(let[W,Y]of Object.entries($.headers??{})){let G=W.toLowerCase();if(ij(W)||oj(Y)||Y.length>0&&KT(Y))throw Error("Agent Plugin remote MCP headers cannot carry credentials");if(Y.length>8192)throw Error("Agent Plugin remote MCP headers are invalid");try{gP$(W),yP$(W,Y)}catch{throw Error("Agent Plugin remote MCP headers are invalid")}if(Q.has(G))throw Error("Agent Plugin remote MCP headers are invalid");Q.add(G)}}function ZE$($,J){let X=$.find((G)=>G.path==="mcp.json");if(!X)return{serverNames:[],hasStreamableHttp:!1,bareCommands:[]};let Q=GE$.safeParse(aa(X,"Agent Plugin mcp.json"));if(!Q.success)throw Error("Agent Plugin mcp.json does not match the 1.0.0 schema");let W=!1,Y=new Set;for(let G of Object.values(Q.data.mcpServers)){if(G.type!=="stdio"){if(DE$(G),G.type==="sse"&&J==="hermes")throw Error(mP$);W||=G.type==="streamable-http";continue}if(G.command.includes("\x00"))throw Error("Agent Plugin stdio MCP command is invalid");if(G.command.startsWith("./")){if(jE$(G.command),$.find((H)=>H.path===G.command.slice(2))?.mode!==33261)throw Error("Agent Plugin stdio MCP command is not an executable package file")}else if(!/^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/.test(G.command))throw Error("Agent Plugin stdio MCP command is invalid");else Y.add(G.command);if((G.args??[]).some((U)=>U.includes("\x00")))throw Error("Agent Plugin stdio MCP args are invalid");let z=new Set;for(let[U,H]of Object.entries(G.env??{})){let V=U.toLowerCase();if(!Fi(U)||U.toUpperCase()==="PLUGIN_ROOT"||U.toUpperCase()==="PLUGIN_DATA"||z.has(V)||U.includes("\x00")||H.includes("\x00"))throw Error("Agent Plugin stdio MCP environment is invalid");if(Oi(U)||H.length>0&&KT(H))throw Error("Agent Plugin stdio MCP environment cannot carry credentials");z.add(V)}if(G.cwd!==void 0)NE$(G.cwd,$)}return{serverNames:Object.keys(Q.data.mcpServers).sort(),hasStreamableHttp:W,bareCommands:[...Y].sort()}}function _E$($,J){let X=$E$.safeParse(aa(J.find((Y)=>Y.path==="plugin.json"),"Agent Plugin plugin.json"));if(!X.success||X.data.$schema!==$.installation.agentPluginsSchema||X.data.name!==$.name||X.data.version!==$.installation.version)throw Error("Agent Plugin package identity does not match the desired installation");let Q=X.data.extensions?.["ai.clawdi"];if(Q===void 0)throw Error("Agent Plugin ai.clawdi extension does not match the Store contract");let W=QE$.safeParse(Q);if(!W.success)throw Error("Agent Plugin ai.clawdi extension does not match the Store contract");if(W.data.display.icon){let Y=W.data.display.icon,G=Y.startsWith("./")?Y.slice(2):"";if(!OV(G)||!J.some((z)=>z.path===G))throw Error("Agent Plugin ai.clawdi display icon is not a package file")}return W.data}function ME$($,J,X){let Q=$.compatibility;if(Q?.runtimes&&!Q.runtimes.includes(J))throw Error(`Agent Plugin ai.clawdi compatibility excludes ${J}`);let W=new Set(Q?.executables??[]);if(X.some((Y)=>!W.has(Y)))throw Error("Agent Plugin bare MCP commands are not declared by ai.clawdi compatibility")}function bE$($){for(let J of $){let X=J.path.split("/").map((Q)=>Q.toLowerCase());if(X.includes(".git")||X.at(-1)===".gitattributes")throw Error(cP$)}}async function Ta($,J){let X=Sa(P1(fa(),"clawdi-agent-plugin-validate-"));try{if(J.installation.source.type==="github-release"&&`sha256:${NV($)}`!==J.installation.source.archiveDigest)throw Error("Agent Plugin release archive digest does not match the desired installation");let Q=J.installation.source.type==="github"?J.installation.source.path:"",W=await qE$(X,$,Q),Y=ra(W);if(Y.digest!==J.installation.contentDigest)throw Error("Agent Plugin package content digest does not match the desired installation");let G=_E$(J,Y.tree),z=LE$(Y.tree),U=ZE$(Y.tree,J.runtime);if(z===0&&U.serverNames.length===0)throw Error("Agent Plugin package must declare at least one Skill or MCP server");if(ME$(G,J.runtime,U.bareCommands),J.runtime==="hermes")bE$(Y.tree);return{name:J.name,installation:J.installation,receiptNativeId:null,mcpServerNames:U.serverNames,hasStreamableHttpMcp:U.hasStreamableHttp,tree:Y.tree}}finally{rN(X,{recursive:!0,force:!0})}}async function IE$($,J){let X=$.installation.source,Q=X.type==="github"?(()=>{let Y=nj(X.url);return new URL(`https://codeload.github.com/${encodeURIComponent(Y.owner)}/${encodeURIComponent(Y.repo)}/tar.gz/${encodeURIComponent(X.commit)}`)})():new URL(X.url),W=await J(Q,{headers:{Accept:X.type==="github"?"application/vnd.github+json":"application/octet-stream"},redirect:"follow"});if(!W.ok)throw Error(`Agent Plugin package download failed (${W.status})`);return k8(W,ka,{resourceLabel:"Agent Plugin source archive",limitLabel:"100 MB"})}async function AE$($,J,X,Q,W){let Y=oa(J,$.installation.ownershipIdentity);if(Y)try{return{plugin:await Ta(Y,$),cacheCreated:!1}}catch(U){if(Q)throw Error("offline Agent Plugin cache is invalid");if(W)throw U}if(Q)throw Error(Pa(J,$.installation.ownershipIdentity)?"offline Agent Plugin cache is invalid":"offline Agent Plugin cache is missing");if(Pa(J,$.installation.ownershipIdentity)&&!FV(J,$.installation.ownershipIdentity))throw Error("Agent Plugin cache ownership path is not a managed cache entry");let G=await IE$($,X),z=await Ta(G,$);return BE$(J,$.installation.ownershipIdentity,G),{plugin:z,cacheCreated:!0}}function RE$($){if($.runtime==="openclaw"||$.runtime==="hermes")return $.runtime;throw Error("Agent Plugins require a selected OpenClaw or Hermes runtime")}async function ta($,J,X={}){let Q=$.projection?.agentPlugins?.installations??{};if($.projection?.sourceBundleVersion!=="clawdi.hosted-runtime.bundle.v2"){if(Object.keys(Q).length>0)throw Error(tj);return null}let Y=VQ(J);if(Object.keys(Q).length===0&&!Y)return null;let G=Object.keys(Q).length>0?RE$($):Y?.runtime;if(!G)return null;let z=X.fetcher??fetch,U=new Map,H=new Set,V=new Set(Object.values(Y?.installations??{}).map((w)=>w.ownershipIdentity)),B=async(w)=>{let q=w.installation.ownershipIdentity,L=`${w.runtime}\x00${q}`,N=U.get(L);if(N)return(await N).plugin;let F=AE$(w,J,z,X.offline===!0,V.has(q));U.set(L,F);let O=await F;if(O.cacheCreated)H.add(q);return O.plugin};try{let w=new Map;for(let[L,N]of Object.entries(Q).sort(([F],[O])=>F.localeCompare(O))){let F=HE$(L,N);w.set(L,await B({name:L,runtime:G,installation:F}))}let q=new Map;if(Y)for(let[L,N]of Object.entries(Y.installations).sort(([F],[O])=>F.localeCompare(O))){let{ownershipIdentity:F,nativeId:O,..._}=N;if(F!==la(L,_))throw Error("Agent Plugin receipt ownership identity is invalid");let M=await B({name:L,runtime:Y.runtime,installation:eC.parse({..._,ownershipIdentity:F})});q.set(L,{...M,receiptNativeId:O})}return{runtime:G,desired:w,previousReceipt:Y,rollback:q,transientCacheOwnerships:new Set([...H].filter((L)=>!V.has(L)))}}catch(w){for(let q of H)if(!V.has(q))FV(J,q,{allowIncomplete:!0});throw w}}function JS($,J){let X=Sa(P1(fa(),"clawdi-agent-plugin-stage-"));try{xP$(X,448),v4(X);let Q=P1(X,"package");return Y0(()=>{Ra(Q,{recursive:!0,mode:448});for(let W of $.tree){let Y=P1(Q,...W.path.split("/"));Ra(aN(Y),{recursive:!0,mode:448}),vP$(Y,W.bytes,{mode:W.mode&511})}}),J(Q)}finally{rN(X,{recursive:!0,force:!0})}}var mP$="Hermes Agent Plugins only support the portable streamable-http remote transport",cP$="Hermes Agent Plugin package cannot preserve its verified bytes through local Git transport",xa="clawdi.hostedAgentPluginArchive.v1",lP$="clawdi.hostedAgentPluginReceipts.v2",dP$="https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",ka=104857600,nP$=268435456,va=2000,ga=1000,ya=52428800,ha=10485760,pP$=512,iP$=262144,oP$=4194304,rP$=4096,ua="$",bY,IY,eC,aP$,sP$,ma,tP$,eP$,$E$,sC=($,J)=>K.array(K.string().min(1).max(J)).max($).refine((X)=>new Set(X.map(ca)).size===X.length,"must not contain case-folded duplicates"),JE$,XE$,QE$,WE$,YE$,GE$,UE$;var AY=D(()=>{Gq();OY();Q0();JY();VX();QY();LT();p0();p6();bY=`${ua}{PLUGIN_ROOT}`,IY=`${ua}{PLUGIN_DATA}`,eC=vH.extend({ownershipIdentity:K.string().regex(/^[a-f0-9]{64}$/)}).strict(),aP$=K.string().min(1).max(128).regex(/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/),sP$=eC.extend({nativeId:aP$}).strict(),ma=K.object({schemaVersion:K.literal(lP$),runtime:K.enum(["openclaw","hermes"]),installations:K.record(XY,sP$)}).strict();tP$=K.object({schemaVersion:K.literal(xa),ownershipIdentity:K.string().regex(/^[a-f0-9]{64}$/),archiveSha256:K.string().regex(/^[a-f0-9]{64}$/)}).strict(),eP$=K.record(K.string(),K.unknown()),$E$=K.object({$schema:K.literal(jT),name:XY,version:K.string().optional(),description:K.string().optional(),author:K.object({name:K.string().optional(),email:K.string().optional(),url:K.string().optional()}).strict().optional(),homepage:K.string().optional(),repository:K.string().optional(),license:K.string().optional(),keywords:K.array(K.string()).optional(),extensions:K.record(K.string(),K.record(K.string(),K.unknown())).optional()}).strict(),JE$=K.object({name:K.string().min(1).max(80),icon:K.string().min(1).max(512).optional(),category:K.string().regex(/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/),languages:sC(20,64).refine(($)=>$.every((J)=>/^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/.test(J)),"must contain language tags")}).strict(),XE$=K.object({runtimes:sC(2,16).min(1).refine(($)=>$.every((J)=>J==="openclaw"||J==="hermes"),"contains an unsupported runtime").optional(),executables:sC(32,128).min(1).refine(($)=>$.every((J)=>/^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/.test(J)),"contains an invalid executable").optional()}).strict(),QE$=K.object({schemaVersion:K.literal(1),display:JE$,compatibility:XE$.optional()}).strict(),WE$=K.object({type:K.literal("stdio"),command:K.string().min(1).max(512),args:K.array(K.string()).max(256).optional(),env:K.record(K.string(),K.string()).optional(),cwd:K.string().min(1).max(512).optional()}).strict(),YE$=K.object({type:K.enum(["streamable-http","sse"]),url:K.string().min(1).max(2048),headers:K.record(K.string(),K.string()).optional()}).strict(),GE$=K.object({$schema:K.literal(dP$),mcpServers:K.record(K.string().min(1),K.union([WE$,YE$]))}).strict();UE$=new Map("b5:3bc;df:73,73;149:2bc,6e;17f:73;1f0:6a,30c;345:3b9;390:3b9,308,301;3b0:3c5,308,301;3c2:3c3;3d0:3b2;3d1:3b8;3d5:3c6;3d6:3c0;3f0:3ba;3f1:3c1;3f5:3b5;587:565,582;1c80:432;1c81:434;1c82:43e;1c83:441;1c84:442;1c85:442;1c86:44a;1c87:463;1c88:a64b;1e96:68,331;1e97:74,308;1e98:77,30a;1e99:79,30a;1e9a:61,2be;1e9b:1e61;1e9e:73,73;1f50:3c5,313;1f52:3c5,313,300;1f54:3c5,313,301;1f56:3c5,313,342;1f80:1f00,3b9;1f81:1f01,3b9;1f82:1f02,3b9;1f83:1f03,3b9;1f84:1f04,3b9;1f85:1f05,3b9;1f86:1f06,3b9;1f87:1f07,3b9;1f88:1f00,3b9;1f89:1f01,3b9;1f8a:1f02,3b9;1f8b:1f03,3b9;1f8c:1f04,3b9;1f8d:1f05,3b9;1f8e:1f06,3b9;1f8f:1f07,3b9;1f90:1f20,3b9;1f91:1f21,3b9;1f92:1f22,3b9;1f93:1f23,3b9;1f94:1f24,3b9;1f95:1f25,3b9;1f96:1f26,3b9;1f97:1f27,3b9;1f98:1f20,3b9;1f99:1f21,3b9;1f9a:1f22,3b9;1f9b:1f23,3b9;1f9c:1f24,3b9;1f9d:1f25,3b9;1f9e:1f26,3b9;1f9f:1f27,3b9;1fa0:1f60,3b9;1fa1:1f61,3b9;1fa2:1f62,3b9;1fa3:1f63,3b9;1fa4:1f64,3b9;1fa5:1f65,3b9;1fa6:1f66,3b9;1fa7:1f67,3b9;1fa8:1f60,3b9;1fa9:1f61,3b9;1faa:1f62,3b9;1fab:1f63,3b9;1fac:1f64,3b9;1fad:1f65,3b9;1fae:1f66,3b9;1faf:1f67,3b9;1fb2:1f70,3b9;1fb3:3b1,3b9;1fb4:3ac,3b9;1fb6:3b1,342;1fb7:3b1,342,3b9;1fbc:3b1,3b9;1fbe:3b9;1fc2:1f74,3b9;1fc3:3b7,3b9;1fc4:3ae,3b9;1fc6:3b7,342;1fc7:3b7,342,3b9;1fcc:3b7,3b9;1fd2:3b9,308,300;1fd3:3b9,308,301;1fd6:3b9,342;1fd7:3b9,308,342;1fe2:3c5,308,300;1fe3:3c5,308,301;1fe4:3c1,313;1fe6:3c5,342;1fe7:3c5,308,342;1ff2:1f7c,3b9;1ff3:3c9,3b9;1ff4:3ce,3b9;1ff6:3c9,342;1ff7:3c9,342,3b9;1ffc:3c9,3b9;fb00:66,66;fb01:66,69;fb02:66,6c;fb03:66,66,69;fb04:66,66,6c;fb05:73,74;fb06:73,74;fb13:574,576;fb14:574,565;fb15:574,56b;fb16:57e,576;fb17:574,56d".split(";").map(zE$))});import{readFileSync as PE$}from"node:fs";function QS($,J){return{installationId:J.installationId,name:$,version:J.version,contentDigest:J.contentDigest}}function CE$($){try{let J=VQ($);if(!J)return{status:"missing",installations:new Map};return{status:"ok",installations:new Map(Object.entries(J.installations).map(([X,Q])=>[X,QS(X,Q)]))}}catch{return{status:"unreadable",installations:new Map}}}function SE$($,J){try{let X=TE$.parse(JSON.parse(PE$($.manifestLastGood,"utf-8")));if(X.instanceId!==J.instanceId||R0(X)!==R0(J))return null;return new Map(Object.entries(X.projection?.agentPlugins?.installations??{}).map(([Q,W])=>[Q,QS(Q,W)]))}catch{return null}}function fE$($,J){return $.installationId===J.installationId&&$.name===J.name&&$.version===J.version&&$.contentDigest===J.contentDigest}function xE$($,J){return XS.parse({...$,sourceRevision:J.sourceRevision,generation:R0(J),status:"installed"})}function ea($,J,X){return XS.parse({...$,sourceRevision:J.sourceRevision,generation:R0(J),status:"unknown",errorCode:X})}function kE$($){if(!$||typeof $!=="object"||Array.isArray($))return null;let J=$.event;if(!J||typeof J!=="object"||Array.isArray(J))return null;let X=J;if(X.status!=="error")return null;let Q=BQ.safeParse(X.agentPlugins);if(!Q.success||Q.data.installations.some((W)=>W.status!=="failed"))return null;return Q.data}function vE$($,J,X){let Q=SE$($,J);if(Q===null){if(X.status!=="ok"||X.installations.size===0)return null;return BQ.parse({schemaVersion:1,installations:[...X.installations.values()].sort((G,z)=>G.name<z.name?-1:G.name>z.name?1:0).map((G)=>ea(G,J,"receipt_mismatch"))})}if(Q.size===0&&X.installations.size===0)return null;let W=X.status==="ok"&&X.installations.size===Q.size&&[...Q].every(([G,z])=>{let U=X.installations.get(G);return U!==void 0&&fE$(z,U)}),Y=X.status==="missing"?"receipt_missing":X.status==="unreadable"?"receipt_unreadable":"receipt_mismatch";return BQ.parse({schemaVersion:1,installations:[...Q.values()].sort((G,z)=>G.name<z.name?-1:G.name>z.name?1:0).map((G)=>W?xE$(G,J):ea(G,J,Y))})}function $s($){let J=CE$($.paths),X=vE$($.paths,$.applied,J),Q=kE$($.watchStatus);if(!Q)return X;let W=R0($.applied),Y=Q.installations.filter((z)=>z.generation>W||z.generation===W&&z.sourceRevision!==$.applied.sourceRevision);if(Y.length===0)return X;let G=new Set(Y.map((z)=>z.name));return BQ.parse({schemaVersion:1,installations:[...X?.installations.filter((z)=>!G.has(z.name))??[],...Y].sort((z,U)=>z.name<U.name?-1:z.name>U.name?1:0)})}function Js($,J,X){let Q=new Set(X),W=Object.entries($.projection?.agentPlugins?.installations??{}).filter(([G])=>Q.has(G)).sort(([G],[z])=>G<z?-1:G>z?1:0).map(([G,z])=>({...QS(G,z),sourceRevision:J,generation:R0($),status:"failed",errorCode:"reconcile_failed"}));if(W.length===0)return null;let Y=BQ.safeParse({schemaVersion:1,installations:W});return Y.success?Y.data:null}var EE$,XS,BQ,TE$;var eN=D(()=>{Q0();wX();AY();QY();EE$=K.enum(["reconcile_failed","receipt_missing","receipt_unreadable","receipt_mismatch"]),XS=vH.pick({version:!0,contentDigest:!0}).extend({installationId:K.uuid().max(200),name:XY,sourceRevision:K.string().regex(/^[0-9a-f]{64}$/),generation:K.number().int().positive().safe(),status:K.enum(["installed","failed","unknown"]),errorCode:EE$.nullable().optional()}).strict().superRefine(($,J)=>{if($.status==="installed"&&$.errorCode!=null)J.addIssue({code:"custom",message:"installed observation cannot include errorCode"});if($.status==="failed"&&$.errorCode!=="reconcile_failed")J.addIssue({code:"custom",message:"failed observation requires reconcile_failed"});if($.status==="unknown"&&!["receipt_missing","receipt_unreadable","receipt_mismatch"].includes($.errorCode))J.addIssue({code:"custom",message:"unknown observation requires a receipt error"})}),BQ=K.object({schemaVersion:K.literal(1),installations:K.array(XS).max(128)}).strict().superRefine(($,J)=>{let X=$.installations.map((W)=>W.name),Q=$.installations.map((W)=>W.installationId);if(new Set(X).size!==X.length||new Set(Q).size!==Q.length)J.addIssue({code:"custom",message:"observation identities must be unique"});if(!X.every((W,Y)=>Y===0||(X[Y-1]??"")<W))J.addIssue({code:"custom",message:"observations must be sorted by name"})}),TE$=K.object({instanceId:K.string().min(1),generation:K.number().int().nonnegative(),applyGeneration:K.number().int().positive().safe().optional(),projection:K.object({agentPlugins:gH.optional()}).passthrough().optional()}).passthrough()});import{createHash as gE$}from"node:crypto";function Xs($){let J=$.egressProfiles!==void 0?xH.parse($.egressProfiles):{profiles:[]};return iE$(J,[...uE$($),...yE$($)])}function yE$($){if(typeof $.mcp!=="object"||$.mcp===null||Array.isArray($.mcp)||!Object.hasOwn($.mcp,"servers"))return[];let J=t7.parse($.mcp),X=[];for(let[Q,W]of Object.entries(J.servers)){if(!("url"in W))continue;let Y=Object.entries(W.headers).filter((U)=>typeof U[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-${Qs(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(([U,H])=>[U,{type:"equals",value:YS(Q,U),prefix:H.prefix}])),query:{}},rewrite:{preservePath:!0,setHeaders:Object.fromEntries(Y.map(([U,H])=>[U,{type:"secretRef",secretRef:H.secretRef,prefix:H.prefix}]))},logging:{redactHeaders:Y.map(([U])=>U),redactUrlPatterns:[]},priority:70,owner:"mcp-projection",description:`Managed remote MCP credentials for ${Q}.`})}return X}function YS($,J){let X=gE$("sha256").update(`${$}\x00${J.toLowerCase()}`).digest("hex").slice(0,16);return`${e7}-mcp-${X}`}function hE$($){return $==="openai_chat"||$==="openai_responses"}function uE$($){let J=[],X=new Set;for(let[Q,W]of mE$($)){let Y=cE$(Q,W);if(!Y)continue;let G=JF(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 mE$($){let J=dE$($.providers),X=WS($.terminalTooling),Q=WS(X?.codex),W=nE$(Q?.provider),Y=$F(typeof Q?.provider_id==="string"?Q.provider_id:null);if(Y&&W)J.push([Y,W]);return J}function cE$($,J){let X=pE$(J?.baseUrl),Q=$F(J?.apiMode),W=JF(J?.apiKeySecretRef);if(!wQ(J)||!X||!W||!hE$(Q))return null;if($F(J.status)&&$F(J.status)!=="ok")return null;let Y=new URL(X),G=g9($)?a6:$;return{id:G==="default"?"managed-provider":`managed-provider-${Qs(G)}`,enabled:!0,kind:"provider",match:{scheme:Y.protocol.replace(/:$/,""),host:Y.host.toLowerCase(),pathPrefix:lE$(Y.pathname),headers:{authorization:{type:"equals",value:e7,prefix:"Bearer "}},query:{}},rewrite:{preservePath:!0,setHeaders:{authorization:{type:"secretRef",secretRef:W,prefix:"Bearer "}}},logging:{redactHeaders:["authorization"],redactUrlPatterns:[]},priority:80,owner:"provider-projection"}}function lE$($){if($==="/")return $;return`${$.replace(/\/+$/,"")}/`}function JF($){let J=$?.trim();return J?.startsWith("secret://")&&J.length>9?J:null}function wQ($){return $.managed_by==="clawdi"}function dE$($){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 nE$($){let J=WS($);if(!J)return null;return{baseUrl:DV(J.baseUrl),apiMode:DV(J.apiMode),apiKeySecretRef:DV(J.apiKeySecretRef),managed_by:DV(J.managed_by),status:DV(J.status)}}function WS($){return typeof $==="object"&&$!==null&&!Array.isArray($)?$:null}function $F($){return $?.trim()||null}function DV($){return $===null||typeof $==="string"?$:void 0}function pE$($){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 iE$($,J){let X=new Set(J.map((Q)=>Q.id));return{profiles:[...$.profiles.filter((Q)=>!X.has(Q.id)),...J]}}function Qs($){return $.toLowerCase().replace(/[^a-z0-9-_.]+/g,"-").replace(/^[^a-z0-9]+/,"").replace(/[^a-z0-9]+$/,"")||"provider"}var XF=D(()=>{m9();v8();$Y();QY()});function _X($){if(!Array.isArray($))return[];return $.flatMap(oE$).sort((J,X)=>`${J.target}:${J.accountKey}:${J.credentialId}`.localeCompare(`${X.target}:${X.accountKey}:${X.credentialId}`))}function oE$($){let J=ZV($);if(!J)return[];if(J.provider!=="whatsapp"||J.kind!=="whatsapp_baileys_auth_state")return[];let X=qQ(J.accountKey),Q=qQ(J.linkId),W=qQ(J.credentialId),G=(Array.isArray(J.files)?J.files:[]).map(ZV).find((L)=>L?.path==="creds.json"&&typeof L.secretRef==="string"),z=G?qQ(G.secretRef):null;if(!X||!W||!z)throw Error("WhatsApp auth credential projection is incomplete");let U=ZV(J.targets),H=[],V=U?ZV(U.openclaw):null,B=U?qQ(V?.authDir):qQ(J.authDir);if(B)H.push({accountKey:X,linkId:Q,credentialId:W,authDir:B,credsJsonSecretRef:z,target:U?"openclaw":"legacy"});let w=U?ZV(U.hermes):null,q=w?qQ(w.authDir):null;if(q)H.push({accountKey:X,linkId:Q,credentialId:W,authDir:q,credsJsonSecretRef:z,target:"hermes"});if(H.length===0)throw Error("WhatsApp auth credential projection is incomplete");return H}function ZV($){return $&&typeof $==="object"&&!Array.isArray($)?$:null}function qQ($){return typeof $==="string"&&$.trim()?$.trim():null}import{existsSync as Ys,readFileSync as rE$}from"node:fs";import{isAbsolute as GS}from"node:path";function QT$($){return{...$,projection:{...$.projection??{},sourceBundleVersion:"clawdi.hosted-runtime.bundle.v2"}}}function Gs($){return JSON.parse(rE$($,"utf-8"))}function zs($){return $.issues.map((J)=>{return`${J.path.length>0?`${J.path.join(".")}: `:""}${J.message}`})}function WT$($){return mH.parse($)}function YT$($){let J=XT$.parse($);return{manifest:QT$(VT$(J.manifest,J.applyGeneration)),secretValues:S8(J.secretValues),channelBindings:J.channelBindings,sourceRevision:J.sourceRevision}}function GT$($){if(typeof $!=="object"||$===null||Array.isArray($))return null;let J=$,X=J.manifest,Q=typeof X==="object"&&X!==null&&!Array.isArray(X)?X.generation:J.generation;return typeof Q==="number"&&Number.isInteger(Q)?Q:null}async function zT$($,J={}){let X=$.manifestSource.url,Q=$.manifestSource.auth.token,W=15000,Y=new AbortController,G=setTimeout(()=>Y.abort(),15000);try{let z=await fetch(X,{method:"GET",headers:{accept:zS,authorization:`Bearer ${Q}`,[aE$]:[sE$,tE$].join(", "),...J.ifNoneMatch?{"if-none-match":J.ifNoneMatch}:{}},signal:Y.signal}),U=z.headers.get("etag")??void 0;if(z.status===304)return{url:X,notModified:!0,etag:U};if(!z.ok){let V=await z.text().catch(()=>"");if(z.status===401||z.status===403)throw new HS(z.status,V);throw Error(`runtime manifest request failed: HTTP ${z.status}${V?` ${V.slice(0,200)}`:""}`)}let H=z.headers.get("content-type")?.split(";",1)[0]?.trim();if(H!==zS)throw new QF(`runtime manifest response content-type must be ${zS}, received ${H??"missing"}`,U);if(!U)throw Error("runtime bundle response is missing its strong ETag");try{return{url:X,raw:await z.json(),etag:U}}catch(V){throw new QF(`runtime manifest response is not valid JSON: ${V instanceof Error?V.message:String(V)}`,U)}}finally{clearTimeout(G)}}async function Us($,J={}){let X;try{X=J.applyContext??BX()}catch(G){return Hs(G)}let Q;try{Q=await zT$(X,J)}catch(G){return{mode:"repair",stage:HT$(G),errors:[`could not fetch runtime manifest: ${G instanceof Error?G.message:String(G)}`],...G instanceof QF&&G.etag?{etag:G.etag}:{}}}if("notModified"in Q)return{source:"remote-datasource",sourcePath:Q.url,notModified:!0,etag:Q.etag??J.ifNoneMatch,...WF(X)};let W;try{W=YT$(Q.raw),BS(W.sourceRevision,Q.etag),UT$(W.manifest,X)}catch(G){return{mode:"manifest-rejected",stage:"network",errors:G instanceof K.ZodError?zs(G):[String(G)],etag:Q.etag,rejectedGeneration:GT$(Q.raw),activeGeneration:Bs($).generation??null}}let Y=NT$(W,$,"remote-datasource",Q.url);if(!("manifest"in Y))return{...Y,etag:Q.etag};return{...Y,etag:Q.etag,...WF(X)}}async function VS($,J={}){return Us($,J)}function Hs($){return{mode:"repair",stage:"local",errors:[$ instanceof Error?$.message:String($)]}}function WF($){return{applyContext:$}}function UT$($,J){if(J.identity&&J.identity.generation!==R0($))throw Error(`runtime apply identity generation ${J.identity.generation} does not match resolved manifest apply generation ${R0($)}`)}function BS($,J){if(!$)return;let X=`"sha256:${$}"`;if(J!==X)throw Error(`runtime bundle ETag ${J??"missing"} does not match its sourceRevision validator ${X}`)}function HT$($){return $ instanceof HS?"auth":"network"}function VT$($,J){let X=N$({mode:"hosted"}),Q=$.runtime,W=$.runtimes[Q];return{schemaVersion:AT,deploymentId:$.deploymentId,environmentId:$.environmentId,instanceId:$.instanceId,generation:$.generation,...J===void 0?{}:{applyGeneration:J},issuedAt:$.issuedAt,expiresAt:$.expiresAt,locale:$.locale,runtime:Q,controlPlane:{apiUrl:$.controlPlane.cloudApiUrl},clawdiCli:{...$.clawdiCli},egressEngine:$.egressEngine,companions:$.companions,runtimes:{[Q]:{enabled:W.enabled,providerMode:W.providerMode,install:{authority:"official",method:"official-installer",url:PT[Q],home:X.userHome,args:TT(Q,X.userHome)},run:wT$(Q,W.run),services:Object.fromEntries(Object.entries(W.services??{}).map(([Y,G])=>[Y,Vs(G)])),...BT$(W)}},openclawGatewayAuth:$.system.openclawGatewayAuth,hermesDashboardAuth:$.system.hermesDashboardAuth,projection:{sourceSchemaVersion:$.schemaVersion,sourceBundleVersion:"clawdi.hosted-runtime.bundle.v2",system:$.system,providers:$.providers,...$.mcp===void 0?{}:{mcp:$.mcp},...$.skills===void 0?{}:{skills:$.skills},...$.agentPlugins===void 0?{}:{agentPlugins:$.agentPlugins},...$.tools===void 0?{}:{tools:$.tools},...$.terminalTooling===void 0?{}:{terminalTooling:$.terminalTooling}},liveSync:$.liveSync,egressProfiles:Xs($),recovery:{cacheManifest:$.recovery.cacheManifest,allowOfflineBoot:$.recovery.allowOfflineBoot}}}function BT$($){if($.providerMode==="unmanaged")return{provider_ids:[]};return{provider_ids:$.provider_ids,primary_model:$.primary_model}}function wT$($,J){let X=Vs(J);if(YY($,J.args))X.args=["gateway","run"];return X}function Vs($){return{args:[...$.args],env:{},prependPath:[],...$.secretEnv===void 0?{}:{secretEnv:{...$.secretEnv}}}}function Bs($){let J=W0($);if(!J)return{};return{instanceId:J.instanceId,generation:J.generation}}function qT$($){if(!$.expiresAt)return null;let J=Date.parse($.expiresAt);if(!Number.isFinite(J))return`manifest expiresAt is not a valid timestamp: ${$.expiresAt}`;if(J<=Date.now())return`manifest expired at ${$.expiresAt}`;return null}function ws($,J,X="generic"){let Q=[],W=X==="hosted"&&$.projection?.sourceBundleVersion==="clawdi.hosted-runtime.bundle.v2",Y=qT$($);if(Y)Q.push(Y);if(!GS(J.userHome))Q.push(`runtime HOME must be absolute: ${J.userHome}`);if($.workspaceRoot&&!GS($.workspaceRoot))Q.push(`runtime workspaceRoot must be absolute: ${$.workspaceRoot}`);if(X!=="generic"){if(cH($)&&!W)Q.push(nJ);let G=uH.safeParse($.clawdiCli);if(!G.success)Q.push(...zs(G.error).map((z)=>`clawdiCli.${z}`))}if($.runtime){let G=$.runtime,z=Object.keys($.runtimes);if(!z.includes(G))Q.push(`manifest runtime ${G} must have a matching runtimes.${G} entry`);for(let U of z)if(U!==G)Q.push(`single-runtime manifest must not declare runtimes.${U}`);if($.runtimes[G]?.enabled!==!0)Q.push(`manifest runtime ${G} must be enabled`);if(G==="openclaw"&&W){let U=$.openclawGatewayAuth;if(!U)Q.push("OpenClaw v2 native Control UI requires official gateway token authentication");if(U?.activation.enabled!==!0)Q.push("OpenClaw native auth activation must be explicitly enabled");let H=$.projection?.system,V=typeof H==="object"&&H!==null&&!Array.isArray(H)?H.openclawControlUiAllowedOrigins:null;if(!Array.isArray(V)||V.length===0)Q.push("OpenClaw v2 native Control UI requires an explicit public allowed origin");let B=$.runtimes.openclaw?.run;if(!YY("openclaw",B?.args))Q.push("OpenClaw v2 gateway must use the official gateway run command");if(B?.secretEnv?.OPENCLAW_GATEWAY_TOKEN!==U?.tokenRef)Q.push("OpenClaw v2 gateway token must use the declared environment secret reference");if(B?.env?.OPENCLAW_GATEWAY_TOKEN!==void 0)Q.push("OpenClaw v2 gateway token must not be embedded in manifest env");for(let w of Object.values($.runtimes.openclaw?.services??{}))for(let q of["env","secretEnv"])for(let L of Object.keys(w[q]??{}))if(L==="OPENCLAW_GATEWAY_TOKEN")Q.push("OpenClaw v2 gateway token must be scoped to the gateway run secretEnv");for(let w of Object.values($.projection?.providers??{})){if(!w||typeof w!=="object"||Array.isArray(w))continue;if(w.runtimeEnvName==="OPENCLAW_GATEWAY_TOKEN")Q.push("OpenClaw v2 provider environment must not target native auth controls")}}if(G==="hermes"&&W){if(!$.hermesDashboardAuth)Q.push("hermes direct dashboard requires official password authentication");if($.hermesDashboardAuth?.activation.enabled!==!0)Q.push("hermes password authentication must be explicitly enabled");if($.openclawGatewayAuth)Q.push("OpenClaw gateway auth is only valid for the OpenClaw runtime");if(!YY("hermes",$.runtimes.hermes?.run?.args))Q.push("Hermes gateway must use the official gateway run command");if(!ET($.runtimes.hermes?.services.dashboard?.args))Q.push("hermes dashboard must bind directly to 0.0.0.0:9119")}}for(let[G,z]of Object.entries($.runtimes)){if(!z.enabled)continue;let U=z.run?.command?.trim();if(!HX(G)){if(z.install)Q.push(`runtime ${G} install metadata is not supported by this Clawdi CLI; provide run.command or upgrade the CLI`);if(!U)Q.push(`runtime ${G} is not supported by this Clawdi CLI; provide run.command or upgrade the CLI`);continue}if(!z.install&&!U&&!HX(G)){Q.push(`runtime ${G} is enabled but missing install metadata`);continue}if(!z.install)continue;let H=PT[G];if(z.install.url!==H)Q.push(`runtime ${G} must use official installer ${H}`);if(z.install.home!==J.userHome)Q.push(`runtime ${G} install.home must match runtime HOME ${J.userHome}`);if(!GS(z.install.home))Q.push(`runtime ${G} install.home must be absolute`);if(z.install.args.includes("--dir"))Q.push(`runtime ${G} install args must not include --dir`);let V=TT(G,z.install.home);if(z.install.args.length!==V.length||z.install.args.some((w,q)=>w!==V[q]))Q.push(`runtime ${G} install must use canonical official args`);let B=z.install.args.flatMap((w,q)=>w==="--prefix"?[q]:[]);if(B.length>0){let w=V.indexOf("--prefix"),q=w>=0?V[w+1]:void 0,L=B[0];if(B.length!==1||q===void 0||z.install.args[L+1]!==q)Q.push(`runtime ${G} install prefix must match the official launcher prefix ${q??"none"}`)}}return Q}async function wS($,J={}){let X;try{X=J.applyContext??BX()}catch(Y){return Hs(Y)}let Q=await Us($,{applyContext:X});if("errors"in Q&&Q.mode==="repair"&&(Q.stage==="network"||Q.stage==="auth")||"notModified"in Q){let Y=qs($,KT$,X);if("manifest"in Y)return Y;return{mode:"repair",stage:"network",errors:[..."errors"in Q?Q.errors:["could not fetch runtime manifest: runtime manifest datasource returned 304 without If-None-Match"],...Y.errors]}}return Q}function qs($,J,X){if(!Ys($.manifestLastGood))return{mode:"repair",stage:"local",errors:["last-good runtime manifest does not exist"]};try{let Q=WT$(Gs($.manifestLastGood));if(J.requireOfflineBoot&&Q.recovery.allowOfflineBoot!==!0)return{mode:"repair",stage:"local",errors:["cached manifest does not allow offline boot"]};if(J.requireSemanticValidity){let H=ws(Q,$,"hosted");if(H.length>0)return{mode:"repair",stage:"local",errors:H.map((V)=>`cached ${V}`)}}let W=W0($),Y=W?pJ(W):null,G=Q.projection?.sourceBundleVersion==="clawdi.hosted-runtime.bundle.v2";if(J.requireOfflineBoot&&(G||Y!==null)&&!lH(X.identity,Y))return{mode:"repair",stage:"local",errors:["cached strict-v2 apply identity does not match the current runtime apply identity; refusing offline boot"],activeGeneration:W?.generation??null};let z=LT$($);if("errors"in z)return z;let U=GF(Q);if(U.length>0){let H=jT$(Q,z.secretValues);if(H.length>0)return{mode:"repair",stage:"local",errors:[`cached manifest references secretValues (${H.join(", ")}); refusing offline boot because cached secret values are missing`]}}if((G||J.requireAppliedAuthority)&&!W)return{mode:"repair",stage:"local",errors:[G?"cached strict-v2 manifest has no durable applied authority; refusing offline boot":"cached manifest has no durable applied authority"]};if((G||Y||J.requireAppliedAuthority)&&W&&(W?.generation!==Q.generation||R0(W)!==R0(Q)||W.instanceId!==Q.instanceId||W.contentIdentity.sha256!==N0({manifest:Q,secretValues:z.secretValues})))return{mode:"repair",stage:"local",errors:["cached manifest does not match the durable strict-v2 apply identity; refusing offline boot"],activeGeneration:W?.generation??null};if(U.length>0)return{manifest:Q,source:"last-good-cache",sourcePath:$.manifestLastGood,offline:!0,secretValues:z.secretValues,...WF(X)};return{manifest:Q,source:"last-good-cache",sourcePath:$.manifestLastGood,offline:!0,...WF(X)}}catch(Q){return{mode:"repair",stage:"local",errors:[`could not read last-good runtime manifest at ${$.manifestLastGood}: ${Q instanceof Error?Q.message:String(Q)}`]}}}function YF($,J){return qs($,{requireOfflineBoot:!1,requireAppliedAuthority:!0,requireSemanticValidity:!1},J)}function LT$($){if(!Ys($.managedSecretCacheFile))return{secretValues:{}};try{let J=Gs($.managedSecretCacheFile);if(!J||typeof J!=="object"||Array.isArray(J))throw Error("cached secret values must be a JSON object");let X={};for(let[Q,W]of Object.entries(J)){if(typeof W!=="string")throw Error(`cached secret value for ${Q} must be a string`);X[Q]=W}return{secretValues:S8(X)}}catch(J){return{mode:"repair",stage:"local",errors:[`could not read cached runtime secret values at ${$.managedSecretCacheFile}: ${J instanceof Error?J.message:String(J)}`]}}}function GF($){let J=new Set,X=US($.projection?.providers),Q=!1;for(let[W,Y]of Object.entries($.runtimes)){if(!Y.enabled)continue;Q=!0,Ws(Y.run?.secretEnv,J);for(let G of Object.values(Y.services??{}))Ws(G.secretEnv,J);if(W==="openclaw"&&$.openclawGatewayAuth)J.add($.openclawGatewayAuth.tokenRef);if(W==="hermes"&&Y.services?.dashboard&&$.hermesDashboardAuth)J.add($.hermesDashboardAuth.passwordSecretRef),J.add($.hermesDashboardAuth.sessionSecretRef);for(let G of Y.provider_ids??[]){let z=US(X?.[G]);if(!z||wQ(z))continue;if(typeof z.apiKeySecretRef==="string")J.add(z.apiKeySecretRef);let U=US(z.auth);if(typeof U?.credentialSecretRef==="string")J.add(U.credentialSecretRef)}}if(Q){for(let W of dj($.egressProfiles))J.add(W);for(let W of _X($.projection?.channelCredentials))J.add(W.credsJsonSecretRef)}return[...J].sort()}function jT$($,J){let X=S8(J??{});return GF($).filter((Q)=>w0(X,Q)===null)}function Ws($,J){for(let X of Object.values($??{}))J.add(X)}function US($){return $&&typeof $==="object"&&!Array.isArray($)?$:null}function NT$($,J,X,Q){let W=Bs(J),Y=$.manifest,G=ws(Y,J,"hosted");if(W.instanceId&&W.instanceId!==Y.instanceId)G.push(`manifest instanceId ${Y.instanceId} does not match applied instanceId ${W.instanceId}`);if(W.instanceId===Y.instanceId&&W.generation!==void 0&&Y.generation<W.generation)G.push(`manifest generation ${Y.generation} is older than applied generation ${W.generation}`);if(G.length>0)return{mode:"manifest-rejected",stage:X==="remote-datasource"?"network":"local",errors:G,rejectedGeneration:Y.generation,activeGeneration:W.generation??null};return{manifest:Y,source:X,sourcePath:Q,offline:!1,secretValues:$.secretValues,channelBindings:$.channelBindings,sourceRevision:$.sourceRevision}}var zS="application/vnd.clawdi.runtime-bundle.v2+json",aE$="x-clawdi-runtime-capabilities",sE$="agent-plugins-manifest-v1",tE$="agent-plugin-github-release-source-v1",eE$,$T$,JT$,XT$,HS,QF,KT$;var _V=D(()=>{Q0();g8();wX();$Y();XF();VX();I0();WY();lJ();eE$=K.object({provider:K.enum(["telegram","discord"]),accountKey:K.string().min(1),agentTokenSecretRef:G6,placeholderTokenSecretRef:G6}).strict(),$T$=K.object({provider:K.literal("whatsapp"),accountId:K.string().uuid(),accountKey:K.string().min(1),linkId:K.string().uuid(),agentTokenSecretRef:G6,placeholderTokenSecretRef:G6,credential:K.object({id:K.string().uuid(),credsSecretRef:G6,authCert:K.object({SERIAL:K.number().int().nonnegative().safe(),ISSUER:K.string().trim().min(1).max(256),PUBLIC_KEY:K.object({type:K.literal("Buffer"),data:K.string().min(1)}).strict()}).strict()}).strict()}).strict(),JT$=K.discriminatedUnion("provider",[eE$,$T$]),XT$=K.object({schemaVersion:K.literal("clawdi.hosted-runtime.bundle.v2"),sourceRevision:K.string().regex(/^[a-f0-9]{64}$/),manifest:di,applyGeneration:K.number().int().positive().safe().optional(),channelBindings:K.array(JT$),secretValues:K.record(G6,K.string())}).strict().superRefine(($,J)=>{if($.manifest.runtimes[$.manifest.runtime]?.providerMode!=="unmanaged")return;let Q=f8($.manifest.terminalTooling?.codex.provider.apiKeySecretRef);for(let W of Object.keys($.secretValues)){let Y=f8(W);if(!Y?.startsWith("provider.")||Y===Q)continue;J.addIssue({code:"custom",message:"unmanaged provider mode must not include provider secret values",path:["secretValues",W]})}});HS=class HS extends Error{status;constructor($,J){super(`runtime manifest authentication failed: HTTP ${$}${J?` ${J.slice(0,200)}`:""}`);this.status=$}};QF=class QF extends Error{etag;constructor($,J){super($);this.etag=J}};KT$={requireOfflineBoot:!0,requireAppliedAuthority:!1,requireSemanticValidity:!0}});function rJ($){return $.startsWith("# Generated by clawdi runtime init. Do not edit inside hosted runtime.")}function MV(){return process.env.CLAWDI_RUNTIME_USER?.trim()||"clawdi"}function Ks($){let J=`/run/user/${$}`;return{XDG_RUNTIME_DIR:J,DBUS_SESSION_BUS_ADDRESS:`unix:path=${J}/bus`}}var zF="# Generated by clawdi runtime init. Do not edit inside hosted runtime.";import{spawnSync as Fs}from"node:child_process";import{existsSync as FT$,readdirSync as OT$,readFileSync as Os}from"node:fs";import{join as qS}from"node:path";function UF($=N$(),J={}){if($.mode!=="hosted")return null;let X=tz($),Q=J.appliedState===void 0?W0($):J.appliedState,W=RY($.runtimeWatchStatus),Y=RY($.cliBootstrapStatus),G=TT$($),z=AT$($),U=Q?{etag:Q.etag,sourceRevision:Q.sourceRevision,generation:R0(Q),instanceId:Q.instanceId,appliedProviderIds:[...Q.providerIds]}:null,H={schemaVersion:"clawdi.hostedRuntimeObserved.v2",reportedAt:J.reportedAt??new Date().toISOString(),runtimeMode:$.mode,status:_T$(X.status,W,G,z,U!==null),activeCliVersion:L4(),applied:U,boot:X.status?MT$(X.status):null,cli:IT$(Y)};if(G)H.systemd=G;if(z)H.providers=z;if(Q&&J.includeAgentPlugins){let B=$s({paths:$,applied:Q,watchStatus:W});if(B)H.agentPlugins=B}if(X.error)H.error=X.error;let V=bT$(W);if(V)H.convergeError=V;return H}function RY($){try{let J=JSON.parse(Os($,"utf-8"));if(!J||typeof J!=="object"||Array.isArray(J))return null;return J}catch{return null}}function _T$($,J,X,Q,W){let Y=MX(J?.event);if($?.status==="error")return"error";if(X?.status==="error")return"error";if(Q&&Object.values(Q).some((G)=>G.status==="error"))return"error";if(Y?.status==="error"&&(!W||Y.healthImpact!=="resource_projection"))return"error";if(!W)return"unknown";if(X&&vT$(X.units)==="unknown")return"unknown";if(Y?.status==="applied"||Y?.status==="not_modified")return"ok";if($?.status==="ok")return"ok";return"unknown"}function MT$($){return{status:$.status,mode:$.mode,stage:$.stage,timestamp:$.timestamp,activeGeneration:$.activeGeneration,instanceId:$.instanceId??null,enabledRuntimes:$.enabledRuntimes,errors:$.errors}}function bT$($){let J=MX($?.event);if(J?.status!=="error")return null;return v0(J.error)??hT$(J.errors)[0]?.toString()??"runtime watch failed"}function IT$($){if(!$)return null;return{status:v0($.status),source:v0($.source),packageSpec:v0($.packageSpec),registry:v0($.registry),activePath:v0($.activePath),activeTarget:v0($.activeTarget),version:v0($.version)}}function AT$($){let J=RY($.providerHealthStatus),X=MX(J?.providers);if(X&&Object.keys(X).length>0){let U={};for(let[H,V]of Object.entries(X)){let B=MX(V);if(B)U[H]=B}if(Object.keys(U).length>0)return U}let Q=RY($.manifestLastGood),W=MX(Q?.projection),Y=MX(W?.providers);if(!Y||Object.keys(Y).length===0)return null;let G={...RY($.managedSecretCacheFile)??{},...RY(qS($.managedSecretRoot,"egress-secrets.json"))??{}},z={};for(let U of Object.keys(Y).sort()){let H=MX(Y[U]);if(!H)continue;let V=v0(H.apiKeySecretRef),B=V===null?null:RT$(G,V),w=PT$(H,B);z[U]={status:w.length>0?"error":"ok",configured:!0,kind:v0(H.kind),baseUrl:v0(H.baseUrl),model:v0(H.model),apiKeySecretRef:V,secretAvailable:B,reasons:w}}return Object.keys(z).length>0?z:null}function RT$($,J){return w0($,J)!==null}function PT$($,J){let X=[],Q=v0($.status);if(Q&&Q!=="ok")X.push(`provider_${Q}`);let W=MX($.error),Y=W?v0(W.code):null;if(Y)X.push(Y);let G=v0($.baseUrl);if(!G)X.push("base_url_missing");else try{let z=new URL(G),U=v0($.apiMode);if(ET$(U)&&(!z.pathname||z.pathname==="/"))X.push("base_url_path_missing")}catch{X.push("base_url_invalid")}if(!v0($.model))X.push("model_missing");if(v0($.apiKeySecretRef)&&J===!1)X.push("secret_missing");if($.apiKeyRequired===!0&&!v0($.apiKeySecretRef))X.push("api_key_secret_ref_missing");return X}function ET$($){return $==="openai_chat"||$==="openai_responses"}function TT$($){let J=Ls($.systemdSystemRoot).map((W)=>Ns("system",W,$)),X=Ls($.systemdUserRoot).map((W)=>Ns("user",W,$)),Q=[...J,...X].slice(0,30);if(Q.length===0)return null;return{status:Ms(Q),unitCount:Q.length,units:Q}}function Ls($){if(!FT$($))return[];let J=new Set;for(let X of OT$($)){if(X.endsWith(".service")){if(X.startsWith("clawdi-")||js(qS($,X)))J.add(X);continue}if(!X.endsWith(".service.d"))continue;let Q=X.slice(0,-2);if(js(qS($,X,"10-clawdi-hosted.conf")))J.add(Q)}return[...J].sort()}function js($){try{return rJ(Os($,"utf-8"))}catch{return!1}}function Ns($,J,X){let Q=$==="system"?ST$(["show",J,"--property=ActiveState","--property=SubState","--property=Result","--property=ExecMainCode","--property=ExecMainStatus"]):xT$(X,["show",J,"--property=ActiveState","--property=SubState","--property=Result","--property=ExecMainCode","--property=ExecMainStatus"]),W=kT$(Q.output),Y=yT$(W.ActiveState,Q.exitCode);return{scope:$,name:J,activeState:W.ActiveState??"unknown",subState:W.SubState??"unknown",status:Y,error:Y==="error"?CT$($,J,W):Q.exitCode===0?null:Zs(Q.output)??"systemctl show failed"}}function CT$($,J,X){let Q=fT$(["--quiet","--no-pager","--output=cat","--boot=0","--priority=err","--lines=20",$==="system"?"--unit":"--user-unit",J]);if(Q.exitCode===0){let W=Q.output.split(/\r?\n/).find((G)=>G.trim()),Y=W?Zs(W):null;if(Y)return Y}return Ds([`Result=${X.Result||"unknown"}`,`ExecMainCode=${X.ExecMainCode||"unknown"}`,`ExecMainStatus=${X.ExecMainStatus||"unknown"}`].join("; "))??"Result=unknown; ExecMainCode=unknown; ExecMainStatus=unknown"}function Ds($){let J=T$($).replace(/\s+/g," ").trim();return J?A9(J,DT$):null}function Zs($){let J=Ds($);return J&&!ZT$.test(J)?J:null}function ST$($){let J=Fs(_s(),$,{encoding:"utf8",maxBuffer:65536,timeout:KS});return{exitCode:J.status,output:[J.stdout,J.stderr,J.error?.message].filter(Boolean).join(`
|
|
@@ -952,10 +952,10 @@ ${X.join(`
|
|
|
952
952
|
`:`
|
|
953
953
|
|
|
954
954
|
`;z=`${X}${U}${J}
|
|
955
|
-
`}return{existing:X,next:z}}function n8$($,J){let{existing:X,next:Q}=dB($,J);if(Q===X)return $;return k$($,Q,{mode:384,dirMode:448}),v4($),$}function ED($,J,X){if(!$.commandPath||!E0($.commandPath))throw Error("Hermes config command is unavailable");return{command:$.commandPath,home:J,cwd:X}}function Ri$($,J){H6($,"dashboard.basic_auth",{username:J.username,session_ttl_seconds:J.sessionTtlSeconds}),H6($,"dashboard.public_url",J.publicUrl);let X=kQ($,"plugins.disabled");if(X.exists&&(!Array.isArray(X.value)||X.value.some((W)=>typeof W!=="string")))throw Error("Hermes config field plugins.disabled must be a string array");let Q=new Set((X.exists?X.value:[]).filter((W)=>W!=="dashboard_auth/basic"));Q.add("dashboard_auth/nous"),Q.add("dashboard_auth/self_hosted"),H6($,"plugins.disabled",[...Q].sort())}function Pi$($,J,X,Q,W,Y){if(X.runtimes[$]?.enabled!==!0)return null;let G=X.locale;if($==="openclaw"){if(!W)throw Error("OpenClaw official agent workspace is unavailable");return G?n8$(v(W,"SOUL.md"),lB(G)):null}if($==="hermes"){let z=X.hermesDashboardAuth,U=X.projection?.sourceBundleVersion==="clawdi.hosted-runtime.bundle.v2";if(!z&&!G&&!U)return null;let H=ED(J,Q,Y),V=v(Q,".hermes");if(U)H6(H,"terminal.cwd",Y);if(z)Ri$(H,z);if(G)H6(H,"timezone",G.timezone);return G?n8$(v(V,"SOUL.md"),lB(G)):null}return null}function _v($,J,X,Q,W){let Y=e9$(J,X,Q,W);return J==="hermes"&&X==="dashboard"?Or$($,Y)??Y:Y}function hD($,J,X){return t9$($,J,X)}function uD($,J,X){let Q={...X},W=J?.secretEnv??{};for(let[Y,G]of Object.entries(W)){let z=Q[Y];if(z!==void 0&&z!==G)throw Error(`runtime ${$} secretEnv.${Y} conflicts with provider secret ref ${z}`);Q[Y]=G}for(let Y of Object.keys(J?.env??{}))if(Q[Y]!==void 0)throw Error(`runtime ${$} defines ${Y} in both env and secretEnv`);return Q}function Mv($,J,X,Q){let W={...Q},Y=X.secretEnv??{};for(let[G,z]of Object.entries(Y)){let U=W[G];if(U!==void 0&&U!==z)throw Error(`runtime ${$} service ${J} secretEnv.${G} conflicts with provider secret ref ${U}`);W[G]=z}for(let G of Object.keys(X.env??{}))if(W[G]!==void 0)throw Error(`runtime ${$} service ${J} defines ${G} in both env and secretEnv`);return W}function TD($){return v($.managedSecretRoot,"egress-secrets.json")}function Bv($){return N0({schemaVersion:"clawdi.runtimeEgressSidecarSecrets.v1",secretValues:$})}function j5$($,J){let X=vD(J,Ci$($));return{content:Object.keys(X).length>0?`${JSON.stringify(X,null,2)}
|
|
956
|
-
`:null,revision:Bv(X)}}function Ei$($){if($===null)return Bv({});try{let J=JSON.parse($);if(!J||typeof J!=="object"||Array.isArray(J))return null;let X={};for(let[Q,W]of Object.entries(J)){if(typeof W!=="string")return null;X[Q]=W}return Bv(X)}catch{return null}}function wv($,J){let X=TD(J);if($.content===null)return l4(X,{force:!0}),null;z8(J,X,$.content,{mode:384,dirMode:448}),L5$(X),Ov(J.managedSecretRoot);try{W5(X,384)}catch{}return X}function Ti$($,J,X){let Q=TD(X),W=b4(Q)?w9(Q,"utf-8"):null,Y=j5$($,J);return{path:wv(Y,X),changed:W!==Y.content,material:Y,previousRevision:Ei$(W)}}function p8$($,J){try{let X=YF($,J);if("errors"in X)return null;return j5$(X.manifest,X.secretValues)}catch{return null}}function Ci$($){return dj($.egressProfiles)}function Si$($){let J=new Set,X=Array.isArray($.egressProfiles?.profiles)?$.egressProfiles.profiles:[];for(let Q of X){let W=j$(Q);if(W?.owner==="provider-projection")CD(Q,J);if(W?.owner==="mcp-projection")CD(Q,J);if(W?.owner==="clawdi-native-channels")fi$(W,J)}return[...J].sort()}function fi$($,J){let X=j$($.rewrite);if(!X)return;let Q=j$(X.pathReplace),W=H4(Q?.replacementSecretRef);if(W)J.add(W);let Y=j$(X.setHeaders);if(!Y)return;for(let G of Object.values(Y)){let z=j$(G);if(z?.type!=="secretRef")continue;let U=H4(z.secretRef);if(U)J.add(U)}}function CD($,J){if(!$||typeof $!=="object")return;if(Array.isArray($)){for(let X of $)CD(X,J);return}for(let[X,Q]of Object.entries($)){if(typeof Q==="string"&&(X==="secretRef"||X.endsWith("SecretRef")))J.add(Q);CD(Q,J)}}function mD($){if(!$)return null;let J=new Map,X=$.catalog.providers.map((W)=>{if(W.managed_by!=="clawdi")return W;let Y=g9(W.id)?a6:W.id===CI||W.id.startsWith("clawdi-managed")?W.id:CI;return J.set(W.id,Y),{...W,id:Y,api_mode:g9(Y)?Ll:W.api_mode}}),Q=J.get($.primaryModel.provider_id);if(!Q)return $;return{catalog:{...$.catalog,providers:X,defaults:{...$.catalog.defaults,chat_provider_id:Q}},primaryModel:{...$.primaryModel,provider_id:Q}}}function OG($){let J=$.runtimes.openclaw,X=J?.provider_ids?.[0],Q=X?j$($.projection?.providers?.[X]):null,Y=mD(fB($,"openclaw"))?.catalog.providers.find((G)=>G.id===a6);return $.projection?.sourceBundleVersion==="clawdi.hosted-runtime.bundle.v2"&&J?.enabled===!0&&J.providerMode==="configured"&&typeof X==="string"&&g9(X)&&Q?.managed_by==="clawdi"&&H4(Q.apiKeySecretRef)!==null&&Y?.managed_by==="clawdi"&&Y.runtime_env_name===I1&&Y.auth.type==="api_key"&&Y.auth.source==="managed"}function xi$($,J,X){return l1$($.oauthCredentialRoot,J,X)}function bD($,J,X,Q){Bk($,{runtime:J,providerId:X},Q)}function o8$($){return d1$($,{migrateLegacy:!0})}function ki$($){let J=$.split(".")[1];if(!J)return null;try{let X=JSON.parse(Buffer.from(J,"base64url").toString("utf8")),Q=j$(X)?.exp;return typeof Q==="number"&&Number.isFinite(Q)?Math.trunc(Q*1000):null}catch{return null}}function vi$($){let J=j$(JSON.parse($));if(J?.kind!=="local_agent_profile"||!Array.isArray(J.files))throw Error("hosted OAuth secret is not a local Agent credential profile");let X=J.files.map(j$).find((z)=>z?.logicalName==="auth.json");if(!X||typeof X.content!=="string")throw Error("hosted OAuth credential profile is missing auth.json");let Q=j$(JSON.parse(X.content)),W=j$(Q?.tokens),Y=H4(W?.access_token),G=H4(W?.refresh_token);if(!Y||!G)throw Error("hosted OAuth credential profile is missing access or refresh token");return{accessToken:Y,refreshToken:G,...H4(W?.id_token)?{idToken:H4(W?.id_token)??void 0}:{},...H4(W?.account_id)?{accountId:H4(W?.account_id)??void 0}:{},lastRefresh:H4(Q?.last_refresh)??new Date().toISOString(),expires:ki$(Y)??Date.now()+3600000}}function N5$($,J,X){if($.runtimes[J]?.enabled!==!0)return[];let Q=j$($.projection?.providers);if(!Q)return[];return($.runtimes[J]?.provider_ids??[]).flatMap((W)=>{let Y=Q[W],G=j$(Y),z=j$(G?.auth);if(z?.type!=="agent_profile"||z.tool!=="codex"||typeof z.profile!=="string"||typeof z.credentialSecretRef!=="string"||typeof z.credentialRevision!=="string")return[];let U=w0(X??{},z.credentialSecretRef);if(!U)throw Error(`hosted OAuth secret is unavailable for ${W}`);return[{providerId:W,profile:z.profile,credentialRevision:z.credentialRevision,material:vi$(U)}]})}function jv($){return v($,".hermes","auth.json")}function F5$($,J,X,Q,W,Y,G,z){let U=jv($);FG(g6(U),$);let H=s$("flock",["--timeout","10",v(g6(U),"auth.lock"),"node","--input-type=module","--eval",m1$,U,X,Q,G?.nativeProfileId??"",W,z??""],$,J,{input:Y?JSON.stringify(Y):"null"});if(H.status!==0)throw Error(`Hermes Codex auth ${X} failed: ${w1(String(H.stderr??""))??"unknown"}`);return j$(JSON.parse(String(H.stdout||"{}")))??{}}function gi$($,J,X,Q,W){return Yk(F5$($,J,"inspect",X,Q,void 0,W))}function O5$($,J,X,Q,W,Y,G,z){return Gk(F5$($,J,X,Q,W,Y,G,z))}function D5$($){return v(wG($),"agents","main","agent")}function iB($,J){let X=process.env.CLAWDI_RUNTIME_TEST_OPENCLAW_PROVIDER_AUTH_SDK?.trim();if(X){if(process.env.CLAWDI_RUNTIME_ALLOW_TEST_INSTALLERS!=="1")throw Error("CLAWDI_RUNTIME_TEST_OPENCLAW_PROVIDER_AUTH_SDK requires CLAWDI_RUNTIME_ALLOW_TEST_INSTALLERS=1");return X}let Q=$?.commandPath,W=g1$(J,[Q,$?.appRoot,v(J,".openclaw","lib","node_modules","openclaw"),v(J,".openclaw","node_modules","openclaw"),v(J,".local","lib","node_modules","openclaw")]);if(!W)throw Error("installed OpenClaw provider-auth SDK export is unavailable");return W}function yi$($,J){return u1$(J,[$.commandPath,$.appRoot,v(J,".openclaw","lib","node_modules","openclaw"),v(J,".openclaw","node_modules","openclaw"),v(J,".local","lib","node_modules","openclaw")])}function r8$($,J){let X=yi$($,J);if(!X)return!1;_G(J);let Q=s$("node",["--input-type=module","--eval",hi$,X],J,J);if(Q.status!==0)throw Error(`installed OpenClaw device-bootstrap capability probe failed: ${w1(String(Q.stderr??""))??"unknown"}`);let W=String(Q.stdout??"").trim();if(W==="supported")return!0;if(W==="unsupported")return!1;throw Error("installed OpenClaw device-bootstrap capability probe returned invalid output")}function ci$($,J){let X=iB($,J);_G(J);let Q=s$("node",["--input-type=module","--eval",ui$,X],J,J);if(Q.status!==0)throw Error(`installed OpenClaw public provider-auth SDK is incompatible: ${w1(String(Q.stderr??""))??"capability probe failed"}`)}function li$($,J){let X=iB($,J),Q=cD($,J);if(!Q)throw Error("installed OpenClaw public config-mutation SDK export is unavailable");_G(J);let W=s$("node",["--input-type=module","--eval",mi$,X,Q,tk({home:J,commandPath:$.commandPath,appRoot:$.appRoot})],J,J);if(W.status!==0)throw Error(`installed OpenClaw public managed-provider auth cleanup SDK is incompatible: ${w1(String(W.stderr??""))??"capability probe failed"}`)}function di$($){let J=N5$($.manifest,"openclaw",$.secretValues),X=OG($.manifest);if(J.length===0&&!X)return $.observation;let Q=J.length>0&&X?"OpenClaw credential convergence":X?"OpenClaw managed API-key cleanup":"OpenClaw OAuth",W=(Y)=>{if(J.length>0)ci$(Y,$.home);if(X)li$(Y,$.home)};try{return W($.observation),$.observation}catch(Y){let G=Y instanceof Error?Y.message:String(Y);throw Error(`${Q} requires the public OpenClaw SDK; automatic runtime reinstall is disabled: ${w1(G)??"capability probe failed"}`)}}function Z5$($,J,X,Q,W,Y,G,z,U){let H=G?JSON.stringify({type:"oauth",provider:tp$,access:G.accessToken,refresh:G.refreshToken,expires:G.expires,...G.idToken?{idToken:G.idToken}:{},...G.accountId?{accountId:G.accountId}:{},copyToAgents:!1}):"",V=s$("node",["--input-type=module","--eval",c1$,iB($,J),D5$(J),Q,W,z?.nativeProfileId??"",Y,U??""],J,X,{input:H||"null"});if(V.status!==0)throw Error(`OpenClaw provider-auth ${Q} failed: ${w1(String(V.stderr??""))??"unknown"}`);return j$(JSON.parse(String(V.stdout||"{}")))??{}}function ni$($,J,X,Q,W,Y){return Yk(Z5$($,J,X,"inspect",Q,W,void 0,Y))}function _5$($,J,X,Q,W,Y,G,z,U){return Gk(Z5$($,J,X,Q,W,Y,G,z,U))}function pi$($,J,X,Q){let W=cD($,J);if(!W)throw Error("installed OpenClaw public config-mutation SDK export is unavailable");let Y=s$("node",["--input-type=module","--eval",zk,iB($,J),W,J,"cleanup",JSON.stringify(Q)],J,X);if(Y.status!==0)throw Error(`OpenClaw managed provider-auth cleanup failed: ${w1(String(Y.stderr||Y.stdout||""))??"unknown"}`)}function ii$($,J){let X=cD($,J);if(!X)throw Error("installed OpenClaw public config-mutation SDK export is unavailable");let Q=s$("node",["--input-type=module","--eval",zk,iB($,J),X,J,"discover"],J,J);if(Q.status!==0)throw Error(`OpenClaw managed provider-auth store discovery failed: ${w1(String(Q.stderr||Q.stdout||""))??"unknown"}`);let W=j$(JSON.parse(String(Q.stdout||"{}")));if(!W||!Array.isArray(W.agentDirs))throw Error("OpenClaw managed provider-auth store discovery returned invalid output");let Y=W.agentDirs.filter((G)=>typeof G==="string");if(Y.length!==W.agentDirs.length||Y.length===0)throw Error("OpenClaw managed provider-auth store discovery returned invalid targets");return Y}function a8$($){if(!$)return;let J=$.state==="seeded"?$.credentialFingerprint:$.state==="intent"&&$.operation==="remove"?$.beforeCredentialFingerprint:void 0;if($.state!=="seeded"&&!($.state==="intent"&&$.operation==="remove"))return;return{nativeProfileId:$.nativeProfileId,...J?{credentialRevision:$.credentialRevision,credentialFingerprint:J}:{}}}function s8$($){if($.runtime==="hermes")return gi$($.home,$.workspaceRoot,$.nativeProfileId,$.credentialRevision,$.ownership);return ni$($.observation,$.home,$.workspaceRoot,$.nativeProfileId,$.credentialRevision,$.ownership)}function oi$($){let J=$.decision.nativeAction;if(J==="preserve")return;if(J==="remove")throw Error("Desired hosted OAuth reconciliation cannot remove a credential");let X=J==="seed"?"seed-if-missing":"upsert",Q=J==="seed"?"missing":Nv($.decision.expectedCredentialFingerprint,"before"),W=Nv($.decision.targetCredentialFingerprint,"target"),Y;if($.runtime==="hermes")Y=O5$($.home,$.workspaceRoot,X,$.nativeProfileId,$.credentialRevision,$.material,void 0,Q);else Y=_5$($.observation,$.home,$.workspaceRoot,X,$.nativeProfileId,$.credentialRevision,$.material,void 0,Q);ai$(Y,Q,W,`${$.runtime} OAuth credential`)}function ri$($){let J;if($.runtime==="hermes")J=O5$($.home,$.workspaceRoot,"remove",$.nativeProfileId,$.credentialRevision,void 0,$.ownership,$.expectedFingerprint);else J=_5$($.observation,$.home,$.workspaceRoot,"remove",$.nativeProfileId,$.credentialRevision,void 0,$.ownership,$.expectedFingerprint);si$(J,$.expectedFingerprint,`${$.runtime} OAuth credential`)}function Nv($,J){if(!$)throw Error(`OAuth credential decision is missing ${J} fingerprint evidence`);return $}function ai$($,J,X,Q){if(!$.casMatched)throw Error(`${Q} changed before the mutation could be applied`);if(M5$($,J,Q),!$.updated||$.afterCredentialFingerprint!==X)throw Error(`${Q} mutation did not produce the intended fingerprint`)}function si$($,J,X){if(!$.casMatched)throw Error(`${X} changed before removal could be applied`);if(M5$($,J,X),!$.updated||$.afterCredentialFingerprint)throw Error(`${X} removal could not verify absence`)}function M5$($,J,X){if(!(J==="missing"?$.beforeCredentialFingerprint===void 0:$.beforeCredentialFingerprint===J))throw Error(`${X} mutation returned inconsistent before evidence`)}function t8$($){let J=N5$($.manifest,$.runtime,$.secretValues),X=new Set(J.map((W)=>W.providerId)),Q=v($.paths.oauthCredentialRoot,$.runtime);if(b4(Q))for(let W of lX(Q).filter((Y)=>Y.endsWith(".json"))){let Y=v(Q,W),G=o8$(Y);if(!G||X.has(G.providerId)||G.state==="retired")continue;let z=nO(G),U=a8$(G),H=s8$({runtime:$.runtime,observation:$.observation,home:$.home,workspaceRoot:$.workspaceRoot,nativeProfileId:G.nativeProfileId,credentialRevision:G.credentialRevision,ownership:U}),V=Qk({desiredCredentialRevision:null,desiredNativeProfileId:null,desiredCredentialFingerprint:null,ledger:z,native:H});if(V.requiresWriteAheadIntent)bD(Y,$.runtime,G.providerId,Wk(V));if(V.nativeAction==="remove"){let B=Nv(V.expectedCredentialFingerprint,"before"),w=U??{nativeProfileId:G.nativeProfileId,credentialRevision:G.credentialRevision,credentialFingerprint:B};ri$({runtime:$.runtime,observation:$.observation,home:$.home,workspaceRoot:$.workspaceRoot,nativeProfileId:G.nativeProfileId,credentialRevision:G.credentialRevision,ownership:w,expectedFingerprint:B})}bD(Y,$.runtime,G.providerId,V.nextLedger)}for(let W of J){let Y=xi$($.paths,$.runtime,W.providerId),G=o8$(Y),z=nO(G),U=k1$($.runtime,W.providerId),H=v1$(W.credentialRevision,W.material.accessToken,W.material.refreshToken),V=s8$({runtime:$.runtime,observation:$.observation,home:$.home,workspaceRoot:$.workspaceRoot,nativeProfileId:U,credentialRevision:W.credentialRevision,ownership:a8$(G)}),B=Qk({desiredCredentialRevision:W.credentialRevision,desiredNativeProfileId:U,desiredCredentialFingerprint:H,ledger:z,native:V});if(B.requiresWriteAheadIntent)bD(Y,$.runtime,W.providerId,Wk(B));oi$({decision:B,runtime:$.runtime,observation:$.observation,home:$.home,workspaceRoot:$.workspaceRoot,nativeProfileId:U,credentialRevision:W.credentialRevision,material:W.material}),bD(Y,$.runtime,W.providerId,B.nextLedger)}}function ti$($,J,X,Q,W,Y,G,z,U){if(!J.enabled||J.status==="install_failed"||!J.commandPath)return{path:null,revision:null,providerIds:[]};let H=mD(fB(X,$));if(bv($,X,H),X.runtimes[$]?.providerMode==="configured"&&!H){if($==="openclaw")X5$(J.commandPath,X,Q,W,Y,z);return{path:null,revision:null,providerIds:[...G]}}if($==="hermes")return Y0(()=>R5$(J,H,G,W,Y));if($==="openclaw"){if(OG(X))$8$({home:W,commandPath:J.commandPath,appRoot:J.appRoot});X5$(J.commandPath,X,Q,W,Y,z);let V=SD(H,G);if(V.apply)Go$(J,V,W,Y);if(OG(X)){if(U.length===0)throw Error("OpenClaw managed provider-auth stores were not transactionally discovered");pi$(J,W,Y,U)}return{path:J.commandPath,revision:null,providerIds:V.providerIds}}return{path:null,revision:null,providerIds:[]}}function ei$($,J,X,Q,W){if($!=="openclaw"&&$!=="hermes"||!J.enabled||J.status==="install_failed"||!J.commandPath)return null;let Y=mD(fB(X,$));if(bv($,X,Y),X.runtimes[$]?.providerMode==="configured"&&!Y)return null;if($==="openclaw"){let G=SD(Y,W);if(!Y)return V1({openClawProviderProjection:"delete",patch:JSON.parse(G.content)});return V1({openClawProviderProjection:"json-patch",patch:b5$("openclaw",JSON.parse(G.content),Y)})}return R5$(J,Y,W,Q,Q,!1).revision}function b5$($,J,X){let Q=j$(J),W=new Set(X.catalog.providers.filter((U)=>U.managed_by==="clawdi").map((U)=>U.id));if(!Q||W.size===0)return J;let Y=$==="openclaw"?j$(Q.models):Q;if(!Y)return J;let G=j$(Y.providers);if(!G)return J;let z=Object.fromEntries(Object.entries(G).map(([U,H])=>{let V=j$(H);if(!W.has(U)||!V)return[U,H];let{models:B,...w}=V;return[U,w]}));if($==="openclaw")return{...Q,models:{...Y,providers:z}};return{...Q,providers:z}}function $o$($,J,X){let Q=Iv($);if(!Q)return{path:null,revision:null,providerIds:[]};let W=I5$(J);FG(W,J);let Y=v(W,Kv),G=A5$(Q);return k$(Y,G,{mode:384,dirMode:448}),v4(Y),FG(W,J),{path:Y,providerIds:[qv],revision:V1({codexManagedProviderProjection:Kv,configContent:G,codexCli:X})}}function bv($,J,X){if(J.runtimes[$]?.providerMode==="unmanaged"&&X)throw Error(`runtime ${$} unmanaged provider mode has a provider projection`)}function Iv($){let J=j$($.projection?.terminalTooling),X=j$(J?.codex),Q=j$(X?.provider),W=j$(X?.primary_model),Y=H4(X?.provider_id),G=H4(Q?.baseUrl),z=H4(Q?.apiMode),U=H4(W?.model);if(X?.enabled!==!0||!Q||Q.managed_by!=="clawdi"||z!=="openai_responses"||!RT(H4(Q.runtimeEnvName))||JF(H4(Q.apiKeySecretRef))!=="secret://tool.codex.apiKey"||!Y||H4(W?.provider_id)!==Y||!G||!U)return null;return{baseUrl:G}}function I5$($){return v($,".codex")}function A5$($){let J=["# Generated by Clawdi hosted runtime. Do not put API keys in this file."];return J.push(`model_provider = ${ID(qv)}`,"",`[model_providers.${qv}]`,`name = ${ID("clawdi")}`,`base_url = ${ID($.baseUrl)}`,`env_key = ${ID(I1)}`,'wire_api = "responses"',""),J.join(`
|
|
955
|
+
`}return{existing:X,next:z}}function n8$($,J){return Y0(()=>{let{existing:X,next:Q}=dB($,J);if(Q===X)return $;return k$($,Q,{mode:384,dirMode:448}),v4($),$})}function ED($,J,X){if(!$.commandPath||!E0($.commandPath))throw Error("Hermes config command is unavailable");return{command:$.commandPath,home:J,cwd:X}}function Ri$($,J){H6($,"dashboard.basic_auth",{username:J.username,session_ttl_seconds:J.sessionTtlSeconds}),H6($,"dashboard.public_url",J.publicUrl);let X=kQ($,"plugins.disabled");if(X.exists&&(!Array.isArray(X.value)||X.value.some((W)=>typeof W!=="string")))throw Error("Hermes config field plugins.disabled must be a string array");let Q=new Set((X.exists?X.value:[]).filter((W)=>W!=="dashboard_auth/basic"));Q.add("dashboard_auth/nous"),Q.add("dashboard_auth/self_hosted"),H6($,"plugins.disabled",[...Q].sort())}function Pi$($,J,X,Q,W,Y){if(X.runtimes[$]?.enabled!==!0)return null;let G=X.locale;if($==="openclaw"){if(!W)throw Error("OpenClaw official agent workspace is unavailable");return G?n8$(v(W,"SOUL.md"),lB(G)):null}if($==="hermes"){let z=X.hermesDashboardAuth,U=X.projection?.sourceBundleVersion==="clawdi.hosted-runtime.bundle.v2";if(!z&&!G&&!U)return null;let H=ED(J,Q,Y),V=v(Q,".hermes");if(U)H6(H,"terminal.cwd",Y);if(z)Ri$(H,z);if(G)H6(H,"timezone",G.timezone);return G?n8$(v(V,"SOUL.md"),lB(G)):null}return null}function _v($,J,X,Q,W){let Y=e9$(J,X,Q,W);return J==="hermes"&&X==="dashboard"?Or$($,Y)??Y:Y}function hD($,J,X){return t9$($,J,X)}function uD($,J,X){let Q={...X},W=J?.secretEnv??{};for(let[Y,G]of Object.entries(W)){let z=Q[Y];if(z!==void 0&&z!==G)throw Error(`runtime ${$} secretEnv.${Y} conflicts with provider secret ref ${z}`);Q[Y]=G}for(let Y of Object.keys(J?.env??{}))if(Q[Y]!==void 0)throw Error(`runtime ${$} defines ${Y} in both env and secretEnv`);return Q}function Mv($,J,X,Q){let W={...Q},Y=X.secretEnv??{};for(let[G,z]of Object.entries(Y)){let U=W[G];if(U!==void 0&&U!==z)throw Error(`runtime ${$} service ${J} secretEnv.${G} conflicts with provider secret ref ${U}`);W[G]=z}for(let G of Object.keys(X.env??{}))if(W[G]!==void 0)throw Error(`runtime ${$} service ${J} defines ${G} in both env and secretEnv`);return W}function TD($){return v($.managedSecretRoot,"egress-secrets.json")}function Bv($){return N0({schemaVersion:"clawdi.runtimeEgressSidecarSecrets.v1",secretValues:$})}function j5$($,J){let X=vD(J,Ci$($));return{content:Object.keys(X).length>0?`${JSON.stringify(X,null,2)}
|
|
956
|
+
`:null,revision:Bv(X)}}function Ei$($){if($===null)return Bv({});try{let J=JSON.parse($);if(!J||typeof J!=="object"||Array.isArray(J))return null;let X={};for(let[Q,W]of Object.entries(J)){if(typeof W!=="string")return null;X[Q]=W}return Bv(X)}catch{return null}}function wv($,J){let X=TD(J);if($.content===null)return l4(X,{force:!0}),null;z8(J,X,$.content,{mode:384,dirMode:448}),L5$(X),Ov(J.managedSecretRoot);try{W5(X,384)}catch{}return X}function Ti$($,J,X){let Q=TD(X),W=b4(Q)?w9(Q,"utf-8"):null,Y=j5$($,J);return{path:wv(Y,X),changed:W!==Y.content,material:Y,previousRevision:Ei$(W)}}function p8$($,J){try{let X=YF($,J);if("errors"in X)return null;return j5$(X.manifest,X.secretValues)}catch{return null}}function Ci$($){return dj($.egressProfiles)}function Si$($){let J=new Set,X=Array.isArray($.egressProfiles?.profiles)?$.egressProfiles.profiles:[];for(let Q of X){let W=j$(Q);if(W?.owner==="provider-projection")CD(Q,J);if(W?.owner==="mcp-projection")CD(Q,J);if(W?.owner==="clawdi-native-channels")fi$(W,J)}return[...J].sort()}function fi$($,J){let X=j$($.rewrite);if(!X)return;let Q=j$(X.pathReplace),W=H4(Q?.replacementSecretRef);if(W)J.add(W);let Y=j$(X.setHeaders);if(!Y)return;for(let G of Object.values(Y)){let z=j$(G);if(z?.type!=="secretRef")continue;let U=H4(z.secretRef);if(U)J.add(U)}}function CD($,J){if(!$||typeof $!=="object")return;if(Array.isArray($)){for(let X of $)CD(X,J);return}for(let[X,Q]of Object.entries($)){if(typeof Q==="string"&&(X==="secretRef"||X.endsWith("SecretRef")))J.add(Q);CD(Q,J)}}function mD($){if(!$)return null;let J=new Map,X=$.catalog.providers.map((W)=>{if(W.managed_by!=="clawdi")return W;let Y=g9(W.id)?a6:W.id===CI||W.id.startsWith("clawdi-managed")?W.id:CI;return J.set(W.id,Y),{...W,id:Y,api_mode:g9(Y)?Ll:W.api_mode}}),Q=J.get($.primaryModel.provider_id);if(!Q)return $;return{catalog:{...$.catalog,providers:X,defaults:{...$.catalog.defaults,chat_provider_id:Q}},primaryModel:{...$.primaryModel,provider_id:Q}}}function OG($){let J=$.runtimes.openclaw,X=J?.provider_ids?.[0],Q=X?j$($.projection?.providers?.[X]):null,Y=mD(fB($,"openclaw"))?.catalog.providers.find((G)=>G.id===a6);return $.projection?.sourceBundleVersion==="clawdi.hosted-runtime.bundle.v2"&&J?.enabled===!0&&J.providerMode==="configured"&&typeof X==="string"&&g9(X)&&Q?.managed_by==="clawdi"&&H4(Q.apiKeySecretRef)!==null&&Y?.managed_by==="clawdi"&&Y.runtime_env_name===I1&&Y.auth.type==="api_key"&&Y.auth.source==="managed"}function xi$($,J,X){return l1$($.oauthCredentialRoot,J,X)}function bD($,J,X,Q){Bk($,{runtime:J,providerId:X},Q)}function o8$($){return d1$($,{migrateLegacy:!0})}function ki$($){let J=$.split(".")[1];if(!J)return null;try{let X=JSON.parse(Buffer.from(J,"base64url").toString("utf8")),Q=j$(X)?.exp;return typeof Q==="number"&&Number.isFinite(Q)?Math.trunc(Q*1000):null}catch{return null}}function vi$($){let J=j$(JSON.parse($));if(J?.kind!=="local_agent_profile"||!Array.isArray(J.files))throw Error("hosted OAuth secret is not a local Agent credential profile");let X=J.files.map(j$).find((z)=>z?.logicalName==="auth.json");if(!X||typeof X.content!=="string")throw Error("hosted OAuth credential profile is missing auth.json");let Q=j$(JSON.parse(X.content)),W=j$(Q?.tokens),Y=H4(W?.access_token),G=H4(W?.refresh_token);if(!Y||!G)throw Error("hosted OAuth credential profile is missing access or refresh token");return{accessToken:Y,refreshToken:G,...H4(W?.id_token)?{idToken:H4(W?.id_token)??void 0}:{},...H4(W?.account_id)?{accountId:H4(W?.account_id)??void 0}:{},lastRefresh:H4(Q?.last_refresh)??new Date().toISOString(),expires:ki$(Y)??Date.now()+3600000}}function N5$($,J,X){if($.runtimes[J]?.enabled!==!0)return[];let Q=j$($.projection?.providers);if(!Q)return[];return($.runtimes[J]?.provider_ids??[]).flatMap((W)=>{let Y=Q[W],G=j$(Y),z=j$(G?.auth);if(z?.type!=="agent_profile"||z.tool!=="codex"||typeof z.profile!=="string"||typeof z.credentialSecretRef!=="string"||typeof z.credentialRevision!=="string")return[];let U=w0(X??{},z.credentialSecretRef);if(!U)throw Error(`hosted OAuth secret is unavailable for ${W}`);return[{providerId:W,profile:z.profile,credentialRevision:z.credentialRevision,material:vi$(U)}]})}function jv($){return v($,".hermes","auth.json")}function F5$($,J,X,Q,W,Y,G,z){let U=jv($);FG(g6(U),$);let H=s$("flock",["--timeout","10",v(g6(U),"auth.lock"),"node","--input-type=module","--eval",m1$,U,X,Q,G?.nativeProfileId??"",W,z??""],$,J,{input:Y?JSON.stringify(Y):"null"});if(H.status!==0)throw Error(`Hermes Codex auth ${X} failed: ${w1(String(H.stderr??""))??"unknown"}`);return j$(JSON.parse(String(H.stdout||"{}")))??{}}function gi$($,J,X,Q,W){return Yk(F5$($,J,"inspect",X,Q,void 0,W))}function O5$($,J,X,Q,W,Y,G,z){return Gk(F5$($,J,X,Q,W,Y,G,z))}function D5$($){return v(wG($),"agents","main","agent")}function iB($,J){let X=process.env.CLAWDI_RUNTIME_TEST_OPENCLAW_PROVIDER_AUTH_SDK?.trim();if(X){if(process.env.CLAWDI_RUNTIME_ALLOW_TEST_INSTALLERS!=="1")throw Error("CLAWDI_RUNTIME_TEST_OPENCLAW_PROVIDER_AUTH_SDK requires CLAWDI_RUNTIME_ALLOW_TEST_INSTALLERS=1");return X}let Q=$?.commandPath,W=g1$(J,[Q,$?.appRoot,v(J,".openclaw","lib","node_modules","openclaw"),v(J,".openclaw","node_modules","openclaw"),v(J,".local","lib","node_modules","openclaw")]);if(!W)throw Error("installed OpenClaw provider-auth SDK export is unavailable");return W}function yi$($,J){return u1$(J,[$.commandPath,$.appRoot,v(J,".openclaw","lib","node_modules","openclaw"),v(J,".openclaw","node_modules","openclaw"),v(J,".local","lib","node_modules","openclaw")])}function r8$($,J){let X=yi$($,J);if(!X)return!1;_G(J);let Q=s$("node",["--input-type=module","--eval",hi$,X],J,J);if(Q.status!==0)throw Error(`installed OpenClaw device-bootstrap capability probe failed: ${w1(String(Q.stderr??""))??"unknown"}`);let W=String(Q.stdout??"").trim();if(W==="supported")return!0;if(W==="unsupported")return!1;throw Error("installed OpenClaw device-bootstrap capability probe returned invalid output")}function ci$($,J){let X=iB($,J);_G(J);let Q=s$("node",["--input-type=module","--eval",ui$,X],J,J);if(Q.status!==0)throw Error(`installed OpenClaw public provider-auth SDK is incompatible: ${w1(String(Q.stderr??""))??"capability probe failed"}`)}function li$($,J){let X=iB($,J),Q=cD($,J);if(!Q)throw Error("installed OpenClaw public config-mutation SDK export is unavailable");_G(J);let W=s$("node",["--input-type=module","--eval",mi$,X,Q,tk({home:J,commandPath:$.commandPath,appRoot:$.appRoot})],J,J);if(W.status!==0)throw Error(`installed OpenClaw public managed-provider auth cleanup SDK is incompatible: ${w1(String(W.stderr??""))??"capability probe failed"}`)}function di$($){let J=N5$($.manifest,"openclaw",$.secretValues),X=OG($.manifest);if(J.length===0&&!X)return $.observation;let Q=J.length>0&&X?"OpenClaw credential convergence":X?"OpenClaw managed API-key cleanup":"OpenClaw OAuth",W=(Y)=>{if(J.length>0)ci$(Y,$.home);if(X)li$(Y,$.home)};try{return W($.observation),$.observation}catch(Y){let G=Y instanceof Error?Y.message:String(Y);throw Error(`${Q} requires the public OpenClaw SDK; automatic runtime reinstall is disabled: ${w1(G)??"capability probe failed"}`)}}function Z5$($,J,X,Q,W,Y,G,z,U){let H=G?JSON.stringify({type:"oauth",provider:tp$,access:G.accessToken,refresh:G.refreshToken,expires:G.expires,...G.idToken?{idToken:G.idToken}:{},...G.accountId?{accountId:G.accountId}:{},copyToAgents:!1}):"",V=s$("node",["--input-type=module","--eval",c1$,iB($,J),D5$(J),Q,W,z?.nativeProfileId??"",Y,U??""],J,X,{input:H||"null"});if(V.status!==0)throw Error(`OpenClaw provider-auth ${Q} failed: ${w1(String(V.stderr??""))??"unknown"}`);return j$(JSON.parse(String(V.stdout||"{}")))??{}}function ni$($,J,X,Q,W,Y){return Yk(Z5$($,J,X,"inspect",Q,W,void 0,Y))}function _5$($,J,X,Q,W,Y,G,z,U){return Gk(Z5$($,J,X,Q,W,Y,G,z,U))}function pi$($,J,X,Q){let W=cD($,J);if(!W)throw Error("installed OpenClaw public config-mutation SDK export is unavailable");let Y=s$("node",["--input-type=module","--eval",zk,iB($,J),W,J,"cleanup",JSON.stringify(Q)],J,X);if(Y.status!==0)throw Error(`OpenClaw managed provider-auth cleanup failed: ${w1(String(Y.stderr||Y.stdout||""))??"unknown"}`)}function ii$($,J){let X=cD($,J);if(!X)throw Error("installed OpenClaw public config-mutation SDK export is unavailable");let Q=s$("node",["--input-type=module","--eval",zk,iB($,J),X,J,"discover"],J,J);if(Q.status!==0)throw Error(`OpenClaw managed provider-auth store discovery failed: ${w1(String(Q.stderr||Q.stdout||""))??"unknown"}`);let W=j$(JSON.parse(String(Q.stdout||"{}")));if(!W||!Array.isArray(W.agentDirs))throw Error("OpenClaw managed provider-auth store discovery returned invalid output");let Y=W.agentDirs.filter((G)=>typeof G==="string");if(Y.length!==W.agentDirs.length||Y.length===0)throw Error("OpenClaw managed provider-auth store discovery returned invalid targets");return Y}function a8$($){if(!$)return;let J=$.state==="seeded"?$.credentialFingerprint:$.state==="intent"&&$.operation==="remove"?$.beforeCredentialFingerprint:void 0;if($.state!=="seeded"&&!($.state==="intent"&&$.operation==="remove"))return;return{nativeProfileId:$.nativeProfileId,...J?{credentialRevision:$.credentialRevision,credentialFingerprint:J}:{}}}function s8$($){if($.runtime==="hermes")return gi$($.home,$.workspaceRoot,$.nativeProfileId,$.credentialRevision,$.ownership);return ni$($.observation,$.home,$.workspaceRoot,$.nativeProfileId,$.credentialRevision,$.ownership)}function oi$($){let J=$.decision.nativeAction;if(J==="preserve")return;if(J==="remove")throw Error("Desired hosted OAuth reconciliation cannot remove a credential");let X=J==="seed"?"seed-if-missing":"upsert",Q=J==="seed"?"missing":Nv($.decision.expectedCredentialFingerprint,"before"),W=Nv($.decision.targetCredentialFingerprint,"target"),Y;if($.runtime==="hermes")Y=O5$($.home,$.workspaceRoot,X,$.nativeProfileId,$.credentialRevision,$.material,void 0,Q);else Y=_5$($.observation,$.home,$.workspaceRoot,X,$.nativeProfileId,$.credentialRevision,$.material,void 0,Q);ai$(Y,Q,W,`${$.runtime} OAuth credential`)}function ri$($){let J;if($.runtime==="hermes")J=O5$($.home,$.workspaceRoot,"remove",$.nativeProfileId,$.credentialRevision,void 0,$.ownership,$.expectedFingerprint);else J=_5$($.observation,$.home,$.workspaceRoot,"remove",$.nativeProfileId,$.credentialRevision,void 0,$.ownership,$.expectedFingerprint);si$(J,$.expectedFingerprint,`${$.runtime} OAuth credential`)}function Nv($,J){if(!$)throw Error(`OAuth credential decision is missing ${J} fingerprint evidence`);return $}function ai$($,J,X,Q){if(!$.casMatched)throw Error(`${Q} changed before the mutation could be applied`);if(M5$($,J,Q),!$.updated||$.afterCredentialFingerprint!==X)throw Error(`${Q} mutation did not produce the intended fingerprint`)}function si$($,J,X){if(!$.casMatched)throw Error(`${X} changed before removal could be applied`);if(M5$($,J,X),!$.updated||$.afterCredentialFingerprint)throw Error(`${X} removal could not verify absence`)}function M5$($,J,X){if(!(J==="missing"?$.beforeCredentialFingerprint===void 0:$.beforeCredentialFingerprint===J))throw Error(`${X} mutation returned inconsistent before evidence`)}function t8$($){let J=N5$($.manifest,$.runtime,$.secretValues),X=new Set(J.map((W)=>W.providerId)),Q=v($.paths.oauthCredentialRoot,$.runtime);if(b4(Q))for(let W of lX(Q).filter((Y)=>Y.endsWith(".json"))){let Y=v(Q,W),G=o8$(Y);if(!G||X.has(G.providerId)||G.state==="retired")continue;let z=nO(G),U=a8$(G),H=s8$({runtime:$.runtime,observation:$.observation,home:$.home,workspaceRoot:$.workspaceRoot,nativeProfileId:G.nativeProfileId,credentialRevision:G.credentialRevision,ownership:U}),V=Qk({desiredCredentialRevision:null,desiredNativeProfileId:null,desiredCredentialFingerprint:null,ledger:z,native:H});if(V.requiresWriteAheadIntent)bD(Y,$.runtime,G.providerId,Wk(V));if(V.nativeAction==="remove"){let B=Nv(V.expectedCredentialFingerprint,"before"),w=U??{nativeProfileId:G.nativeProfileId,credentialRevision:G.credentialRevision,credentialFingerprint:B};ri$({runtime:$.runtime,observation:$.observation,home:$.home,workspaceRoot:$.workspaceRoot,nativeProfileId:G.nativeProfileId,credentialRevision:G.credentialRevision,ownership:w,expectedFingerprint:B})}bD(Y,$.runtime,G.providerId,V.nextLedger)}for(let W of J){let Y=xi$($.paths,$.runtime,W.providerId),G=o8$(Y),z=nO(G),U=k1$($.runtime,W.providerId),H=v1$(W.credentialRevision,W.material.accessToken,W.material.refreshToken),V=s8$({runtime:$.runtime,observation:$.observation,home:$.home,workspaceRoot:$.workspaceRoot,nativeProfileId:U,credentialRevision:W.credentialRevision,ownership:a8$(G)}),B=Qk({desiredCredentialRevision:W.credentialRevision,desiredNativeProfileId:U,desiredCredentialFingerprint:H,ledger:z,native:V});if(B.requiresWriteAheadIntent)bD(Y,$.runtime,W.providerId,Wk(B));oi$({decision:B,runtime:$.runtime,observation:$.observation,home:$.home,workspaceRoot:$.workspaceRoot,nativeProfileId:U,credentialRevision:W.credentialRevision,material:W.material}),bD(Y,$.runtime,W.providerId,B.nextLedger)}}function ti$($,J,X,Q,W,Y,G,z,U){if(!J.enabled||J.status==="install_failed"||!J.commandPath)return{path:null,revision:null,providerIds:[]};let H=mD(fB(X,$));if(bv($,X,H),X.runtimes[$]?.providerMode==="configured"&&!H){if($==="openclaw")X5$(J.commandPath,X,Q,W,Y,z);return{path:null,revision:null,providerIds:[...G]}}if($==="hermes")return R5$(J,H,G,W,Y);if($==="openclaw"){if(OG(X))$8$({home:W,commandPath:J.commandPath,appRoot:J.appRoot});X5$(J.commandPath,X,Q,W,Y,z);let V=SD(H,G);if(V.apply)Go$(J,V,W,Y);if(OG(X)){if(U.length===0)throw Error("OpenClaw managed provider-auth stores were not transactionally discovered");pi$(J,W,Y,U)}return{path:J.commandPath,revision:null,providerIds:V.providerIds}}return{path:null,revision:null,providerIds:[]}}function ei$($,J,X,Q,W){if($!=="openclaw"&&$!=="hermes"||!J.enabled||J.status==="install_failed"||!J.commandPath)return null;let Y=mD(fB(X,$));if(bv($,X,Y),X.runtimes[$]?.providerMode==="configured"&&!Y)return null;if($==="openclaw"){let G=SD(Y,W);if(!Y)return V1({openClawProviderProjection:"delete",patch:JSON.parse(G.content)});return V1({openClawProviderProjection:"json-patch",patch:b5$("openclaw",JSON.parse(G.content),Y)})}return R5$(J,Y,W,Q,Q,!1).revision}function b5$($,J,X){let Q=j$(J),W=new Set(X.catalog.providers.filter((U)=>U.managed_by==="clawdi").map((U)=>U.id));if(!Q||W.size===0)return J;let Y=$==="openclaw"?j$(Q.models):Q;if(!Y)return J;let G=j$(Y.providers);if(!G)return J;let z=Object.fromEntries(Object.entries(G).map(([U,H])=>{let V=j$(H);if(!W.has(U)||!V)return[U,H];let{models:B,...w}=V;return[U,w]}));if($==="openclaw")return{...Q,models:{...Y,providers:z}};return{...Q,providers:z}}function $o$($,J,X){let Q=Iv($);if(!Q)return{path:null,revision:null,providerIds:[]};let W=I5$(J);FG(W,J);let Y=v(W,Kv),G=A5$(Q);return k$(Y,G,{mode:384,dirMode:448}),v4(Y),FG(W,J),{path:Y,providerIds:[qv],revision:V1({codexManagedProviderProjection:Kv,configContent:G,codexCli:X})}}function bv($,J,X){if(J.runtimes[$]?.providerMode==="unmanaged"&&X)throw Error(`runtime ${$} unmanaged provider mode has a provider projection`)}function Iv($){let J=j$($.projection?.terminalTooling),X=j$(J?.codex),Q=j$(X?.provider),W=j$(X?.primary_model),Y=H4(X?.provider_id),G=H4(Q?.baseUrl),z=H4(Q?.apiMode),U=H4(W?.model);if(X?.enabled!==!0||!Q||Q.managed_by!=="clawdi"||z!=="openai_responses"||!RT(H4(Q.runtimeEnvName))||JF(H4(Q.apiKeySecretRef))!=="secret://tool.codex.apiKey"||!Y||H4(W?.provider_id)!==Y||!G||!U)return null;return{baseUrl:G}}function I5$($){return v($,".codex")}function A5$($){let J=["# Generated by Clawdi hosted runtime. Do not put API keys in this file."];return J.push(`model_provider = ${ID(qv)}`,"",`[model_providers.${qv}]`,`name = ${ID("clawdi")}`,`base_url = ${ID($.baseUrl)}`,`env_key = ${ID(I1)}`,'wire_api = "responses"',""),J.join(`
|
|
957
957
|
`)}function Jo$($){if(process.env.CLAWDI_CODEX_INSTALL_DISABLED==="1")return null;let J=$.userNpmPrefix,X=v(J,"bin","codex");Qo$(X,$.userHome);let Q=e8$(J);if(Q===null||!E0(X)){if(Xo$(i8$,J,$),Q=e8$(J),Q!==Lv)throw Error(`Codex bootstrap installed version ${Q??"unknown"}; expected ${Lv}`);if(!E0(X))throw Error(`Codex bootstrap did not create ${X}`)}if(Q===null)throw Error("Codex package metadata is unavailable");return{commandPath:X,npmPrefix:J,bootstrapPackageSpec:i8$,installedVersion:Q,realBin:X}}function e8$($){let J=v($,"lib","node_modules","@openai","codex","package.json");try{let X=JSON.parse(w9(J,"utf8"));if(!X||typeof X!=="object"||!("version"in X))return null;return typeof X.version==="string"&&o4(X.version)?X.version:null}catch{return null}}function Xo$($,J,X){if(!pN("npm"))throw Error("Codex bootstrap requires npm on PATH");Y0(()=>pQ(J,{recursive:!0}));let Q=s$("npm",["install","-g","--prefix",J,"--ignore-scripts","--fetch-retries","2","--fetch-retry-mintimeout","1000","--fetch-retry-maxtimeout","10000","--fetch-timeout","60000","--omit=dev","--no-audit","--no-fund","--no-update-notifier",$],X.userHome,X.userHome,{timeoutMs:600000});if(Q.status!==0)throw Error(`Codex bootstrap failed: ${w1(Q.stderr?.toString())??w1(Q.stdout?.toString())??"npm failed"}`)}function Qo$($,J){let X;try{X=w9($,"utf8")}catch{return}let Q=v(J,".local","share","clawdi","codex","bin","codex"),W=["#!/usr/bin/env sh",`export ${I1}='${e7}'`,`exec '${Q}' "$@"`,""].join(`
|
|
958
|
-
`);if(X===W)Y0(()=>l4($))}function R5$($,J,X,Q,W,Y=!0){let G=v(Q,".hermes","config.yaml");if(Y)Wo$(Q);if(!J){let q=fD(new Set(X),new Set);if(Y&&q.length>0)J5$(ED($,Q,W),{},q);return{path:null,providerIds:[],revision:V1({hermesProviderProjection:"none",deletedProviderIds:q})}}if(!$.commandPath)return{path:null,revision:null,providerIds:[]};let H=mO("hermes",J.catalog,J.primaryModel,{freezeManagedModelCatalog:!0}).files.find((q)=>q.path.endsWith(".hermes.yaml"));if(!H)throw Error("Hermes projection did not include a config merge YAML file.");let V=[...wo$(H.content)].sort(),B=fD(new Set(X),new Set(V)),w=Ko$(H.content,B);if(Y){let q=u8(H.content),L=j$(q);if(!L)throw Error("Hermes projection patch must be a YAML object.");J5$(ED($,Q,W),L,B)}return{path:G,providerIds:V,revision:V1({hermesProviderProjection:"yaml-merge",patch:b5$("hermes",u8(w),J)})}}function ID($){return JSON.stringify($)}function P5$($){return v($,".hermes","plugins","model-providers","clawdi")}function Wo$($){l4(P5$($),{recursive:!0,force:!0})}function cD($,J){let X=$.commandPath;return y1$(J,[X,$.appRoot,v(J,".openclaw","lib","node_modules","openclaw"),v(J,".openclaw","node_modules","openclaw"),v(J,".local","lib","node_modules","openclaw")])}function Go$($,J,X,Q){let W=cD($,X);if(!W){Q9($.commandPath??"openclaw",["config","patch","--stdin",...J.args],J.content,X,Q);return}_G(X),Q9("node",["--input-type=module","--eval",Yo$,W],J.content,X,Q)}function SD($,J){if(!$){let z=fD(new Set(J),new Set);return{apply:z.length>0,args:[],content:`${JSON.stringify(Bo$(z),null,2)}
|
|
958
|
+
`);if(X===W)Y0(()=>l4($))}function R5$($,J,X,Q,W,Y=!0){let G=v(Q,".hermes","config.yaml");if(Y)Wo$(Q);if(!J){let q=fD(new Set(X),new Set);if(Y&&q.length>0)J5$(ED($,Q,W),{},q);return{path:null,providerIds:[],revision:V1({hermesProviderProjection:"none",deletedProviderIds:q})}}if(!$.commandPath)return{path:null,revision:null,providerIds:[]};let H=mO("hermes",J.catalog,J.primaryModel,{freezeManagedModelCatalog:!0}).files.find((q)=>q.path.endsWith(".hermes.yaml"));if(!H)throw Error("Hermes projection did not include a config merge YAML file.");let V=[...wo$(H.content)].sort(),B=fD(new Set(X),new Set(V)),w=Ko$(H.content,B);if(Y){let q=u8(H.content),L=j$(q);if(!L)throw Error("Hermes projection patch must be a YAML object.");J5$(ED($,Q,W),L,B)}return{path:G,providerIds:V,revision:V1({hermesProviderProjection:"yaml-merge",patch:b5$("hermes",u8(w),J)})}}function ID($){return JSON.stringify($)}function P5$($){return v($,".hermes","plugins","model-providers","clawdi")}function Wo$($){Y0(()=>l4(P5$($),{recursive:!0,force:!0}))}function cD($,J){let X=$.commandPath;return y1$(J,[X,$.appRoot,v(J,".openclaw","lib","node_modules","openclaw"),v(J,".openclaw","node_modules","openclaw"),v(J,".local","lib","node_modules","openclaw")])}function Go$($,J,X,Q){let W=cD($,X);if(!W){Q9($.commandPath??"openclaw",["config","patch","--stdin",...J.args],J.content,X,Q);return}_G(X),Q9("node",["--input-type=module","--eval",Yo$,W],J.content,X,Q)}function SD($,J){if(!$){let z=fD(new Set(J),new Set);return{apply:z.length>0,args:[],content:`${JSON.stringify(Bo$(z),null,2)}
|
|
959
959
|
`,providerIds:[]}}let Q=mO("openclaw",$.catalog,$.primaryModel).files.find((z)=>z.path.endsWith(".openclaw.json"));if(!Q)throw Error("OpenClaw projection did not include a config patch JSON file.");let W=[...zo$(Q.content)].sort(),Y=fD(new Set(J),new Set(W)),G=W.length>0?Ho$(Q.content,"replace"):Q.content;return{apply:!0,args:Uo$(Q.content),content:Vo$(G,Y),providerIds:W}}function zo$($){let J=JSON.parse($),X=j$(J),Q=X?j$(X.models):null,W=Q?j$(Q.providers):null;if(!W)return new Set;return new Set(Object.entries(W).filter(([,Y])=>Y!==null).map(([Y])=>Y))}function Uo$($){let J=JSON.parse($),X=j$(J),Q=X?j$(X.models):null,W=Q?j$(Q.providers):null;if(!W)return[];return Object.entries(W).flatMap(([Y,G])=>{if(!j$(G))return[];return["--replace-path",`models.providers[${JSON.stringify(Y)}]`]})}function Ho$($,J){let X=JSON.parse($),Q=j$(X);if(!Q)return $;let W={...Q},Y={...j$(W.models)??{},mode:J};return W.models=Y,`${JSON.stringify(W,null,2)}
|
|
960
960
|
`}function Vo$($,J){if(J.length===0)return $;let X=JSON.parse($),Q=j$(X);if(!Q)return $;let W={...Q},Y=j$(W.models),G=Y?{...Y}:{mode:"merge"},z=j$(G.providers),U=z?{...z}:{};for(let H of J)U[H]=null;return G.providers=U,W.models=G,`${JSON.stringify(W,null,2)}
|
|
961
961
|
`}function Bo$($){return{models:{mode:"merge",providers:Object.fromEntries($.map((J)=>[J,null]))}}}function wo$($){if(!$.trim())return new Set;let J=u8($),X=j$(J),Q=X?j$(X.providers):null;if(!Q)return new Set;return new Set(Object.entries(Q).filter(([,W])=>W!==null).map(([W])=>W))}function J5$($,J,X){let Q=j$(J.model)??{},W=new Set([...qo$,...Object.keys(Q)]);for(let H of[...W].sort()){let V=Object.hasOwn(Q,H)?Q[H]:void 0;H6($,`model.${H}`,V===null?void 0:V)}if(!Object.hasOwn(Q,"provider")&&X.length>0){let H=K0$($,"model.provider");if(H.exists&&typeof H.value!=="string")throw Error("Hermes config field model.provider must be a string");let V=new Set(X.flatMap((B)=>[B,`custom:${B}`]));if(H.exists&&V.has(H.value)){if(H6($,"model.provider",void 0),!Object.hasOwn(Q,"default"))H6($,"model.default",void 0)}}let Y=kQ($,"providers");if(Y.exists&&!s4(Y.value))throw Error("Hermes config field providers must be an object");let G=Y.exists&&s4(Y.value)?Y.value:{};for(let[H,V]of Object.entries(G))if(V!==void 0&&V!==null&&!s4(V))throw Error(`Hermes provider ${H} must be an object`);let z={...G};for(let H of X)delete z[H];let U=j$(J.providers)??{};for(let[H,V]of Object.entries(U)){if(V===null){delete z[H];continue}if(!s4(V))continue;let B=z[H];if(B!==void 0&&B!==null&&!s4(B))throw Error(`Hermes provider ${H} must be an object`);let w=s4(B)?{...B}:{};for(let N of $5$)delete w[N];let q=!1;for(let[N,F]of Object.entries(V)){if(F===null){delete w[N];continue}w[N]=F,q=!0}let L=Object.keys(w).some((N)=>!$5$.includes(N));if(q||L)z[H]=w;else delete z[H]}if(Object.keys(z).length===0&&Object.keys(G).length===0)return;H6($,"providers",Object.keys(z).length>0?z:void 0)}function Ko$($,J){if(J.length===0)return $;let X=u8($),Q=j$(X);if(!Q)return $;let W={...Q},Y=j$(W.providers),G=Y?{...Y}:{};for(let z of J)G[z]=null;return W.providers=G,`${KV(W).trimEnd()}
|
|
@@ -967,7 +967,7 @@ ${X.join(`
|
|
|
967
967
|
`)}
|
|
968
968
|
`,{mode:416,dirMode:457}),O6())ZG($.paths.egressTransparentEnv,0,$.egressGid);return $.paths.egressTransparentEnv}function Wr$($){if(/[\r\n]/.test($))throw Error("runtime environment files only support single-line values");return`"${$.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function Yr$($){return V5$("sha256").update($).digest("hex")}function Gr$($,J){if(!b4(J.runConfigRoot))return;for(let X of lX(J.runConfigRoot)){if(!X.endsWith(".json"))continue;let Q=X.slice(0,-5);if(!zr$(Q))continue;if(!$.has(Q))l4(v(J.runConfigRoot,X),{force:!0})}}function zr$($){let[J,X,...Q]=$.split("+");if(Q.length>0)return!1;if(!R1.safeParse(J).success)return!1;if(X===void 0)return!0;return dJ.safeParse(X).success}function Ur$($){if($.liveSync?.enabled===!1)return[];let J=$.liveSync?.agents??[],X=new Map;for(let Q of J)X.set(Q.agentType,Q);return[...X.values()].sort((Q,W)=>Q.agentType.localeCompare(W.agentType))}function Hr$($,J){let X=Ur$($),Q=new Set(X.map((G)=>G.agentType)),W=new Set([...Br$(J),...h5$]),Y=Y0(()=>{let G=J.localEnvironments;pQ(G,{recursive:!0}),v4(G);for(let U of W)if(!Q.has(U))l4(v(G,`${U}.json`),{force:!0});let z=[];for(let U of X){let H=v(G,`${U.agentType}.json`);k$(H,`${JSON.stringify({id:U.environmentId,agentType:U.agentType,managedBy:"clawdi runtime init",deploymentId:$.deploymentId,instanceId:$.instanceId},null,2)}
|
|
969
969
|
`,{mode:384,dirMode:448}),v4(H),z.push(H)}return z});return wr$(Q,J),Y}function Vr$($){let J=v($.userHome,".clawdi");if(q0(J)===q0($.clawdiHome))return;let X;try{X=x1(J)}catch(G){if(G.code==="ENOENT")return;throw G}if(!X.isDirectory()||X.isSymbolicLink())return;let Q=v(J,"environments"),W;try{W=x1(Q)}catch(G){if(G.code==="ENOENT")return;throw G}if(!W.isDirectory()||W.isSymbolicLink())return;let Y=!1;for(let G of lX(Q)){if(!G.endsWith(".json"))continue;let z=v(Q,G);try{let U=x1(z);if(!U.isFile()||U.isSymbolicLink())continue;let H;try{H=JSON.parse(w9(z,"utf8"))}catch{continue}if(typeof H!=="object"||H===null||Array.isArray(H)||H.managedBy!=="clawdi runtime init")continue;l4(z),Y=!0}catch(U){if(U.code!=="ENOENT")throw U}}if(!Y)return;Y5$(Q),Y5$(J)}function Y5$($){try{ip$($)}catch(J){let X=J.code;if(X!=="ENOENT"&&X!=="ENOTEMPTY")throw J}}function c5$($){return $.liveSyncEnvironmentIndex}function Br$($){let J=c5$($);if(!b4(J))return[];try{return Oi$.parse(JSON.parse(w9(J,"utf-8"))).agentTypes}catch{return[]}}function wr$($,J){z8(J,c5$(J),`${JSON.stringify({schemaVersion:"clawdi.liveSyncEnvironments.v1",agentTypes:[...$].sort()},null,2)}
|
|
970
|
-
`,{mode:420})}function qr$($,J){let X=g6$($,J??{});if(!X)return null;return Ov(g6(X)),X}function Kr$($){return N0({schemaVersion:"clawdi.daemonAuthTokenRevision.v1",token:$})}function Lr$($,J,X,Q,W,Y){let G=$.runtimes[J],z=G?xB($,J):{placeholderEnv:{},secretEnv:{}},U=G?hD(J,G.run,z.placeholderEnv):void 0,H=G?[...Object.values(uD(J,U,z.secretEnv)),...pB($).filter((q)=>q.target===J||J==="openclaw"&&q.target==="legacy").map((q)=>q.credsJsonSecretRef)]:[],V=oB($),B=J==="openclaw"||J==="hermes",w=null;if(V&&J==="openclaw")w=Rv(V);else if(V&&J==="hermes"&&G?.enabled)w=LD(V,W);return w8$({renderedProjection:{channels:w,gateway:J==="openclaw"?Av($,X,Y):null,locale:$.locale&&B?lB($.locale):$.locale?.timezone??null,mcp:B?C5$($):null,provider:Q},desiredRuntime:G,secretValues:vD(X,H)})}function jr$($,J){return $.workspaceRoot??J.workspaceRoot}function Nr$($){return $.secretValues&&Object.keys($.secretValues).length>0?$.secretValues:void 0}function Fr$($,J,X){let Q=V9($,J);for(let[W,Y]of Object.entries($.runtimes)){let G=R1.parse(W),z=Y.enabled?xB($,W,{validateOverlap:!0}):{placeholderEnv:{},secretEnv:{}},{placeholderEnv:U,secretEnv:H}=z,V=hD(G,Y.run,U);if(Y.enabled)uD(W,V,H);for(let[w,q]of Object.entries(Y.services??{})){let L=dJ.parse(w),N=_v($,G,L,q,U);if(Y.enabled)Mv(W,L,N,H)}if(!Y.enabled||!$.locale)continue;let B=lB($.locale);if(G==="openclaw"){if(!X)throw Error("OpenClaw official agent workspace is unavailable");dB(v(X,"SOUL.md"),B)}else if(G==="hermes")dB(v(Q,".hermes","SOUL.md"),B)}}function G5$($){let J=[];for(let[Q,W]of Object.entries($.manifest.runtimes).sort(([Y],[G])=>Y.localeCompare(G))){let Y=$.observations.get(Q);if(!Y)throw Error(`runtime ${Q} install observation is missing`);let G=l5$({manifest:$.manifest,paths:$.paths,name:Q,runtime:W,observation:Y,workspaceRoot:$.workspaceRoot,generatedAt:$.generatedAt,secretValues:$.secretValues,egressProfileBundlePath:$.egressProfileBundlePath});if(W.enabled&&(HX(Q)||Boolean(W.run?.command?.trim()))){let z=Xv({config:G.runtime,paths:$.paths,secretValues:$.secretValues,egress:$.egress});if(z)J.push(z)}for(let z of G.services){let U=Xv({config:z,paths:$.paths,secretValues:$.secretValues,egress:$.egress});if(U)J.push(U)}}let X=G9$($.manifest,$.paths);if(X)J.push(X);return J}function Or$($,J){let X=$.hermesDashboardAuth;if(!X)return J;if(!X.activation.enabled)throw Error("Hermes password authentication is disabled");return{...J??{},prependPath:J?.prependPath??[],env:J?.env??{},secretEnv:{...J?.secretEnv??{},HERMES_DASHBOARD_BASIC_AUTH_PASSWORD:X.passwordSecretRef,HERMES_DASHBOARD_BASIC_AUTH_SECRET:X.sessionSecretRef}}}function l5$($){let J=R1.parse($.name),X=$.runtime.enabled?xB($.manifest,$.name,{validateOverlap:!0}):{placeholderEnv:{},secretEnv:{}},{placeholderEnv:Q,secretEnv:W}=X,Y=hD(J,$.runtime.run,Q),G=$.runtime.enabled?uD($.name,Y,W):{},z=null,U=_T({runtime:J,enabled:$.runtime.enabled,generatedAt:$.generatedAt,generation:$.manifest.generation,instanceId:$.manifest.instanceId,commandPath:$.observation.commandPath,appRoot:$.observation.appRoot,workspaceRoot:$.workspaceRoot,egressProfileBundlePath:$.egressProfileBundlePath,settings:Y,secretFilePath:null,secretEnv:G}),H=Object.entries($.runtime.services??{}).sort(([V],[B])=>V.localeCompare(B)).map(([V,B])=>{let w=dJ.parse(V),q=_v($.manifest,J,w,B,Q);return _T({runtime:J,service:w,enabled:$.runtime.enabled,generatedAt:$.generatedAt,generation:$.manifest.generation,instanceId:$.manifest.instanceId,commandPath:$.observation.commandPath,appRoot:$.observation.appRoot,workspaceRoot:$.workspaceRoot,settings:q,secretFilePath:null,secretEnv:$.runtime.enabled?Mv($.name,w,q,W):{}})});return{runtime:U,services:H,secretEnv:G,secretFilePath:null}}function hB($){let J=v($.paths.instanceRoot,$.load.manifest.instanceId);return{manifest:$.load.manifest,source:$.load.source,sourcePath:$.load.sourcePath,offline:$.load.offline,mode:$.load.offline?"degraded-offline":"normal",enabledRuntimes:$.enabledRuntimes,installErrors:$.installErrors,resourceProjectionErrors:[],projectedProviderIds:$.projectedProviderIds,agentPluginFailedNames:$.agentPluginFailedNames??[],outputs:{processManager:"systemd",workspaceRoot:$.workspaceRoot,managedConfig:$.paths.managedConfig,syncState:$.paths.syncState,instanceData:$.paths.instanceData,sensitiveInstanceData:$.paths.sensitiveInstanceData,manifestLastGood:null,appliedState:null,installInventory:[],projections:[],managedLocaleFiles:[],runConfigs:[],systemdSystemUnitRoot:$.paths.systemdSystemRoot,systemdSystemUnits:[],systemdUserUnitRoot:$.paths.systemdUserRoot,systemdUserUnits:[],egressProfileBundle:null,egressSecretFile:null,egressEngine:null,egressTransparentEnv:null,egressAddon:null,liveSyncEnvironments:[],daemonAuthTokenFile:null,instanceSemaphores:[],bootFinished:v(J,"boot-finished")}}}function z5$($){let{manifest:J,paths:X,openClawWorkspaceRoot:Q,secretValues:W,observations:Y,previousProjectedProviderIds:G,hermesWhatsAppAuthDir:z,openClawOwnerBrowserBootstrapSupported:U}=$,H=V9(J,X),V=J.locale?lB(J.locale):null;if(V)for(let w of Object.keys(J.runtimes)){if(J.runtimes[w]?.enabled!==!0)continue;if(w==="openclaw"){if(!Q)throw Error("OpenClaw official agent workspace is unavailable");dB(v(Q,"SOUL.md"),V)}if(w==="hermes")dB(v(H,".hermes","SOUL.md"),V)}let B=Iv(J);if(B)A5$(B);for(let[w,q]of Object.entries(J.runtimes).sort(([L],[N])=>L.localeCompare(N))){if(!Y.get(w))throw Error(`runtime ${w} install observation is missing`);let N=R1.parse(w),F=q.enabled?xB(J,w,{validateOverlap:!0}):{placeholderEnv:{},secretEnv:{}},{placeholderEnv:O,secretEnv:_}=F,M=hD(N,q.run,O),b=q.enabled?uD(w,M,_):{};vD(W,Object.values(b));for(let[R,d]of Object.entries(q.services??{})){let $$=dJ.parse(R),Q$=_v(J,N,$$,d,O);Mv(w,$$,Q$,_)}let Z=mD(fB(J,w));bv(w,J,Z);let I=J.runtimes[w]?.providerMode==="configured"&&!Z;if(w==="openclaw"){if(Z)SD(Z,G.openclaw??[]);else if(!I)SD(null,G.openclaw??[]);JSON.stringify(Av(J,W,U))}if(w==="hermes"){if(Z){let d=mO("hermes",Z.catalog,Z.primaryModel,{freezeManagedModelCatalog:!0}).files.find(($$)=>$$.path.endsWith(".hermes.yaml"));if(!d)throw Error("Hermes projection did not include a config merge YAML file.");if(!j$(u8(d.content)))throw Error("Hermes projection patch must be a YAML object.")}}let P=oB(J);if(P&&w==="openclaw")JSON.stringify(Rv(P));if(P&&w==="hermes"&&q.enabled)LD(P,z)}lo$(J,X,Y),Qi$(J,W,H)}function d5$($,J,X){let Q=new Set,W=X.get("openclaw");if($.runtimes.openclaw?.enabled&&$.runtimes.openclaw.install&&W?.status!=="present")Q.add(v(J,".local","bin","openclaw")),Q.add(v(J,".local","tools"));let Y=X.get("hermes");if($.runtimes.hermes?.enabled&&$.runtimes.hermes.install&&Y?.status!=="present")for(let G of[v(J,".hermes","hermes-agent"),v(J,".hermes","bin"),v(J,".hermes","node"),v(J,".hermes","uv"),v(J,".hermes",".env"),v(J,".hermes",".no-bundled-skills"),v(J,".hermes","config.yaml"),v(J,".hermes","SOUL.md"),v(J,".hermes","skills"),v(J,".local","bin","hermes"),v(J,".local","bin","hermes-agent"),v(J,".local","bin","hermes-acp"),v(J,".local","bin","node"),v(J,".local","bin","npm"),v(J,".local","bin","npx")])Q.add(G);return[...Q]}function Zr$($,J,X){if(!Object.entries($.runtimes).some(([H,V])=>{if(!V.enabled||!V.install)return!1;return X.get(H)?.status!=="present"}))return null;let W=V9($,J),Y=d5$($,W,X).sort();if(Y.length===0)return null;let G=[J.userHome,J.clawdiHome],z=[...new Set([J.userHome,J.clawdiHome,...DG(Y,G),...$.runtimes.hermes?.enabled&&$.runtimes.hermes.install&&X.get("hermes")?.status!=="present"?Dr$.map((H)=>v(W,".hermes",H)):[]])].sort(),U=Object.keys($.runtimes).flatMap((H)=>{let V=iQ(H,W);return V&&Y.includes(V)?[V]:[]});return{snapshot:{rootTargets:[],trustedRootDirectories:[],runtimeUserTargets:Y,runtimeUserTrustedRoots:G,runtimeUserSymlinkTargets:U,metadataTargets:z},runtimeUserOwnershipTargets:[...new Set([...z,...Y])].sort((H,V)=>H.length-V.length||H.localeCompare(V))}}function U5$($,J){let X=J.runtimeUserTargets.map((Y)=>q0(Y)),Q=(Y)=>{let G=q0(Y);return X.some((z)=>{let U=kD(z,G);return U===""||!U.startsWith("..")&&!nB(U)})},W=new Set(J.metadataTargets.map((Y)=>q0(Y)));return{...$,runtimeUserTargets:$.runtimeUserTargets.filter((Y)=>!Q(Y)),runtimeUserSymlinkTargets:$.runtimeUserSymlinkTargets.filter((Y)=>!Q(Y)),metadataTargets:$.metadataTargets.filter((Y)=>!Q(Y)&&!W.has(q0(Y)))}}function _r$($,J){if(!OG($))return null;let X=qG(V9($,J)),Q=[J.userHome,J.clawdiHome];return{rootTargets:[],trustedRootDirectories:[],runtimeUserTargets:[X],runtimeUserTrustedRoots:Q,runtimeUserSymlinkTargets:[],metadataTargets:DG([X],Q)}}function Mr$($,J){let X=new Set(Dv($)?pB($).map((Y)=>Y.authDir):[]),Q=cB(J,"openclaw");if(Q&&b4(Q))for(let Y of lX(Q)){let G=v(Q,Y);if(NG(G))X.add(G)}let W=cB(J,"hermes");if(W&&NG(W)?.target==="hermes")X.add(W);return[...X]}function n5$($){let J=new Set;for(let X of pB($))J.add(X.target==="hermes"?"hermes":"openclaw");if(J.size>1)throw Error("managed WhatsApp projection must target exactly one native runtime");return J.values().next().value??null}function br$($,J,X,Q){let W=V9($,J),Y=d5$($,W,Q),G=n5$($),z=oB($),U=z?Object.keys(z).filter((B)=>Boolean(u5$[B])).map((B)=>v(W,".openclaw","extensions",B)):[],H=new Set([sk(W),v(W,".hermes","config.yaml"),v(W,".hermes","SOUL.md"),jv(W),v(g6(jv(W)),"auth.lock"),D5$(W),v(I5$(W),Kv),P5$(W),...Y,...Mr$($,W),...U]);if(OG($))for(let B of aJ$(W))H.add(B);if(X)H.add(v(X,"SOUL.md"));for(let B of Y5){if($.runtimes[B]?.enabled!==!0)continue;let w=iQ(B,W);if(w&&!Y.some((q)=>{let L=kD(q0(q),q0(w));return L===""||!L.startsWith("..")&&!nB(L)}))H.add(w)}let V=IJ$({desiredRuntime:G,home:W,paths:J});for(let B of V){let w=yD(B,W);if(!w)continue;for(let q of AJ$({runtime:B,home:W,appRoot:w})){if([...Y,...U].some((L)=>q===L||q.startsWith(`${L}/`)))continue;H.add(q)}}for(let B of h5$)H.add(v(J.localEnvironments,`${B}.json`));return[...H].sort()}function Ir$($,J,X){let Q=new Set;for(let z of Y5)for(let U of SJ()){let H=aB(z,U,J,X??void 0);if(H)Q.add(H)}let W=v(J,".hermes","skills"),Y=X?v(X,"skills"):null,G=!1;for(let[z,U]of Object.entries($.projection?.skills?.entries??{})){if(!("source"in U))continue;if($.runtimes.hermes?.enabled===!0)G=!0,Q.add(v(W,z));if($.runtimes.openclaw?.enabled===!0&&Y)Q.add(v(Y,z))}for(let z of lW("hosted-manifest")){if(g6(z.targetDir)===W&&!SJ().includes(z.id))G=!0,Q.add(z.targetDir);if(Y&&g6(z.targetDir)===Y&&!SJ().includes(z.id))Q.add(z.targetDir)}if(G)Q.add(v(W,".hub"));return[...Q].sort()}function DG($,J){let X=J.map((W)=>q0(W)),Q=new Set;for(let W of $){let Y=q0(W),G=X.find((U)=>{let H=kD(U,Y);return H===""||!H.startsWith("..")&&!nB(H)});if(!G)throw Error(`runtime mutation target is outside managed user roots: ${Y}`);if(Y===G)continue;let z=g6(Y);while(z!==G)Q.add(z),z=g6(z)}return[...Q]}function Ar$($){let J=new Set(UJ$($.manifest,$.paths)),X=Q9$($.manifest,$.paths);for(let q of X.rootTargets)J.add(q);J.add(UG($.paths));let Q=new Set,W=$.manifest.egressEngine;if(W?.type==="mitmproxy"){let q=v($.paths.egressEngineMaintainedRoot,W.version,W.sha256.toLowerCase());if(!E0(v(q,"mitmdump")))J.add(q);Q.add(g6($.paths.egressEngineMaintainedRoot)),Q.add($.paths.egressEngineMaintainedRoot),Q.add(v($.paths.egressEngineMaintainedRoot,W.version))}let Y=g8$($.programs,$.paths);for(let q of Y.environmentTargets)J.add(q);let G=[...new Set([...br$($.manifest,$.paths,$.openClawWorkspaceRoot,$.observations),...Y.targets])].sort(),z=[...J].sort(),U=V9($.manifest,$.paths),H=Y5.flatMap((q)=>{if($.manifest.runtimes[q]?.enabled!==!0)return[];let L=iQ(q,U);return L?[L]:[]}),V=[$.paths.userHome,$.paths.clawdiHome],B=[...new Set([...Y.metadataTargets,$.paths.userHome,$.paths.clawdiHome,...DG(G,V)])].sort(),w=[...new Set([...G,...B,...H])].sort((q,L)=>q.length-L.length||q.localeCompare(L));return{snapshot:{rootTargets:z,trustedRootDirectories:[...HJ$($.manifest,$.paths),...X.rootTrustedRoots],runtimeUserTargets:G,runtimeUserTrustedRoots:V,runtimeUserSymlinkTargets:[...new Set([...Y.symlinkTargets,...H.filter((q)=>G.includes(q))])].sort(),metadataTargets:[...new Set([...Q,...Y.metadataTargets,$.paths.configurationRoot,$.paths.serviceStateRoot,$.paths.cacheRoot,$.paths.runRoot,$.paths.systemdSystemRoot,...DG(z,[$.paths.configurationRoot,$.paths.serviceStateRoot,$.paths.cacheRoot,$.paths.runRoot,$.paths.systemdSystemRoot]),...B])].sort()},runtimeUserOwnershipTargets:w,staleOfficialUnits:Y.staleOfficialUnits,systemdUserUnits:Y.unitNames,systemdDriftErrors:Y.driftErrors}}function RD($){if(!O6())return;let J=process.env.CLAWDI_RUNTIME_USER?.trim();if(!J||J==="root"||J==="0")return;let X=X9(J),Q=l8(J);if(X===0||Q===0)throw Error(`runtime user ${J} resolved to a root filesystem identity`);for(let W of $){let Y;try{Y=x1(W)}catch(G){if(G.code==="ENOENT")continue;throw G}if(Y.uid===X&&Y.gid===Q)continue;if(Y.isSymbolicLink())dp$(W,X,Q);else ZG(W,X,Q)}}function p5$($,J,X={}){let{manifest:Q}=$;if((cH(Q)||X.preparedHostedAgentPlugins)&&Q.projection?.sourceBundleVersion!=="clawdi.hosted-runtime.bundle.v2")throw Error(tj);if(cH(Q)&&!X.preparedHostedAgentPlugins&&!X.resourcePreparationFailures?.agentPlugins)throw Error(nJ);let W=Nr$($),Y=$.applyContext;if(!Y)throw Error("runtime manifest convergence requires an explicit apply context");let G=jB(J,Y,X.hostedRuntimeContract),z=V9(Q,J);wi$(Q,z);let U=cJ$(Q,z);if(G1$(J),Vr$(J),Q.companions?.filebrowser){if(Q.projection?.sourceBundleVersion!=="clawdi.hosted-runtime.bundle.v2")throw Error("Files companion requires a hosted v2 bundle");if(!X.systemdApply)throw Error("Files companion requires systemd apply and readiness hooks")}let H=jr$(Q,J),V=null,B=new Set,w=null,q=null,L=!1,N=!1,F=!1,O=[],_=[],M=new Set,b=[],Z=Object.entries(Q.runtimes).filter(([,F$])=>F$.enabled).map(([F$])=>F$).sort(),I=new Date().toISOString(),P=qi({generatedAt:I,generation:Q.generation,instanceId:Q.instanceId,profiles:Q.egressProfiles}),R=qT(P)?J.egressProfileBundle:null,d=v(J.instanceRoot,Q.instanceId),$$=v(d,"sem"),Q$=[],X$=[],k=[],p=[],e=[],Y$=[],n=[],V4=[],u$=W0(J),y$=null,u0={officialServices:new Map,channelPlugins:new Map,companions:new Map},G4=u$?.projectedProviderIds??{},I4={},$4=Object.entries(Q.runtimes).sort(([F$],[e4])=>F$.localeCompare(e4)),i$=new Map,a0=!1,N1=[],jW=X.preparedHostedSourcedSkills??new Map,s0=X.resourcePreparationFailures?.sourcedSkills===void 0;if(X.resourcePreparationFailures?.sourcedSkills)V4.push(X.resourcePreparationFailures.sourcedSkills);if(X.resourcePreparationFailures?.agentPlugins){V4.push(X.resourcePreparationFailures.agentPlugins.error);for(let F$ of X.resourcePreparationFailures.agentPlugins.installationNames)B.add(F$)}let b9=X.hostedHermesSkillExactSourceDriver??u9$,u=X.hostedOpenClawSkillDriver??r9$;for(let[F$,e4]of $4){let N4=Ai$(F$,e4,z);if(i$.set(F$,N4),N4.error)n.push(N4.error)}if(n.length>0)return hB({load:$,paths:J,workspaceRoot:H,enabledRuntimes:Z,installErrors:n,projectedProviderIds:Object.fromEntries(Object.entries(G4).map(([F$,e4])=>[F$,[...e4]]))});try{y$=fk(J)}catch(F$){return n.push(F$ instanceof Error?F$.message:String(F$)),hB({load:$,paths:J,workspaceRoot:H,enabledRuntimes:Z,installErrors:n,projectedProviderIds:Object.fromEntries(Object.entries(G4).map(([e4,N4])=>[e4,[...N4]]))})}let P$=Zr$(Q,J,i$),Z$=P$?dQ(P$.snapshot):null,z4=_r$(Q,J),A6=null;try{if(P$)G.assertPlatformRoots(),RD(P$.runtimeUserOwnershipTargets);for(let[F$,e4]of $4){let N4=Vv(F$,e4,z);if(i$.set(F$,N4),N4.error)n.push(N4.error);if(F$==="openclaw"&&N4.enabled&&N4.commandPath)a0=r8$(N4,z)}if(n.length>0)throw Error(n.join("; "));if(z4){A6=dQ(z4),RD([...z4.metadataTargets,...z4.runtimeUserTargets]);let F$=i$.get("openclaw");if(!F$?.commandPath)throw Error("OpenClaw managed provider marker requires an installed runtime");eJ$({home:z,commandPath:F$.commandPath,appRoot:F$.appRoot})}}catch(F$){if(A6)try{H1(A6)}catch(N4){n.push(`OpenClaw managed provider marker rollback failed: ${N4 instanceof Error?N4.message:String(N4)}`)}if(Z$)try{H1(Z$)}catch(N4){n.push(`runtime installer rollback failed: ${N4 instanceof Error?N4.message:String(N4)}`)}let e4=F$ instanceof Error?F$.message:String(F$);if(!n.includes(e4))n.unshift(e4);return hB({load:$,paths:J,workspaceRoot:H,enabledRuntimes:Z,installErrors:n,projectedProviderIds:Object.fromEntries(Object.entries(G4).map(([N4,y1])=>[N4,[...y1]]))})}let R6,_5,t0;try{let F$=iQ("openclaw",z);R6=Q.runtimes.openclaw?.enabled===!0||Boolean(F$&&E0(F$))?u.resolveWorkspace({home:z,repairInvalidConfig:Q.projection?.sourceBundleVersion==="clawdi.hosted-runtime.bundle.v2"}):null,Fr$(Q,J,R6),z5$({manifest:Q,paths:J,openClawWorkspaceRoot:R6,secretValues:W,observations:i$,previousProjectedProviderIds:G4,hermesWhatsAppAuthDir:U,openClawOwnerBrowserBootstrapSupported:a0}),_5=G5$({manifest:Q,paths:J,workspaceRoot:H,generatedAt:I,secretValues:W,observations:i$,egressProfileBundlePath:R,egress:null}),c8$(_5),t0=Ar$({manifest:Q,paths:J,openClawWorkspaceRoot:R6,programs:_5,observations:i$})}catch(F$){if(A6)H1(A6);if(Z$)H1(Z$);throw F$}if(t0.systemdDriftErrors.length>0){if(A6)H1(A6);if(Z$)H1(Z$);return n.push(...t0.systemdDriftErrors),hB({load:$,paths:J,workspaceRoot:H,enabledRuntimes:Z,installErrors:n,projectedProviderIds:Object.fromEntries(Object.entries(G4).map(([F$,e4])=>[F$,[...e4]]))})}let d_=b4(H),r;try{let F$=t0.snapshot;if(P$)F$=U5$(F$,P$.snapshot);if(z4)F$=U5$(F$,z4);r=dQ(F$);for(let e4 of[Z$,A6]){if(!e4)continue;for(let[N4,y1]of e4.entries)if(!r.entries.has(N4))r.entries.set(N4,y1)}}catch(F$){if(A6)H1(A6);if(Z$)H1(Z$);throw F$}let d$=!1,S0=!1,e0,u4,DJ=!1,K8,H7,n_,NW=!0,FW={files:[],systemUnits:[],userUnits:[]};try{G.assertPlatformRoots(),RD(t0.runtimeUserOwnershipTargets);let F$=Y9$(Q,J,y$?.companions.filebrowser,X.fileBrowserInstallOptions);if(F$)u0.companions.set(F$.receiptKey,F$.receiptTarget);let e4=i$.get("openclaw");if(e4)try{let x=di$({manifest:Q,secretValues:W,observation:e4,home:z});if(i$.set("openclaw",x),x!==e4)a0=r8$(x,z)}catch(x){n.push(`runtime openclaw credential capability check failed: ${x instanceof Error?x.message:String(x)}`)}if(n.length>0)throw Error(n.join("; "));let N4=i$.get("openclaw");if(N4&&OG(Q)){N1=ii$(N4,z);let x=N1.filter((E$)=>!r.entries.has(E$));if(x.length>0){let E$=dQ({rootTargets:[],trustedRootDirectories:[],runtimeUserTargets:x,runtimeUserTrustedRoots:[J.userHome,J.clawdiHome],runtimeUserSymlinkTargets:[],metadataTargets:[]});for(let[A$,m4]of E$.entries)if(!r.entries.has(A$))r.entries.set(A$,m4);RD(x)}}if(R6&&q0(u.resolveWorkspace({home:z}))!==q0(R6))throw Error("OpenClaw official agent workspace changed during runtime reconciliation");if(X.preparedHostedAgentPlugins){let x=Z9$(z),E$;try{E$=sp$({prepared:X.preparedHostedAgentPlugins,home:z,commands:x,...X.hostedAgentPluginCommandRunner?{runner:X.hostedAgentPluginCommandRunner}:{}})}catch(A$){for(let m4 of X.preparedHostedAgentPlugins.desired.keys())B.add(m4);V4.push(`runtime Agent Plugin projection planning failed: ${A$ instanceof Error?A$.message:String(A$)}`),E$={transaction:null}}if(V=E$.transaction,V?.hasMutations&&!X.systemdApply)throw Error("Agent Plugin mutations require systemd activation and readiness")}G.assertPlatformRoots();let y1=null;if(Iv(Q)||Q.projection?.sourceSchemaVersion==="clawdi.hosted-runtime.manifest.v1")try{y1=Jo$(J)}catch(x){n.push(`runtime codex setup failed: ${x instanceof Error?x.message:String(x)}`)}for(let[x]of $4){let E$=i$.get(x);if(!E$)throw Error(`runtime ${x} install observation is missing`);try{Do$(x,E$,Q,z,J.userHome,y$,u0)}catch(A$){n.push(`runtime ${x} channel plugin install failed: ${A$ instanceof Error?A$.message:String(A$)}`)}}let h1=n5$(Q);try{let x=h1?i$.get(h1):void 0;if(h1&&!x?.appRoot)throw Error(`runtime ${h1} artifact root is unavailable`);let E$=RJ$({desiredRuntime:h1,home:z,...x?.appRoot?{appRoot:x.appRoot}:{},paths:J});if(E$.status==="rollback-refused")throw Error(E$.errors.join(", "))}catch(x){let E$=h1?`runtime ${h1} managed WhatsApp compatibility`:"runtime managed WhatsApp compatibility cleanup";n.push(`${E$} failed: ${x instanceof Error?x.message:String(x)}`)}if(n.length>0)throw Error(n.join("; "));G.assertPlatformRoots(),_G(J.userHome),qi$(J.clawdiHome,G.identity),Y0(()=>{pQ(H,{recursive:!0}),v4(H)});for(let x of[J.installInventory,J.projectionRoot,d,$$])sz(J,x,{mode:493});sz(J,J.managedSecretRoot),Ov(J.managedSecretRoot),sz(J,J.egressRoot,{mode:457}),W5(J.egressRoot,457),Ki$(J.egressCaDir),sz(J,g6(J.egressSystemCaFile),{mode:457}),W5(g6(J.egressSystemCaFile),457),FG(J.egressScratchRoot,J.userHome);let OW=null;YJ(J.managedConfig,{schemaVersion:"clawdi.hostedManagedConfig.v1",generatedAt:I,deploymentId:Q.deploymentId,environmentId:Q.environmentId,instanceId:Q.instanceId,generation:Q.generation,locale:Q.locale??null,controlPlane:Q.controlPlane,egressEngine:Q.egressEngine??null,auth:{source:"runtime-instance-data",token:"<redacted>"},workspaceRoot:H},J),YJ(J.syncState,{schemaVersion:"clawdi.runtimeSyncState.v1",generatedAt:I,deploymentId:Q.deploymentId,environmentId:Q.environmentId,instanceId:Q.instanceId,generation:Q.generation,locale:Q.locale??null,runtimes:Object.fromEntries(Object.entries(Q.runtimes).map(([x,E$])=>[x,{enabled:E$.enabled,updateChannel:E$.updateChannel??null,workspaceRoot:H}]))},J),YJ(J.instanceData,{schemaVersion:"clawdi.runtimeInstanceData.v1",generatedAt:I,deploymentId:Q.deploymentId,environmentId:Q.environmentId,instanceId:Q.instanceId,generation:Q.generation,locale:Q.locale??null,controlPlane:Q.controlPlane,workspaceRoot:H},J),YJ(J.sensitiveInstanceData,{schemaVersion:"clawdi.runtimeSensitiveInstanceData.v1",generatedAt:I,tokenSource:w0(W??{},Sx)?"CLAWDI_AUTH_TOKEN":$.source,token:"<redacted>"},J);let C4=qT(P)?eo$(P,J):ao$(J),M0=so$(C4?H8$(Q.egressEngine,J,X.egressEngineEnsureOptions):null,J);to$(Q,C4,M0);let xh=C4?$r$(J):Jr$(J),p_=qr$(J,W),kh=p_?EO(J):null;if(kh)e0=Kr$(kh),u4=ND(Q),S0=e0!==u$?.daemonAuthTokenRevision||u4!==u$?.daemonProgramRevision;try{Y0(()=>Xi$(Q,W,z))}catch(x){n.push(`runtime channel credential materialization failed: ${x instanceof Error?x.message:String(x)}`)}let Hz=Ti$(Q,W,J),vh=Hz.path,gh=process.env.CLAWDI_RUNTIME_USER?.trim()||"clawdi",yh=Z8$({paths:J,profileBundlePath:C4,secretFilePath:vh,engine:M0,addon:xh,runtimeUser:gh}),jw=yh.egressProgram,DW=yh.identity,GH$=DW?.runtimeUid??0,zH$=DW?.runtimeGid??0,UH$=DW?.egressUid??0,HH$=DW?.egressGid??0,VH$=Qr$({program:jw,paths:J,runtimeUser:gh,runtimeUid:GH$,runtimeGid:zH$,egressUid:UH$,egressGid:HH$});zi$(Q,$.secretValues,J);let BH$=Hr$(Q,J),i_=new Set;Y$.push(...G5$({manifest:Q,paths:J,workspaceRoot:H,generatedAt:I,secretValues:W,observations:i$,egressProfileBundlePath:C4,egress:jw}));let wH$=jw!==null&&DW!==null&&Y$.length>0,ZW=u$?.egressSidecarSecretRevision;if(wH$){if(K8=Hz.material.revision,DJ=Hz.changed||ZW===void 0||ZW!==K8,ZW===void 0)H7=p8$(J,Y)??void 0,NW=H7!==void 0;else if(DJ&&Hz.previousRevision!==ZW)if(K8===ZW)H7=Hz.material;else n_=ZW}let qH$=h8$(J);z5$({manifest:Q,paths:J,openClawWorkspaceRoot:R6,secretValues:W,observations:i$,previousProjectedProviderIds:G4,hermesWhatsAppAuthDir:U,openClawOwnerBrowserBootstrapSupported:a0});let o_={};for(let[x]of $4){let E$=i$.get(x);if(!E$)throw Error(`runtime ${x} install observation is missing`);o_[x]=ei$(x,E$,Q,z,G4[x]??[])}try{let x=Y0(()=>$o$(Q,z,y1));o_.codex=x.revision,I4.codex=x.providerIds}catch(x){n.push(`runtime codex provider projection failed: ${x instanceof Error?x.message:String(x)}`)}if(n.length>0)throw Error(n.join("; "));if(s0)try{let x=Ir$(Q,z,R6);q=dQ({rootTargets:[mm()],trustedRootDirectories:[J.managedResourceRoot],runtimeUserTargets:x,runtimeUserTrustedRoots:[J.userHome,J.clawdiHome],runtimeUserSymlinkTargets:[],metadataTargets:DG(x,[J.userHome,J.clawdiHome])}),ho$({manifest:Q,observations:i$,home:z,openClawWorkspaceRoot:R6,preparedSourcedSkills:jW,hermesDriver:b9,openClawDriver:u})}catch(x){let E$=x instanceof Error?x.message:String(x);try{if(q)H1(q)}catch(A$){throw Error(`runtime Skill projection failed and could not be rolled back: ${E$}; ${A$ instanceof Error?A$.message:String(A$)}`)}q=null,V4.push(E$)}try{uo$(Q,J,i$,H)}catch(x){n.push(`runtime MCP projection failed: ${x instanceof Error?x.message:String(x)}`)}if(n.length>0)throw Error(n.join("; "));for(let x of["hermes","openclaw"]){if(Object.hasOwn(Q.runtimes,x))continue;try{t8$({runtime:x,manifest:Q,secretValues:W,paths:J,home:z,workspaceRoot:H})}catch(E$){n.push(`stale ${x} OAuth credential reconciliation failed: ${E$ instanceof Error?E$.message:String(E$)}`)}}if(n.length>0)throw Error(n.join("; "));for(let[x,E$]of $4){let A$=i$.get(x);if(!A$)throw Error(`runtime ${x} install observation is missing`);let m4=v(J.installInventory,`${x}.json`);YJ(m4,{schemaVersion:"clawdi.runtimeInstallInventory.v1",generatedAt:I,runtime:x,enabled:E$.enabled,updateChannel:E$.updateChannel??null,simulation:!1,status:A$.status,executionUser:A$.executionUser,install:A$.install,command:ji$(x,E$.install),commandPath:A$.commandPath,appRoot:A$.appRoot,installerUrl:A$.installerUrl,executedInstallerUrl:A$.executedInstallerUrl,installStartedAt:A$.installStartedAt??null,installFinishedAt:A$.installFinishedAt??null,installDurationMs:A$.installDurationMs??null,resultExitCode:A$.exitCode,stdoutTail:A$.stdoutTail,stderrTail:A$.stderrTail,error:A$.error},J),X$.push(m4);let ch=v(J.projectionRoot,`${x}.json`);if(YJ(ch,d8$(x,Q),J),k.push(ch),x==="hermes"||x==="openclaw")try{t8$({runtime:x,observation:A$,manifest:Q,secretValues:W,paths:J,home:z,workspaceRoot:H})}catch(d4){n.push(`runtime ${x} OAuth credential reconciliation failed: ${d4 instanceof Error?d4.message:String(d4)}`)}try{let d4=Y0(()=>Pi$(x,A$,Q,z,R6,H));if(d4)p.push(d4)}catch(d4){n.push(`runtime ${x} config projection failed: ${d4 instanceof Error?d4.message:String(d4)}`)}try{let d4=ti$(x,A$,Q,W,z,H,G4[x]??[],a0,N1);I4[x]=d4.providerIds}catch(d4){n.push(`runtime ${x} provider projection failed: ${d4 instanceof Error?d4.message:String(d4)}`)}try{if(Oo$(x,A$,Q,z,H,U))M.add(x)}catch(d4){n.push(`runtime ${x} channel projection failed: ${d4 instanceof Error?d4.message:String(d4)}`)}if(n.length>0)throw Error(n.join("; "));let a_=l5$({manifest:Q,paths:J,name:x,runtime:E$,observation:A$,workspaceRoot:H,generatedAt:I,secretValues:W,egressProfileBundlePath:C4}),LH$=MT(a_.runtime,J);e.push(LH$),i_.add(aj(a_.runtime.runtime));for(let d4 of a_.services){let jH$=MT(d4,J);e.push(jH$),i_.add(aj(d4.runtime,d4.service))}let lh=v($$,`${x}.enabled`);if(E$.enabled)z8(J,lh,`${I}
|
|
970
|
+
`,{mode:420})}function qr$($,J){let X=g6$($,J??{});if(!X)return null;return Ov(g6(X)),X}function Kr$($){return N0({schemaVersion:"clawdi.daemonAuthTokenRevision.v1",token:$})}function Lr$($,J,X,Q,W,Y){let G=$.runtimes[J],z=G?xB($,J):{placeholderEnv:{},secretEnv:{}},U=G?hD(J,G.run,z.placeholderEnv):void 0,H=G?[...Object.values(uD(J,U,z.secretEnv)),...pB($).filter((q)=>q.target===J||J==="openclaw"&&q.target==="legacy").map((q)=>q.credsJsonSecretRef)]:[],V=oB($),B=J==="openclaw"||J==="hermes",w=null;if(V&&J==="openclaw")w=Rv(V);else if(V&&J==="hermes"&&G?.enabled)w=LD(V,W);return w8$({renderedProjection:{channels:w,gateway:J==="openclaw"?Av($,X,Y):null,locale:$.locale&&B?lB($.locale):$.locale?.timezone??null,mcp:B?C5$($):null,provider:Q},desiredRuntime:G,secretValues:vD(X,H)})}function jr$($,J){return $.workspaceRoot??J.workspaceRoot}function Nr$($){return $.secretValues&&Object.keys($.secretValues).length>0?$.secretValues:void 0}function Fr$($,J,X){let Q=V9($,J);for(let[W,Y]of Object.entries($.runtimes)){let G=R1.parse(W),z=Y.enabled?xB($,W,{validateOverlap:!0}):{placeholderEnv:{},secretEnv:{}},{placeholderEnv:U,secretEnv:H}=z,V=hD(G,Y.run,U);if(Y.enabled)uD(W,V,H);for(let[w,q]of Object.entries(Y.services??{})){let L=dJ.parse(w),N=_v($,G,L,q,U);if(Y.enabled)Mv(W,L,N,H)}if(!Y.enabled||!$.locale)continue;let B=lB($.locale);if(G==="openclaw"){if(!X)throw Error("OpenClaw official agent workspace is unavailable");dB(v(X,"SOUL.md"),B)}else if(G==="hermes")dB(v(Q,".hermes","SOUL.md"),B)}}function G5$($){let J=[];for(let[Q,W]of Object.entries($.manifest.runtimes).sort(([Y],[G])=>Y.localeCompare(G))){let Y=$.observations.get(Q);if(!Y)throw Error(`runtime ${Q} install observation is missing`);let G=l5$({manifest:$.manifest,paths:$.paths,name:Q,runtime:W,observation:Y,workspaceRoot:$.workspaceRoot,generatedAt:$.generatedAt,secretValues:$.secretValues,egressProfileBundlePath:$.egressProfileBundlePath});if(W.enabled&&(HX(Q)||Boolean(W.run?.command?.trim()))){let z=Xv({config:G.runtime,paths:$.paths,secretValues:$.secretValues,egress:$.egress});if(z)J.push(z)}for(let z of G.services){let U=Xv({config:z,paths:$.paths,secretValues:$.secretValues,egress:$.egress});if(U)J.push(U)}}let X=G9$($.manifest,$.paths);if(X)J.push(X);return J}function Or$($,J){let X=$.hermesDashboardAuth;if(!X)return J;if(!X.activation.enabled)throw Error("Hermes password authentication is disabled");return{...J??{},prependPath:J?.prependPath??[],env:J?.env??{},secretEnv:{...J?.secretEnv??{},HERMES_DASHBOARD_BASIC_AUTH_PASSWORD:X.passwordSecretRef,HERMES_DASHBOARD_BASIC_AUTH_SECRET:X.sessionSecretRef}}}function l5$($){let J=R1.parse($.name),X=$.runtime.enabled?xB($.manifest,$.name,{validateOverlap:!0}):{placeholderEnv:{},secretEnv:{}},{placeholderEnv:Q,secretEnv:W}=X,Y=hD(J,$.runtime.run,Q),G=$.runtime.enabled?uD($.name,Y,W):{},z=null,U=_T({runtime:J,enabled:$.runtime.enabled,generatedAt:$.generatedAt,generation:$.manifest.generation,instanceId:$.manifest.instanceId,commandPath:$.observation.commandPath,appRoot:$.observation.appRoot,workspaceRoot:$.workspaceRoot,egressProfileBundlePath:$.egressProfileBundlePath,settings:Y,secretFilePath:null,secretEnv:G}),H=Object.entries($.runtime.services??{}).sort(([V],[B])=>V.localeCompare(B)).map(([V,B])=>{let w=dJ.parse(V),q=_v($.manifest,J,w,B,Q);return _T({runtime:J,service:w,enabled:$.runtime.enabled,generatedAt:$.generatedAt,generation:$.manifest.generation,instanceId:$.manifest.instanceId,commandPath:$.observation.commandPath,appRoot:$.observation.appRoot,workspaceRoot:$.workspaceRoot,settings:q,secretFilePath:null,secretEnv:$.runtime.enabled?Mv($.name,w,q,W):{}})});return{runtime:U,services:H,secretEnv:G,secretFilePath:null}}function hB($){let J=v($.paths.instanceRoot,$.load.manifest.instanceId);return{manifest:$.load.manifest,source:$.load.source,sourcePath:$.load.sourcePath,offline:$.load.offline,mode:$.load.offline?"degraded-offline":"normal",enabledRuntimes:$.enabledRuntimes,installErrors:$.installErrors,resourceProjectionErrors:[],projectedProviderIds:$.projectedProviderIds,agentPluginFailedNames:$.agentPluginFailedNames??[],outputs:{processManager:"systemd",workspaceRoot:$.workspaceRoot,managedConfig:$.paths.managedConfig,syncState:$.paths.syncState,instanceData:$.paths.instanceData,sensitiveInstanceData:$.paths.sensitiveInstanceData,manifestLastGood:null,appliedState:null,installInventory:[],projections:[],managedLocaleFiles:[],runConfigs:[],systemdSystemUnitRoot:$.paths.systemdSystemRoot,systemdSystemUnits:[],systemdUserUnitRoot:$.paths.systemdUserRoot,systemdUserUnits:[],egressProfileBundle:null,egressSecretFile:null,egressEngine:null,egressTransparentEnv:null,egressAddon:null,liveSyncEnvironments:[],daemonAuthTokenFile:null,instanceSemaphores:[],bootFinished:v(J,"boot-finished")}}}function z5$($){let{manifest:J,paths:X,openClawWorkspaceRoot:Q,secretValues:W,observations:Y,previousProjectedProviderIds:G,hermesWhatsAppAuthDir:z,openClawOwnerBrowserBootstrapSupported:U}=$,H=V9(J,X),V=J.locale?lB(J.locale):null;if(V)for(let w of Object.keys(J.runtimes)){if(J.runtimes[w]?.enabled!==!0)continue;if(w==="openclaw"){if(!Q)throw Error("OpenClaw official agent workspace is unavailable");dB(v(Q,"SOUL.md"),V)}if(w==="hermes")dB(v(H,".hermes","SOUL.md"),V)}let B=Iv(J);if(B)A5$(B);for(let[w,q]of Object.entries(J.runtimes).sort(([L],[N])=>L.localeCompare(N))){if(!Y.get(w))throw Error(`runtime ${w} install observation is missing`);let N=R1.parse(w),F=q.enabled?xB(J,w,{validateOverlap:!0}):{placeholderEnv:{},secretEnv:{}},{placeholderEnv:O,secretEnv:_}=F,M=hD(N,q.run,O),b=q.enabled?uD(w,M,_):{};vD(W,Object.values(b));for(let[R,d]of Object.entries(q.services??{})){let $$=dJ.parse(R),Q$=_v(J,N,$$,d,O);Mv(w,$$,Q$,_)}let Z=mD(fB(J,w));bv(w,J,Z);let I=J.runtimes[w]?.providerMode==="configured"&&!Z;if(w==="openclaw"){if(Z)SD(Z,G.openclaw??[]);else if(!I)SD(null,G.openclaw??[]);JSON.stringify(Av(J,W,U))}if(w==="hermes"){if(Z){let d=mO("hermes",Z.catalog,Z.primaryModel,{freezeManagedModelCatalog:!0}).files.find(($$)=>$$.path.endsWith(".hermes.yaml"));if(!d)throw Error("Hermes projection did not include a config merge YAML file.");if(!j$(u8(d.content)))throw Error("Hermes projection patch must be a YAML object.")}}let P=oB(J);if(P&&w==="openclaw")JSON.stringify(Rv(P));if(P&&w==="hermes"&&q.enabled)LD(P,z)}lo$(J,X,Y),Qi$(J,W,H)}function d5$($,J,X){let Q=new Set,W=X.get("openclaw");if($.runtimes.openclaw?.enabled&&$.runtimes.openclaw.install&&W?.status!=="present")Q.add(v(J,".local","bin","openclaw")),Q.add(v(J,".local","tools"));let Y=X.get("hermes");if($.runtimes.hermes?.enabled&&$.runtimes.hermes.install&&Y?.status!=="present")for(let G of[v(J,".hermes","hermes-agent"),v(J,".hermes","bin"),v(J,".hermes","node"),v(J,".hermes","uv"),v(J,".hermes",".env"),v(J,".hermes",".no-bundled-skills"),v(J,".hermes","config.yaml"),v(J,".hermes","SOUL.md"),v(J,".hermes","skills"),v(J,".local","bin","hermes"),v(J,".local","bin","hermes-agent"),v(J,".local","bin","hermes-acp"),v(J,".local","bin","node"),v(J,".local","bin","npm"),v(J,".local","bin","npx")])Q.add(G);return[...Q]}function Zr$($,J,X){if(!Object.entries($.runtimes).some(([H,V])=>{if(!V.enabled||!V.install)return!1;return X.get(H)?.status!=="present"}))return null;let W=V9($,J),Y=d5$($,W,X).sort();if(Y.length===0)return null;let G=[J.userHome,J.clawdiHome],z=[...new Set([J.userHome,J.clawdiHome,...DG(Y,G),...$.runtimes.hermes?.enabled&&$.runtimes.hermes.install&&X.get("hermes")?.status!=="present"?Dr$.map((H)=>v(W,".hermes",H)):[]])].sort(),U=Object.keys($.runtimes).flatMap((H)=>{let V=iQ(H,W);return V&&Y.includes(V)?[V]:[]});return{snapshot:{rootTargets:[],trustedRootDirectories:[],runtimeUserTargets:Y,runtimeUserTrustedRoots:G,runtimeUserSymlinkTargets:U,metadataTargets:z},runtimeUserOwnershipTargets:[...new Set([...z,...Y])].sort((H,V)=>H.length-V.length||H.localeCompare(V))}}function U5$($,J){let X=J.runtimeUserTargets.map((Y)=>q0(Y)),Q=(Y)=>{let G=q0(Y);return X.some((z)=>{let U=kD(z,G);return U===""||!U.startsWith("..")&&!nB(U)})},W=new Set(J.metadataTargets.map((Y)=>q0(Y)));return{...$,runtimeUserTargets:$.runtimeUserTargets.filter((Y)=>!Q(Y)),runtimeUserSymlinkTargets:$.runtimeUserSymlinkTargets.filter((Y)=>!Q(Y)),metadataTargets:$.metadataTargets.filter((Y)=>!Q(Y)&&!W.has(q0(Y)))}}function _r$($,J){if(!OG($))return null;let X=qG(V9($,J)),Q=[J.userHome,J.clawdiHome];return{rootTargets:[],trustedRootDirectories:[],runtimeUserTargets:[X],runtimeUserTrustedRoots:Q,runtimeUserSymlinkTargets:[],metadataTargets:DG([X],Q)}}function Mr$($,J){let X=new Set(Dv($)?pB($).map((Y)=>Y.authDir):[]),Q=cB(J,"openclaw");if(Q&&b4(Q))for(let Y of lX(Q)){let G=v(Q,Y);if(NG(G))X.add(G)}let W=cB(J,"hermes");if(W&&NG(W)?.target==="hermes")X.add(W);return[...X]}function n5$($){let J=new Set;for(let X of pB($))J.add(X.target==="hermes"?"hermes":"openclaw");if(J.size>1)throw Error("managed WhatsApp projection must target exactly one native runtime");return J.values().next().value??null}function br$($,J,X,Q){let W=V9($,J),Y=d5$($,W,Q),G=n5$($),z=oB($),U=z?Object.keys(z).filter((B)=>Boolean(u5$[B])).map((B)=>v(W,".openclaw","extensions",B)):[],H=new Set([sk(W),v(W,".hermes","config.yaml"),v(W,".hermes","SOUL.md"),jv(W),v(g6(jv(W)),"auth.lock"),D5$(W),v(I5$(W),Kv),P5$(W),...Y,...Mr$($,W),...U]);if(OG($))for(let B of aJ$(W))H.add(B);if(X)H.add(v(X,"SOUL.md"));for(let B of Y5){if($.runtimes[B]?.enabled!==!0)continue;let w=iQ(B,W);if(w&&!Y.some((q)=>{let L=kD(q0(q),q0(w));return L===""||!L.startsWith("..")&&!nB(L)}))H.add(w)}let V=IJ$({desiredRuntime:G,home:W,paths:J});for(let B of V){let w=yD(B,W);if(!w)continue;for(let q of AJ$({runtime:B,home:W,appRoot:w})){if([...Y,...U].some((L)=>q===L||q.startsWith(`${L}/`)))continue;H.add(q)}}for(let B of h5$)H.add(v(J.localEnvironments,`${B}.json`));return[...H].sort()}function Ir$($,J,X){let Q=new Set;for(let z of Y5)for(let U of SJ()){let H=aB(z,U,J,X??void 0);if(H)Q.add(H)}let W=v(J,".hermes","skills"),Y=X?v(X,"skills"):null,G=!1;for(let[z,U]of Object.entries($.projection?.skills?.entries??{})){if(!("source"in U))continue;if($.runtimes.hermes?.enabled===!0)G=!0,Q.add(v(W,z));if($.runtimes.openclaw?.enabled===!0&&Y)Q.add(v(Y,z))}for(let z of lW("hosted-manifest")){if(g6(z.targetDir)===W&&!SJ().includes(z.id))G=!0,Q.add(z.targetDir);if(Y&&g6(z.targetDir)===Y&&!SJ().includes(z.id))Q.add(z.targetDir)}if(G)Q.add(v(W,".hub"));return[...Q].sort()}function DG($,J){let X=J.map((W)=>q0(W)),Q=new Set;for(let W of $){let Y=q0(W),G=X.find((U)=>{let H=kD(U,Y);return H===""||!H.startsWith("..")&&!nB(H)});if(!G)throw Error(`runtime mutation target is outside managed user roots: ${Y}`);if(Y===G)continue;let z=g6(Y);while(z!==G)Q.add(z),z=g6(z)}return[...Q]}function Ar$($){let J=new Set(UJ$($.manifest,$.paths)),X=Q9$($.manifest,$.paths);for(let q of X.rootTargets)J.add(q);J.add(UG($.paths));let Q=new Set,W=$.manifest.egressEngine;if(W?.type==="mitmproxy"){let q=v($.paths.egressEngineMaintainedRoot,W.version,W.sha256.toLowerCase());if(!E0(v(q,"mitmdump")))J.add(q);Q.add(g6($.paths.egressEngineMaintainedRoot)),Q.add($.paths.egressEngineMaintainedRoot),Q.add(v($.paths.egressEngineMaintainedRoot,W.version))}let Y=g8$($.programs,$.paths);for(let q of Y.environmentTargets)J.add(q);let G=[...new Set([...br$($.manifest,$.paths,$.openClawWorkspaceRoot,$.observations),...Y.targets])].sort(),z=[...J].sort(),U=V9($.manifest,$.paths),H=Y5.flatMap((q)=>{if($.manifest.runtimes[q]?.enabled!==!0)return[];let L=iQ(q,U);return L?[L]:[]}),V=[$.paths.userHome,$.paths.clawdiHome],B=[...new Set([...Y.metadataTargets,$.paths.userHome,$.paths.clawdiHome,...DG(G,V)])].sort(),w=[...new Set([...G,...B,...H])].sort((q,L)=>q.length-L.length||q.localeCompare(L));return{snapshot:{rootTargets:z,trustedRootDirectories:[...HJ$($.manifest,$.paths),...X.rootTrustedRoots],runtimeUserTargets:G,runtimeUserTrustedRoots:V,runtimeUserSymlinkTargets:[...new Set([...Y.symlinkTargets,...H.filter((q)=>G.includes(q))])].sort(),metadataTargets:[...new Set([...Q,...Y.metadataTargets,$.paths.configurationRoot,$.paths.serviceStateRoot,$.paths.cacheRoot,$.paths.runRoot,$.paths.systemdSystemRoot,...DG(z,[$.paths.configurationRoot,$.paths.serviceStateRoot,$.paths.cacheRoot,$.paths.runRoot,$.paths.systemdSystemRoot]),...B])].sort()},runtimeUserOwnershipTargets:w,staleOfficialUnits:Y.staleOfficialUnits,systemdUserUnits:Y.unitNames,systemdDriftErrors:Y.driftErrors}}function RD($){if(!O6())return;let J=process.env.CLAWDI_RUNTIME_USER?.trim();if(!J||J==="root"||J==="0")return;let X=X9(J),Q=l8(J);if(X===0||Q===0)throw Error(`runtime user ${J} resolved to a root filesystem identity`);for(let W of $){let Y;try{Y=x1(W)}catch(G){if(G.code==="ENOENT")continue;throw G}if(Y.uid===X&&Y.gid===Q)continue;if(Y.isSymbolicLink())dp$(W,X,Q);else ZG(W,X,Q)}}function p5$($,J,X={}){let{manifest:Q}=$;if((cH(Q)||X.preparedHostedAgentPlugins)&&Q.projection?.sourceBundleVersion!=="clawdi.hosted-runtime.bundle.v2")throw Error(tj);if(cH(Q)&&!X.preparedHostedAgentPlugins&&!X.resourcePreparationFailures?.agentPlugins)throw Error(nJ);let W=Nr$($),Y=$.applyContext;if(!Y)throw Error("runtime manifest convergence requires an explicit apply context");let G=jB(J,Y,X.hostedRuntimeContract),z=V9(Q,J);wi$(Q,z);let U=cJ$(Q,z);if(G1$(J),Vr$(J),Q.companions?.filebrowser){if(Q.projection?.sourceBundleVersion!=="clawdi.hosted-runtime.bundle.v2")throw Error("Files companion requires a hosted v2 bundle");if(!X.systemdApply)throw Error("Files companion requires systemd apply and readiness hooks")}let H=jr$(Q,J),V=null,B=new Set,w=null,q=null,L=!1,N=!1,F=!1,O=[],_=[],M=new Set,b=[],Z=Object.entries(Q.runtimes).filter(([,F$])=>F$.enabled).map(([F$])=>F$).sort(),I=new Date().toISOString(),P=qi({generatedAt:I,generation:Q.generation,instanceId:Q.instanceId,profiles:Q.egressProfiles}),R=qT(P)?J.egressProfileBundle:null,d=v(J.instanceRoot,Q.instanceId),$$=v(d,"sem"),Q$=[],X$=[],k=[],p=[],e=[],Y$=[],n=[],V4=[],u$=W0(J),y$=null,u0={officialServices:new Map,channelPlugins:new Map,companions:new Map},G4=u$?.projectedProviderIds??{},I4={},$4=Object.entries(Q.runtimes).sort(([F$],[e4])=>F$.localeCompare(e4)),i$=new Map,a0=!1,N1=[],jW=X.preparedHostedSourcedSkills??new Map,s0=X.resourcePreparationFailures?.sourcedSkills===void 0;if(X.resourcePreparationFailures?.sourcedSkills)V4.push(X.resourcePreparationFailures.sourcedSkills);if(X.resourcePreparationFailures?.agentPlugins){V4.push(X.resourcePreparationFailures.agentPlugins.error);for(let F$ of X.resourcePreparationFailures.agentPlugins.installationNames)B.add(F$)}let b9=X.hostedHermesSkillExactSourceDriver??u9$,u=X.hostedOpenClawSkillDriver??r9$;for(let[F$,e4]of $4){let N4=Ai$(F$,e4,z);if(i$.set(F$,N4),N4.error)n.push(N4.error)}if(n.length>0)return hB({load:$,paths:J,workspaceRoot:H,enabledRuntimes:Z,installErrors:n,projectedProviderIds:Object.fromEntries(Object.entries(G4).map(([F$,e4])=>[F$,[...e4]]))});try{y$=fk(J)}catch(F$){return n.push(F$ instanceof Error?F$.message:String(F$)),hB({load:$,paths:J,workspaceRoot:H,enabledRuntimes:Z,installErrors:n,projectedProviderIds:Object.fromEntries(Object.entries(G4).map(([e4,N4])=>[e4,[...N4]]))})}let P$=Zr$(Q,J,i$),Z$=P$?dQ(P$.snapshot):null,z4=_r$(Q,J),A6=null;try{if(P$)G.assertPlatformRoots(),RD(P$.runtimeUserOwnershipTargets);for(let[F$,e4]of $4){let N4=Vv(F$,e4,z);if(i$.set(F$,N4),N4.error)n.push(N4.error);if(F$==="openclaw"&&N4.enabled&&N4.commandPath)a0=r8$(N4,z)}if(n.length>0)throw Error(n.join("; "));if(z4){A6=dQ(z4),RD([...z4.metadataTargets,...z4.runtimeUserTargets]);let F$=i$.get("openclaw");if(!F$?.commandPath)throw Error("OpenClaw managed provider marker requires an installed runtime");eJ$({home:z,commandPath:F$.commandPath,appRoot:F$.appRoot})}}catch(F$){if(A6)try{H1(A6)}catch(N4){n.push(`OpenClaw managed provider marker rollback failed: ${N4 instanceof Error?N4.message:String(N4)}`)}if(Z$)try{H1(Z$)}catch(N4){n.push(`runtime installer rollback failed: ${N4 instanceof Error?N4.message:String(N4)}`)}let e4=F$ instanceof Error?F$.message:String(F$);if(!n.includes(e4))n.unshift(e4);return hB({load:$,paths:J,workspaceRoot:H,enabledRuntimes:Z,installErrors:n,projectedProviderIds:Object.fromEntries(Object.entries(G4).map(([N4,y1])=>[N4,[...y1]]))})}let R6,_5,t0;try{let F$=iQ("openclaw",z);R6=Q.runtimes.openclaw?.enabled===!0||Boolean(F$&&E0(F$))?u.resolveWorkspace({home:z,repairInvalidConfig:Q.projection?.sourceBundleVersion==="clawdi.hosted-runtime.bundle.v2"}):null,Fr$(Q,J,R6),z5$({manifest:Q,paths:J,openClawWorkspaceRoot:R6,secretValues:W,observations:i$,previousProjectedProviderIds:G4,hermesWhatsAppAuthDir:U,openClawOwnerBrowserBootstrapSupported:a0}),_5=G5$({manifest:Q,paths:J,workspaceRoot:H,generatedAt:I,secretValues:W,observations:i$,egressProfileBundlePath:R,egress:null}),c8$(_5),t0=Ar$({manifest:Q,paths:J,openClawWorkspaceRoot:R6,programs:_5,observations:i$})}catch(F$){if(A6)H1(A6);if(Z$)H1(Z$);throw F$}if(t0.systemdDriftErrors.length>0){if(A6)H1(A6);if(Z$)H1(Z$);return n.push(...t0.systemdDriftErrors),hB({load:$,paths:J,workspaceRoot:H,enabledRuntimes:Z,installErrors:n,projectedProviderIds:Object.fromEntries(Object.entries(G4).map(([F$,e4])=>[F$,[...e4]]))})}let d_=b4(H),r;try{let F$=t0.snapshot;if(P$)F$=U5$(F$,P$.snapshot);if(z4)F$=U5$(F$,z4);r=dQ(F$);for(let e4 of[Z$,A6]){if(!e4)continue;for(let[N4,y1]of e4.entries)if(!r.entries.has(N4))r.entries.set(N4,y1)}}catch(F$){if(A6)H1(A6);if(Z$)H1(Z$);throw F$}let d$=!1,S0=!1,e0,u4,DJ=!1,K8,H7,n_,NW=!0,FW={files:[],systemUnits:[],userUnits:[]};try{G.assertPlatformRoots(),RD(t0.runtimeUserOwnershipTargets);let F$=Y9$(Q,J,y$?.companions.filebrowser,X.fileBrowserInstallOptions);if(F$)u0.companions.set(F$.receiptKey,F$.receiptTarget);let e4=i$.get("openclaw");if(e4)try{let x=di$({manifest:Q,secretValues:W,observation:e4,home:z});if(i$.set("openclaw",x),x!==e4)a0=r8$(x,z)}catch(x){n.push(`runtime openclaw credential capability check failed: ${x instanceof Error?x.message:String(x)}`)}if(n.length>0)throw Error(n.join("; "));let N4=i$.get("openclaw");if(N4&&OG(Q)){N1=ii$(N4,z);let x=N1.filter((E$)=>!r.entries.has(E$));if(x.length>0){let E$=dQ({rootTargets:[],trustedRootDirectories:[],runtimeUserTargets:x,runtimeUserTrustedRoots:[J.userHome,J.clawdiHome],runtimeUserSymlinkTargets:[],metadataTargets:[]});for(let[A$,m4]of E$.entries)if(!r.entries.has(A$))r.entries.set(A$,m4);RD(x)}}if(R6&&q0(u.resolveWorkspace({home:z}))!==q0(R6))throw Error("OpenClaw official agent workspace changed during runtime reconciliation");if(X.preparedHostedAgentPlugins){let x=Z9$(z),E$;try{E$=sp$({prepared:X.preparedHostedAgentPlugins,home:z,commands:x,...X.hostedAgentPluginCommandRunner?{runner:X.hostedAgentPluginCommandRunner}:{}})}catch(A$){for(let m4 of X.preparedHostedAgentPlugins.desired.keys())B.add(m4);V4.push(`runtime Agent Plugin projection planning failed: ${A$ instanceof Error?A$.message:String(A$)}`),E$={transaction:null}}if(V=E$.transaction,V?.hasMutations&&!X.systemdApply)throw Error("Agent Plugin mutations require systemd activation and readiness")}G.assertPlatformRoots();let y1=null;if(Iv(Q)||Q.projection?.sourceSchemaVersion==="clawdi.hosted-runtime.manifest.v1")try{y1=Jo$(J)}catch(x){n.push(`runtime codex setup failed: ${x instanceof Error?x.message:String(x)}`)}for(let[x]of $4){let E$=i$.get(x);if(!E$)throw Error(`runtime ${x} install observation is missing`);try{Do$(x,E$,Q,z,J.userHome,y$,u0)}catch(A$){n.push(`runtime ${x} channel plugin install failed: ${A$ instanceof Error?A$.message:String(A$)}`)}}let h1=n5$(Q);try{let x=h1?i$.get(h1):void 0;if(h1&&!x?.appRoot)throw Error(`runtime ${h1} artifact root is unavailable`);let E$=RJ$({desiredRuntime:h1,home:z,...x?.appRoot?{appRoot:x.appRoot}:{},paths:J});if(E$.status==="rollback-refused")throw Error(E$.errors.join(", "))}catch(x){let E$=h1?`runtime ${h1} managed WhatsApp compatibility`:"runtime managed WhatsApp compatibility cleanup";n.push(`${E$} failed: ${x instanceof Error?x.message:String(x)}`)}if(n.length>0)throw Error(n.join("; "));G.assertPlatformRoots(),_G(J.userHome),qi$(J.clawdiHome,G.identity),Y0(()=>{pQ(H,{recursive:!0}),v4(H)});for(let x of[J.installInventory,J.projectionRoot,d,$$])sz(J,x,{mode:493});sz(J,J.managedSecretRoot),Ov(J.managedSecretRoot),sz(J,J.egressRoot,{mode:457}),W5(J.egressRoot,457),Ki$(J.egressCaDir),sz(J,g6(J.egressSystemCaFile),{mode:457}),W5(g6(J.egressSystemCaFile),457),FG(J.egressScratchRoot,J.userHome);let OW=null;YJ(J.managedConfig,{schemaVersion:"clawdi.hostedManagedConfig.v1",generatedAt:I,deploymentId:Q.deploymentId,environmentId:Q.environmentId,instanceId:Q.instanceId,generation:Q.generation,locale:Q.locale??null,controlPlane:Q.controlPlane,egressEngine:Q.egressEngine??null,auth:{source:"runtime-instance-data",token:"<redacted>"},workspaceRoot:H},J),YJ(J.syncState,{schemaVersion:"clawdi.runtimeSyncState.v1",generatedAt:I,deploymentId:Q.deploymentId,environmentId:Q.environmentId,instanceId:Q.instanceId,generation:Q.generation,locale:Q.locale??null,runtimes:Object.fromEntries(Object.entries(Q.runtimes).map(([x,E$])=>[x,{enabled:E$.enabled,updateChannel:E$.updateChannel??null,workspaceRoot:H}]))},J),YJ(J.instanceData,{schemaVersion:"clawdi.runtimeInstanceData.v1",generatedAt:I,deploymentId:Q.deploymentId,environmentId:Q.environmentId,instanceId:Q.instanceId,generation:Q.generation,locale:Q.locale??null,controlPlane:Q.controlPlane,workspaceRoot:H},J),YJ(J.sensitiveInstanceData,{schemaVersion:"clawdi.runtimeSensitiveInstanceData.v1",generatedAt:I,tokenSource:w0(W??{},Sx)?"CLAWDI_AUTH_TOKEN":$.source,token:"<redacted>"},J);let C4=qT(P)?eo$(P,J):ao$(J),M0=so$(C4?H8$(Q.egressEngine,J,X.egressEngineEnsureOptions):null,J);to$(Q,C4,M0);let xh=C4?$r$(J):Jr$(J),p_=qr$(J,W),kh=p_?EO(J):null;if(kh)e0=Kr$(kh),u4=ND(Q),S0=e0!==u$?.daemonAuthTokenRevision||u4!==u$?.daemonProgramRevision;try{Y0(()=>Xi$(Q,W,z))}catch(x){n.push(`runtime channel credential materialization failed: ${x instanceof Error?x.message:String(x)}`)}let Hz=Ti$(Q,W,J),vh=Hz.path,gh=process.env.CLAWDI_RUNTIME_USER?.trim()||"clawdi",yh=Z8$({paths:J,profileBundlePath:C4,secretFilePath:vh,engine:M0,addon:xh,runtimeUser:gh}),jw=yh.egressProgram,DW=yh.identity,GH$=DW?.runtimeUid??0,zH$=DW?.runtimeGid??0,UH$=DW?.egressUid??0,HH$=DW?.egressGid??0,VH$=Qr$({program:jw,paths:J,runtimeUser:gh,runtimeUid:GH$,runtimeGid:zH$,egressUid:UH$,egressGid:HH$});zi$(Q,$.secretValues,J);let BH$=Hr$(Q,J),i_=new Set;Y$.push(...G5$({manifest:Q,paths:J,workspaceRoot:H,generatedAt:I,secretValues:W,observations:i$,egressProfileBundlePath:C4,egress:jw}));let wH$=jw!==null&&DW!==null&&Y$.length>0,ZW=u$?.egressSidecarSecretRevision;if(wH$){if(K8=Hz.material.revision,DJ=Hz.changed||ZW===void 0||ZW!==K8,ZW===void 0)H7=p8$(J,Y)??void 0,NW=H7!==void 0;else if(DJ&&Hz.previousRevision!==ZW)if(K8===ZW)H7=Hz.material;else n_=ZW}let qH$=h8$(J);z5$({manifest:Q,paths:J,openClawWorkspaceRoot:R6,secretValues:W,observations:i$,previousProjectedProviderIds:G4,hermesWhatsAppAuthDir:U,openClawOwnerBrowserBootstrapSupported:a0});let o_={};for(let[x]of $4){let E$=i$.get(x);if(!E$)throw Error(`runtime ${x} install observation is missing`);o_[x]=ei$(x,E$,Q,z,G4[x]??[])}try{let x=Y0(()=>$o$(Q,z,y1));o_.codex=x.revision,I4.codex=x.providerIds}catch(x){n.push(`runtime codex provider projection failed: ${x instanceof Error?x.message:String(x)}`)}if(n.length>0)throw Error(n.join("; "));if(s0)try{let x=Ir$(Q,z,R6);q=dQ({rootTargets:[mm()],trustedRootDirectories:[J.managedResourceRoot],runtimeUserTargets:x,runtimeUserTrustedRoots:[J.userHome,J.clawdiHome],runtimeUserSymlinkTargets:[],metadataTargets:DG(x,[J.userHome,J.clawdiHome])}),ho$({manifest:Q,observations:i$,home:z,openClawWorkspaceRoot:R6,preparedSourcedSkills:jW,hermesDriver:b9,openClawDriver:u})}catch(x){let E$=x instanceof Error?x.message:String(x);try{if(q)H1(q)}catch(A$){throw Error(`runtime Skill projection failed and could not be rolled back: ${E$}; ${A$ instanceof Error?A$.message:String(A$)}`)}q=null,V4.push(E$)}try{uo$(Q,J,i$,H)}catch(x){n.push(`runtime MCP projection failed: ${x instanceof Error?x.message:String(x)}`)}if(n.length>0)throw Error(n.join("; "));for(let x of["hermes","openclaw"]){if(Object.hasOwn(Q.runtimes,x))continue;try{t8$({runtime:x,manifest:Q,secretValues:W,paths:J,home:z,workspaceRoot:H})}catch(E$){n.push(`stale ${x} OAuth credential reconciliation failed: ${E$ instanceof Error?E$.message:String(E$)}`)}}if(n.length>0)throw Error(n.join("; "));for(let[x,E$]of $4){let A$=i$.get(x);if(!A$)throw Error(`runtime ${x} install observation is missing`);let m4=v(J.installInventory,`${x}.json`);YJ(m4,{schemaVersion:"clawdi.runtimeInstallInventory.v1",generatedAt:I,runtime:x,enabled:E$.enabled,updateChannel:E$.updateChannel??null,simulation:!1,status:A$.status,executionUser:A$.executionUser,install:A$.install,command:ji$(x,E$.install),commandPath:A$.commandPath,appRoot:A$.appRoot,installerUrl:A$.installerUrl,executedInstallerUrl:A$.executedInstallerUrl,installStartedAt:A$.installStartedAt??null,installFinishedAt:A$.installFinishedAt??null,installDurationMs:A$.installDurationMs??null,resultExitCode:A$.exitCode,stdoutTail:A$.stdoutTail,stderrTail:A$.stderrTail,error:A$.error},J),X$.push(m4);let ch=v(J.projectionRoot,`${x}.json`);if(YJ(ch,d8$(x,Q),J),k.push(ch),x==="hermes"||x==="openclaw")try{t8$({runtime:x,observation:A$,manifest:Q,secretValues:W,paths:J,home:z,workspaceRoot:H})}catch(d4){n.push(`runtime ${x} OAuth credential reconciliation failed: ${d4 instanceof Error?d4.message:String(d4)}`)}try{let d4=Pi$(x,A$,Q,z,R6,H);if(d4)p.push(d4)}catch(d4){n.push(`runtime ${x} config projection failed: ${d4 instanceof Error?d4.message:String(d4)}`)}try{let d4=ti$(x,A$,Q,W,z,H,G4[x]??[],a0,N1);I4[x]=d4.providerIds}catch(d4){n.push(`runtime ${x} provider projection failed: ${d4 instanceof Error?d4.message:String(d4)}`)}try{if(Oo$(x,A$,Q,z,H,U))M.add(x)}catch(d4){n.push(`runtime ${x} channel projection failed: ${d4 instanceof Error?d4.message:String(d4)}`)}if(n.length>0)throw Error(n.join("; "));let a_=l5$({manifest:Q,paths:J,name:x,runtime:E$,observation:A$,workspaceRoot:H,generatedAt:I,secretValues:W,egressProfileBundlePath:C4}),LH$=MT(a_.runtime,J);e.push(LH$),i_.add(aj(a_.runtime.runtime));for(let d4 of a_.services){let jH$=MT(d4,J);e.push(jH$),i_.add(aj(d4.runtime,d4.service))}let lh=v($$,`${x}.enabled`);if(E$.enabled)z8(J,lh,`${I}
|
|
971
971
|
`),Q$.push(lh)}let r_=v(J.projectionRoot,"clawdi-mcp.json");if(Ro$(Q)||Q.projection?.skills!==void 0)YJ(r_,d8$("clawdi-mcp",Q),J),k.push(r_);else l4(r_,{force:!0});G.assertPlatformRoots();let Vz=m8$({runtimePrograms:Y$,egressProgram:jw,egressIdentity:DW,manifest:Q,paths:J,workspaceRoot:H,daemonAuthTokenFile:p_,secretValues:W,providerProjectionRevisions:o_,runtimeRevision:(x,E$,A$,m4)=>Lr$(x,E$,A$,m4,U,a0),commonEnvironment:qH$});FW=Vz.staleFiles;let Bz=E8$(Y$,J,y$,X.systemdApply!==void 0||X.executeOfficialServiceInstallers===!0),KH$=new Set(Bz.pending.map((x)=>x.unitName));b=[...new Set(Y$.filter((x)=>x.programKind==="runtime"&&x.service===null&&M.has(x.runtime)).map(Qv))].filter((x)=>!KH$.has(x)).sort(),u0.officialServices=Bz.targets;let ZJ=V;if(ZJ?.hasMutations){let x=b8$({runtimePrograms:Y$,staleUserUnits:FW.userUnits,mutationRuntimes:ZJ.mutationRuntimes});O=x.quiesceUserUnits,_=x.restartUserUnits,L=!0,X.systemdApply?.quiesce(O),N=!0,F=!0}let hh=!1;try{if(ZJ)w=dQ({rootTargets:[sN(J)],trustedRootDirectories:[J.statusRoot],runtimeUserTargets:[...ZJ.snapshotTargets],runtimeUserTrustedRoots:[z],runtimeUserSymlinkTargets:[],metadataTargets:DG(ZJ.snapshotTargets,[z])});if(ZJ?.apply(),hh=!0,ZJ)da(ZJ.nextReceipt,J)}catch(x){let E$=hh?X.preparedHostedAgentPlugins?.desired.keys():ZJ?.mutationNames;for(let m4 of E$??[])B.add(m4);let A$=ZJ?.rollback()??[];try{if(w)H1(w)}catch(m4){A$.push(`runtime Agent Plugin snapshot rollback failed: ${m4 instanceof Error?m4.message:String(m4)}`)}if(A$.length>0)throw Error(`runtime Agent Plugin projection failed and could not be rolled back: ${[x instanceof Error?x.message:String(x),...A$].join("; ")}`);V4.push(`runtime Agent Plugin projection failed: ${x instanceof Error?x.message:String(x)}`),V=null,w=null,F=!1}if(Bz.pending.length>0&&Vz.egressSidecarActive&&X.systemdApply){if(N=!1,!X.systemdApply.activateEgressPrerequisite({restartDaemon:S0,restartEgressSidecar:DJ,stopEgressSidecar:!1,reconcileUserUnits:t0.systemdUserUnits,restartUserUnits:[],staleSystemUnits:[],staleUserUnits:[]}).applied)throw Error("transparent-egress system prerequisites did not reach readiness")}if(Bz.pending.length>0)N=!1;for(let x of Bz.pending){G.assertPlatformRoots();let E$=()=>x8$(x,J),A$=X.systemdApply?X.systemdApply.installOfficialService(x.unitName,E$):E$();if(A$)throw Error(A$)}G.assertPlatformRoots();let uh=v(d,"boot-finished");if(z8(J,uh,`${I}
|
|
972
972
|
`),X.systemdApply){N=!1;let x=X.systemdApply.activate({restartDaemon:S0,restartEgressSidecar:DJ,stopEgressSidecar:!1,reconcileUserUnits:t0.systemdUserUnits,restartUserUnits:[...new Set([..._,...b])].sort(),staleSystemUnits:FW.systemUnits,staleUserUnits:FW.userUnits});if(d$=x.applied,!x.applied)throw Error("systemd runtime services did not reach required readiness");z9$(Q,{probe:X.fileBrowserReadinessProbe})}if(n.length===0&&X.cacheLastGood!==!1)OW=B5$($.sourceManifest??Q,J,$.secretValues,Q);let mh={manifest:Q,source:$.source,sourcePath:$.sourcePath,offline:$.offline,mode:$.offline?"degraded-offline":"normal",enabledRuntimes:Z,installErrors:n,resourceProjectionErrors:V4,projectedProviderIds:I4,agentPluginFailedNames:[...B].sort(),outputs:{processManager:"systemd",workspaceRoot:H,managedConfig:J.managedConfig,syncState:J.syncState,instanceData:J.instanceData,sensitiveInstanceData:J.sensitiveInstanceData,manifestLastGood:OW,appliedState:null,installInventory:X$,projections:k,managedLocaleFiles:p,runConfigs:e,systemdSystemUnitRoot:J.systemdSystemRoot,systemdSystemUnits:Vz.systemUnits,systemdUserUnitRoot:J.systemdUserRoot,systemdUserUnits:Vz.userUnits,egressProfileBundle:C4,egressSecretFile:vh,egressEngine:M0,egressTransparentEnv:VH$,egressAddon:xh?.path??null,liveSyncEnvironments:BH$,daemonAuthTokenFile:p_,instanceSemaphores:Q$,bootFinished:uh}};if(n.length===0){G.assertPlatformRoots();let x=e0!==void 0&&e0===u$?.daemonAuthTokenRevision,E$=u4!==void 0&&u4===u$?.daemonProgramRevision,A$=K8!==void 0&&K8===u$?.egressSidecarSecretRevision;l4(v(J.managedResourceRoot,Ji$),{force:!0}),ro$(u0,J),X.commitAuthority?.(mh,{...e0!==void 0&&(d$||x)?{daemonAuthTokenRevision:e0}:{},...u4!==void 0&&(d$||E$)?{daemonProgramRevision:u4}:{},...K8!==void 0&&(d$||A$)?{egressSidecarSecretRevision:K8}:{}});try{U9$(Q,J)}catch(m4){console.warn(`post-commit Files companion candidate cleanup deferred: ${m4 instanceof Error?m4.message:String(m4)}`)}try{for(let m4 of y8$(J,Vz.staleFiles))console.warn(`post-commit systemd file cleanup deferred: ${m4}`);Gr$(i_,J)}catch(m4){console.warn(`post-commit runtime file cleanup deferred: ${m4 instanceof Error?m4.message:String(m4)}`)}for(let m4 of v8$({paths:J,unitNames:t0.staleOfficialUnits,workspaceRoot:H}))console.warn(`post-commit official runtime service cleanup deferred: ${m4}`)}return mh}catch(F$){if(F)for(let C4 of V?.mutationNames??[])B.add(C4);let e4=F$ instanceof Error?F$.message:String(F$),y1=X.systemdApply?.transactionState()==="mutated"||L||F,h1=N||!y1;if(y1&&!h1)try{X.systemdApply?.quiesce(O),h1=!0}catch(C4){n.push(`runtime candidate service quiesce failed: ${C4 instanceof Error?C4.message:String(C4)}`)}let OW=!1;if(h1){if(V)n.push(...V.rollback());let C4=!0;if(w)try{H1(w)}catch(M0){C4=!1,n.push(`runtime Agent Plugin filesystem rollback failed: ${M0 instanceof Error?M0.message:String(M0)}`)}if(q)try{H1(q)}catch(M0){C4=!1,n.push(`runtime Skill filesystem rollback failed: ${M0 instanceof Error?M0.message:String(M0)}`)}try{if(G.assertPlatformRoots(),H1(r),H7)wv(H7,J);else if(n_){let M0=p8$(J,Y);if(M0?.revision===n_)wv(M0,J);else NW=!1,l4(TD(J),{force:!0})}else if(!NW)l4(TD(J),{force:!0});OW=C4}catch(M0){n.push(`runtime filesystem rollback failed: ${M0 instanceof Error?M0.message:String(M0)}`)}}else n.push("runtime filesystem rollback skipped because candidate services did not quiesce");if(OW&&!d_&&q0(H)!==q0(J.userHome)&&b4(H))try{Y0(()=>{if(lX(H).length===0)l4(H,{recursive:!0})})}catch(C4){n.push(`runtime workspace rollback failed: ${C4 instanceof Error?C4.message:String(C4)}`)}if(X.systemdApply&&OW&&y1)try{X.systemdApply.rollback({restartDaemon:S0,restartEgressSidecar:DJ&&NW,stopEgressSidecar:DJ&&!NW,reconcileUserUnits:t0.systemdUserUnits,restartUserUnits:[...new Set([..._,...b])].sort(),staleSystemUnits:FW.systemUnits,staleUserUnits:FW.userUnits})}catch(C4){n.push(`runtime systemd rollback failed: ${C4 instanceof Error?C4.message:String(C4)}`)}else if(X.systemdApply&&y1&&h1)n.push("runtime systemd rollback skipped because filesystem authority restoration failed");else if(X.systemdApply&&y1)n.push("runtime systemd reconciliation skipped because candidate services did not quiesce");if(!NW)n.push("runtime egress sidecar stopped because committed secret rollback authority could not be verified");return n.unshift(`runtime apply failed: ${e4}`),hB({load:$,paths:J,workspaceRoot:H,enabledRuntimes:Z,installErrors:n,projectedProviderIds:Object.fromEntries(Object.entries(G4).map(([C4,M0])=>[C4,[...M0]])),agentPluginFailedNames:[...B].sort()})}}var tp$="openai",Hv=".clawdi-managed-whatsapp-auth.json",Ji$="hermes-whatsapp.json",Ni$="import uvicorn; assert callable(getattr(uvicorn.Server, 'capture_signals', None))",Oi$,PD="<!-- >>> clawdi managed locale >>>",uB="<!-- <<< clawdi managed locale <<< -->",qv="clawdi",Kv="config.toml",Lv="0.146.0",i8$,hi$=`
|
|
973
973
|
import { pathToFileURL } from "node:url";
|