clawdi 0.13.56 → 0.13.58

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +2 -2
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -484,7 +484,7 @@ ${W.errors.join(`
484
484
  `)}`);let Y=await TK(Q),z=J.live===!0||J.probe===!0?await Te(Q,Y,Ee(J.timeout)):{status:"skipped",detail:"live probe disabled; pass --live to call provider"},H={provider_id:Q.id,base_url:Q.base_url,auth:Re(Y),model:J.model??Eg$(Q)??null,provider_probe:z};if(J.json){console.log(JSON.stringify(H,null,2));return}console.log(`Provider: ${Q.id}`),console.log(`Endpoint: ${Q.base_url}`),console.log(`Auth: ${Y.status}${Y.detail?` (${Y.detail})`:""}`),console.log(`Provider probe: ${z.status}${"detail"in z&&z.detail?` (${z.detail})`:""}`)}async function pf$($,J={}){if(J.project)throw Error("AI Provider auth is account-global; --project is not supported here.");let X=h6({allowNoAuthPublic:!0}),Q=fK(X,$),W=J.tool??(Q.auth.type==="agent_profile"?Q.auth.tool:void 0);if(!W)throw Error("--tool is required unless the provider already uses agent_profile auth.");te(ae(W)??W);let Y=J.profile??(Q.auth.type==="agent_profile"?Q.auth.profile:"default"),G=await xK(W,{profile:Y,source:J.source,from:J.from,to:J.to,keychainService:J.keychainService,keychainAccount:J.keychainAccount,yes:J.yes,dryRun:J.dryRun,json:J.json,quiet:J.json,destinationLabel:"AI Provider auth"});if(!G)return;let z=await Wg$(Q,G);if(lQ(E3(X,z,!0)),J.json){console.log(JSON.stringify({provider_id:$,auth:z.auth},null,2));return}console.log(B.green(`✓ Bound ${$} auth to agent profile ${G.tool}/${G.profile}`))}async function of$($,J={}){let X=h6({allowNoAuthPublic:!0}),Q=fK(X,$),W=J.method??"oauth";if(W!=="oauth")throw Error("AI Provider connect currently supports --method oauth.");let Y=$g$(J.callback??(J.json?"manual":"loopback"));if(J.redirectUri&&Y==="loopback")throw Error("--redirect-uri is only supported with --callback manual.");let G=ae(J.tool??Hg$(Q));if(!G)throw Error("--tool is required for this provider type. Supported OAuth tool: codex.");se(G);let z=null;if(Y==="loopback"&&!J.dryRun)try{z=await af$(Jg$(J.timeout),ee(G))}catch(V){if(Y="manual",!J.json)console.log(B.yellow(`Could not start the local OAuth callback: ${V.message}. Falling back to manual completion.`))}let H=z?.redirectUri??J.redirectUri??wg$(G),w={provider_id:$,method:W,provider:G,callback:Y,redirect_uri:H,dry_run:Boolean(J.dryRun)};if(J.dryRun){console.log(JSON.stringify(w,null,2));return}try{let V=new $$;await V.postJsonBody("/v1/ai-providers",oe(Q),{replace:"true"});let U=await V.postJsonBody(`/v1/ai-providers/${encodeURIComponent($)}/auth/oauth/start`,{provider:G,redirect_uri:w.redirect_uri});if(J.json){console.log(JSON.stringify(U,null,2));return}if(console.log(B.green(`✓ Started OAuth for ${$}`)),console.log(`Open: ${U.auth_url}`),!z){console.log(B.gray(`After the browser redirects, complete with \`clawdi ai-provider complete-oauth ${$} --redirect-url <url>\`.`));return}if(J.open!==!1)Xg$(U.auth_url);console.log(B.gray(`Waiting for OAuth callback on ${z.redirectUri}`));let q=await z.wait();if(q.error)throw Error(`OAuth provider returned ${q.error}${q.errorDescription?`: ${q.errorDescription}`:""}`);if(!q.code||!q.state)throw Error("OAuth callback did not include code and state.");let Z=await pe($,{code:q.code,state:q.state,redirectUri:z.redirectUri});console.log(B.green(`✓ Connected OAuth profile for ${Z.id}`))}catch(V){if(z?.timedOut(V)){console.log(B.yellow("Timed out waiting for the browser callback. If the browser shows a localhost URL, paste it with:")),console.log(B.bold(`clawdi ai-provider complete-oauth ${$} --redirect-url <url>`));return}throw V}finally{await z?.close()}}async function rf$($,J={}){let X=if$(J),Q=await pe($,X);if(J.json){console.log(JSON.stringify(Q,null,2));return}console.log(B.green(`✓ Connected OAuth profile for ${$}`))}async function pe($,J){let Q=await new $$().postJsonBody(`/v1/ai-providers/${encodeURIComponent($)}/auth/oauth/complete`,{code:J.code,state:J.state,...J.redirectUri?{redirect_uri:J.redirectUri}:{}}),W=h6({allowNoAuthPublic:!0}),Y=fK(W,$),G=re(Y,Q);return lQ(E3(W,G,!0)),G}function if$($){let{code:J,state:X}=$;if($.redirectUrl){let Q;try{Q=new URL($.redirectUrl)}catch(Y){throw Error(`Invalid --redirect-url: ${Y.message}`)}let W=Q.searchParams.get("error");if(W){let Y=Q.searchParams.get("error_description");throw Error(`OAuth provider returned ${W}${Y?`: ${Y}`:""}`)}J=J??Q.searchParams.get("code")??void 0,X=X??Q.searchParams.get("state")??void 0}if(!J||!X)throw Error("OAuth completion requires --redirect-url or both --code and --state.");return{code:J,state:X,redirectUri:$.redirectUri}}async function af$($,J){let X="",Q,W=!1,Y=()=>{},G=()=>{},z=new Promise((V,U)=>{Y=V,G=U}),w=await sf$((V,U)=>{let q=new URL(V.url??"/",X);if(q.pathname!==J.path){gS(U,404,"Not found");return}if(W){gS(U,200,"OAuth callback already received. You can close this tab.");return}if(W=!0,Q)clearTimeout(Q);let Z={code:q.searchParams.get("code")??void 0,state:q.searchParams.get("state")??void 0,error:q.searchParams.get("error")??void 0,errorDescription:q.searchParams.get("error_description")??void 0};gS(U,Z.error?400:200,Z.error?"OAuth returned an error. Return to your terminal for details.":"OAuth callback received. You can close this tab."),Y(Z)},J);return X=`http://${J.host}:${w.port}`,Q=setTimeout(()=>{G(new uS)},$*1000),{redirectUri:`${X}${J.path}`,wait:()=>z,close:async()=>{if(Q)clearTimeout(Q);await vK(w.servers)},timedOut:(V)=>V instanceof uS}}async function sf$($,J){let X;for(let Q=0;Q<J.ports.length;Q+=1){let W=J.ports[Q];try{return await tf$($,J.host,W)}catch(Y){if(X=Y,mS(Y)!=="EADDRINUSE"||Q===J.ports.length-1)break}}throw X instanceof Error?X:Error("No available OAuth callback port.")}async function tf$($,J,X){if(J==="localhost")return await ef$($,X);let Q=yS($);return{port:(await hS(Q,J,X)).port,servers:[Q]}}async function ef$($,J){let X=yS($),Q=yS($);try{let W=await hS(X,"127.0.0.1",J);try{await hS(Q,"::1",J,{ipv6Only:!0})}catch(Y){if(mS(Y)==="EADDRNOTAVAIL"||mS(Y)==="EAFNOSUPPORT")return await vK([Q]),{port:W.port,servers:[X]};throw await vK([X,Q]),Y}return{port:W.port,servers:[X,Q]}}catch(W){throw await vK([X,Q]),W}}async function hS($,J,X,Q={}){return await new Promise((W,Y)=>{let G=(H)=>{$.off("listening",z),Y(H)},z=()=>{$.off("error",G);let H=$.address();if(!H||typeof H==="string"){Y(Error("Could not determine loopback callback port."));return}W(H)};$.once("error",G),$.once("listening",z),$.listen({port:X,host:J,...Q})})}async function vK($){await Promise.all($.map((J)=>new Promise((X)=>{if(!J.listening){X();return}J.close(()=>X())})))}function mS($){if(typeof $!=="object"||$===null||!("code"in $))return;let J=$.code;return typeof J==="string"?J:void 0}function gS($,J,X){$.writeHead(J,{"content-type":"text/html; charset=utf-8"}),$.end(`<!doctype html><meta charset="utf-8"><title>Clawdi OAuth</title><body>${Qg$(X)}</body>`)}function $g$($){if($==="loopback"||$==="manual")return $;throw Error("Invalid --callback. Supported modes: loopback, manual.")}function Jg$($){let J=Number($??600);if(!Number.isFinite(J)||J<1||J>3600)throw Error("--timeout must be a number of seconds between 1 and 3600.");return J}function Xg$($){let J=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open";try{let X=process.platform==="win32"?["/c","start","",$]:[$],Q=xf$(J,X,{stdio:"ignore",detached:!0});Q.on("error",()=>{}),Q.unref()}catch{}}function Qg$($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}async function Wg$($,J){let X=new $$;await X.postJsonBody("/v1/ai-providers",oe($),{replace:"true"});let Q=await X.postJsonBody(`/v1/ai-providers/${encodeURIComponent($.id)}/auth/import`,{type:"agent_profile",tool:J.tool,profile:J.profile,payload:J.payload});return re($,Q)}function oe($){return{provider_id:$.id,type:$.type,label:$.label,base_url:$.base_url,api_mode:$.api_mode,auth:$.auth,managed_by:$.managed_by??"user",runtime_env_name:$.runtime_env_name,capabilities:$.capabilities,models:$.models}}function re($,J){let X={...$,auth:J.auth};if(J.runtime_env_name!==void 0&&J.runtime_env_name!==null)X.runtime_env_name=J.runtime_env_name;if(J.models!==void 0&&J.models!==null)X.models=J.models;return X}function ie($,J,X){if(!$8($))throw Error(`Invalid AI Provider id: ${$}`);let Q=cS(J.type??X?.type),W=lS(J.apiMode??X?.api_mode??iX(Q)),Y=J.baseUrl??X?.base_url??vq(Q);if(!Y)throw Error(`--base-url is required for provider type ${Q}.`);let G=J.auth?Yg$(J.auth):X?.auth;if(!G)throw Error("--auth is required. Use env:<NAME>, clawdi://..., agent:codex/<profile>, or none.");let z={id:$,type:Q,base_url:Y,auth:G};if(J.label??X?.label)z.label=J.label??X?.label;let H=Tg$(J.defaultModel,X?.models);if(H)z.models=H;if(W)z.api_mode=W;let w=J.agentEnv??(Gg$(G)?X?.runtime_env_name:void 0);if(w){if(!kq(w))throw Error(`Invalid agent env name: ${w}`);z.runtime_env_name=w}let V=Vg$(J.capability);if(V??X?.capabilities)z.capabilities=V??X?.capabilities;return z}function cS($){if(!$||!oG($))throw Error("Invalid or missing --type. Supported types: openai, anthropic, openrouter, gemini, mistral, custom_openai_compatible.");return $}function lS($){if(!$)return;if(!rX($))throw Error("Invalid --api-mode. Supported modes: openai_chat, openai_responses, anthropic_messages, google_generate_content.");return $}function Yg$($){if($==="none")return{type:"none"};if(Rj($))return{type:"secret_ref",ref:$};if($.startsWith("oauth:"))throw Error("Direct oauth_profile auth is not supported. Use connect for Codex OAuth.");if($.startsWith("agent:")){let{provider:J,profile:X}=zg$($.slice(6));return te(J),{type:"agent_profile",tool:J,profile:X}}throw Error("Unsupported --auth. Use env:<NAME>, clawdi://..., agent:codex/<profile>, or none.")}function Gg$($){if($.type==="secret_ref")return!$.ref.startsWith("env:");if($.type==="api_key")return $.source!=="env";return!1}function zg$($){let[J,X="default",Q]=$.split("/");if(!J||Q!==void 0)throw Error("Profile auth must use <provider>/<profile>.");if(!B5(J)||!B5(X))throw Error("Profile auth provider and profile must use lowercase letters, numbers, dots, underscores, or hyphens.");return{provider:J,profile:X}}function ae($){if(!$)return;let J=$.trim().toLowerCase().replace(/_/g,"-");if(J==="claude"||J==="claudecode")return"claude-code";if(J==="github"||J==="github-cli")return"gh";return J}function Hg$($){if($.type==="openai")return ne;return}function se($){if($===ne)return;throw Error(`AI Provider OAuth currently supports Codex only. Use API key, env:, or clawdi:// auth for ${$}.`)}function te($){if($===ff$)return;throw Error(`AI Provider auth profiles currently support Codex only. Use API key, env:, clawdi:// auth, or legacy agent credential commands for ${$}.`)}function ee($){return se($),gf$}function wg$($){let J=ee($);return`http://${J.host}:${J.ports[0]}${J.path}`}function Vg$($){if(!$||$.length===0)return;let J={};for(let X of $.flatMap((Q)=>Q.split(","))){let Q=X.trim();if(!Q)continue;if(Q==="chat"||Q==="responses"||Q==="tools"||Q==="vision"||Q==="embeddings"||Q==="image_generation"){J[Q]=!0;continue}throw Error(`Unsupported capability: ${Q}`)}return J}function $$$($,J,X){if(!X.setDefault)return $;return{...$,defaults:{...$.defaults,chat_provider_id:J.id}}}function J$$($,J){let X=fK($,J);return{...$,providers:[X],defaults:void 0}}function Ug$($){let J=[];for(let X of $.providers){let Q=qg$(X.auth);if(!Q)continue;let W=Q.slice(4),Y=process.env[W];if(!Y)throw Error(`Cannot include secrets: ${Q} is not set in the current environment.`);J.push({provider_id:X.id,ref:Q,env_name:W,value:Y})}return{schema_version:1,secrets:J}}function qg$($){if($.type==="secret_ref"){if($.ref.startsWith("env:"))return $.ref;if($.ref.startsWith("clawdi://"))throw Error("Provider-only encrypted export does not resolve clawdi:// refs. Export/import keeps those refs and leaves the Vault secret in Vault.")}if($.type==="api_key"){if($.source==="env"&&$.ref?.startsWith("env:"))return $.ref;if($.source==="vault"||$.source==="managed")throw Error("Provider-only encrypted export currently supports env-backed provider secrets only.")}return null}function X$$($="CLAWDI_SECRET_EXPORT_PASSPHRASE"){let J=process.env[$];if(!J)throw Error(`Set ${$} to use --secret-passphrase.`);return J}function Zg$($,J){let X=me(16),Q=me(12),W=de($,X,32),Y=kf$("aes-256-gcm",W,Q),G=Buffer.concat([Y.update(JSON.stringify(J),"utf-8"),Y.final()]);return{schema_version:1,algorithm:"aes-256-gcm+scrypt",kdf:{name:"scrypt",salt:X.toString("base64"),key_length:32},nonce:Q.toString("base64"),ciphertext:G.toString("base64"),auth_tag:Y.getAuthTag().toString("base64")}}function Bg$($,J){if(J.schema_version!==1||J.algorithm!=="aes-256-gcm+scrypt"||J.kdf?.name!=="scrypt"||J.kdf.key_length!==32)throw Error("Unsupported encrypted secret export format.");let X=Buffer.from(J.kdf.salt,"base64"),Q=Buffer.from(J.nonce,"base64"),W=de($,X,32),Y=vf$("aes-256-gcm",W,Q);Y.setAuthTag(Buffer.from(J.auth_tag,"base64"));let G=Buffer.concat([Y.update(Buffer.from(J.ciphertext,"base64")),Y.final()]).toString("utf-8"),z=JSON.parse(G),H=RJ(z,"secret export payload");if(H.schema_version!==1||!Array.isArray(H.secrets))throw Error("Invalid decrypted secret export payload.");return{schema_version:1,secrets:H.secrets.map((V)=>{let U=RJ(V,"secret export entry");if(typeof U.provider_id!=="string"||typeof U.ref!=="string"||typeof U.env_name!=="string"||typeof U.value!=="string")throw Error("Invalid decrypted secret export entry.");if(!kq(U.env_name)||U.ref!==`env:${U.env_name}`)throw Error("Invalid decrypted env secret metadata.");return{provider_id:U.provider_id,ref:U.ref,env_name:U.env_name,value:U.value}})}}function Kg$($){if(typeof $!=="object"||$===null||Array.isArray($))return $;let{encrypted_secrets:J,...X}=$;return X}function Lg$($,J,X,Q){if(J!=="env-file")throw Error("Only --import-secrets env-file is supported in the provider-only path.");if(!X)throw Error("--import-secrets env-file requires --out <file>.");let Y=RJ($,"AI Provider export").encrypted_secrets;if(!Y||typeof Y!=="object"||Array.isArray(Y))throw Error("Export file does not contain encrypted_secrets.");let z=Bg$(X$$(Q),Y).secrets.map((H)=>`${H.env_name}=${Ng$(H.value)}`);return{out:X,content:`${z.join(`
485
485
  `)}
486
486
  `}}function Ng$($){return`'${$.replace(/'/g,"'\\''")}'`}function Q$$($,J){Z$($,J,{mode:f4})}function Og$($){let J=RJ($,"OpenClaw config"),X=RJ(J.models,"OpenClaw models"),Q=RJ(X.providers,"OpenClaw models.providers"),W=[];for(let[G,z]of Object.entries(Q)){if(!$8(G))continue;let H=RJ(z,`OpenClaw provider ${G}`),w=D4(H,"baseUrl")??D4(H,"base_url");if(!w)continue;let V=bg$(D4(H,"api"))??lS(D4(H,"apiMode")??D4(H,"api_mode")),U=cS(D4(H,"type")??D4(H,"provider")??Y$$(G,w,{api_mode:V??D4(H,"api")})),q=D4(H,"keyEnv")??D4(H,"key_env")??le(H.apiKey)??le(H.api_key),Z=Ag$(H.models),K={id:G,type:U,base_url:w,auth:q?{type:"secret_ref",ref:`env:${q}`}:{type:"none"}};if(Z)K.models=[{id:Z}];if(K.api_mode=V??iX(U),q)K.runtime_env_name=q;W.push(K)}let Y=Pg$(J);return{schema_version:1,providers:W,defaults:Y}}function Dg$($){let J;try{J=R9($)}catch(G){throw Error(`Hermes config is not valid YAML: ${G instanceof Error?G.message:String(G)}`)}let X=RJ(J,"Hermes config"),Q=[...Fg$(ce(X,"providers")),...jg$(X.custom_providers)];if(Q.length===0)throw Error("Hermes config does not contain a providers block.");let W=ce(X,"model"),Y=W?Ig$(D4(W,"provider")):void 0;return{schema_version:1,providers:Q,defaults:Y?{chat_provider_id:Y}:void 0}}function Fg$($){if(!$)return[];let J=[];for(let[X,Q]of Object.entries($)){if(!$8(X))continue;let W=RJ(Q,`Hermes provider ${X}`),Y=W$$(X,W);if(Y)J.push(Y)}return J}function jg$($){if($===void 0||$===null)return[];if(!Array.isArray($))throw Error("Hermes custom_providers must be a list.");let J=[];for(let X of $){let Q=RJ(X,"Hermes custom provider"),W=D4(Q,"name");if(!W)continue;let Y=_g$(W),G=W$$(Y,Q);if(G)J.push(G)}return J}function W$$($,J){let X=D4(J,"api")??D4(J,"url")??D4(J,"base_url")??D4(J,"baseUrl");if(!X)return;let Q=D4(J,"key_env")??D4(J,"api_key_env"),W=cS(D4(J,"type")??Y$$($,X,J)),Y={id:$,type:W,base_url:X,auth:Q?{type:"secret_ref",ref:`env:${Q}`}:{type:"none"}},G=D4(J,"default_model")??D4(J,"model")??D4(J,"default");if(G)Y.models=[{id:G}];let z=lS(Mg$(D4(J,"transport"))??D4(J,"api_mode")??iX(W));if(z)Y.api_mode=z;if(Q)Y.runtime_env_name=Q;let H=D4(J,"name");if(H)Y.label=H;return Y}function Y$$($,J,X){let Q=$.toLowerCase(),W=G$$(J).toLowerCase(),Y=D4(X,"transport")??D4(X,"api_mode");if(Q.includes("openrouter")||W.includes("openrouter.ai"))return"openrouter";if(Q.includes("mistral")||W.includes("mistral.ai"))return"mistral";if(Q.includes("gemini")||W.includes("generativelanguage.googleapis.com"))return"gemini";if(Q.includes("anthropic")||W.includes("anthropic.com"))return"anthropic";if(Q.includes("openai")||W.includes("api.openai.com"))return"openai";if(Y==="anthropic_messages")return"anthropic";return"custom_openai_compatible"}function Mg$($){if($==="chat_completions")return"openai_chat";if($==="codex_responses")return"openai_responses";if($==="anthropic_messages")return"anthropic_messages";return}function bg$($){if($==="openai-completions")return"openai_chat";if($==="openai-responses")return"openai_responses";if($==="anthropic-messages")return"anthropic_messages";if($==="google-generative-ai")return"google_generate_content";return}function Ig$($){if(!$)return;let J=$.startsWith("custom:")?$.slice(7):$;return $8(J)?J:void 0}function _g$($){let X=$.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[^a-z]+/,"").replace(/-+/g,"-").replace(/[-.]+$/g,"").slice(0,63).replace(/[-.]+$/g,"");if($8(X))return X;let W=`provider-${X.replace(/^[^a-z0-9]+/,"").slice(0,54).replace(/[-.]+$/g,"")||"custom"}`.slice(0,63).replace(/[-.]+$/g,"");return $8(W)?W:"provider-custom"}function ce($,J){let X=$[J];if(X===void 0||X===null)return;return RJ(X,J)}function fK($,J){let X=$.providers.find((Q)=>Q.id===J);if(!X)throw Error(`AI Provider not found: ${J}`);return X}function RJ($,J){if(typeof $!=="object"||$===null||Array.isArray($))throw Error(`${J} must be an object.`);return $}function D4($,J){let X=$[J];return typeof X==="string"&&X.trim()?X.trim():void 0}function Ag$($){if(!Array.isArray($))return;let J=$[0];if(typeof J==="string")return J;if(typeof J==="object"&&J!==null&&"id"in J){let X=J.id;return typeof X==="string"?X:void 0}return}function Pg$($){let J=$.agents;if(typeof J!=="object"||J===null||Array.isArray(J))return;let X=J.defaults;if(typeof X!=="object"||X===null||Array.isArray(X))return;let Q=X.model,W=typeof Q==="string"?Q:typeof Q==="object"&&Q!==null&&!Array.isArray(Q)?Q.primary:void 0;if(typeof W!=="string")return;let Y=W.split("/")[0];return $8(Y)?{chat_provider_id:Y}:void 0}function le($){if(typeof $!=="object"||$===null||Array.isArray($))return;let J=$;if(J.source!=="env")return;return typeof J.id==="string"?J.id:void 0}function Rg$($){if($.type==="secret_ref")return Cg$($.ref);if($.type==="api_key")return`api_key:${$.source}`;if($.type==="oauth_profile")return`oauth:${$.provider}/${$.profile}`;if($.type==="agent_profile")return`agent:${$.tool}/${$.profile}`;return"none"}function Tg$($,J){let X=$?.trim(),Q=J?[...J]:[];if(X&&!Q.some((W)=>W.id===X))Q.unshift({id:X});return Q.length>0?Q:void 0}function Eg$($){return $.models?.find((J)=>J.id.trim())?.id}function Sg$($){let J=$.models?.map((X)=>X.id).filter(Boolean)??[];if(J.length===0)return"-";if(J.length<=2)return J.join(", ");return`${J.slice(0,2).join(", ")} +${J.length-2}`}function Cg$($){if($.startsWith("env:"))return $;if($.startsWith("clawdi://"))return"clawdi://...";return"redacted"}function G$$($){try{return new URL($).host}catch{return $}}function z$$($,J,X){if(X){console.log(JSON.stringify({[$]:J.id,provider:J},null,2));return}console.log(B.green(`✓ ${kg$($)} AI Provider ${J.id}`)),console.log(B.dim(`Catalog: ${bK()}`))}function xg$($,J){let X=$.map((W,Y)=>Math.max(W.length,...J.map((G)=>G[Y]?.length??0))),Q=(W)=>W.map((Y,G)=>Y.padEnd(X[G]??Y.length)).join(" ");console.log(Q($)),console.log(Q($.map((W)=>"-".repeat(W.length))));for(let W of J)console.log(Q(W))}function kg$($){return`${$.slice(0,1).toUpperCase()}${$.slice(1)}`}var ne="codex",ff$="codex",gf$,uS;var c1=F(()=>{B8();b$();Hw();IS();SS();t$();t4();kK();gf$={host:"localhost",path:"/auth/callback",ports:[1455,1457]};uS=class uS extends Error{constructor(){super("Timed out waiting for OAuth callback.")}}});var Z1={};Y$(Z1,{channelSyncCommandsCommand:()=>ng$,channelSendCommand:()=>lg$,channelRotateTokenCommand:()=>mg$,channelPairCodeCommand:()=>cg$,channelListCommand:()=>vg$,channelLinksCommand:()=>ug$,channelLinkCommand:()=>hg$,channelGetCommand:()=>gg$,channelDeleteCommand:()=>pg$,channelCreateCommand:()=>yg$,channelBindingsCommand:()=>dg$,channelAvailableCommand:()=>fg$});async function vg$($={}){let J=new $$,X=G$(await J.GET("/v1/channels"));if($.json){console.log(JSON.stringify({channels:X},null,2));return}if(X.length===0){console.log("No channels configured."),console.log(B.gray("Create a private bot: clawdi channel create telegram my-bot")),console.log(B.gray("List available channel bots: clawdi channel available"));return}Vw(["ID","PROVIDER","VISIBILITY","STATUS","NAME"],X.map((Q)=>[v3(Q.id),Q.provider,Q.visibility,Q.status,Q.name]))}async function fg$($={}){let J=new $$,X=G$(await J.GET("/v1/channels/bot-pool"));if($.json){console.log(JSON.stringify({bot_pool:X},null,2));return}$y$(X)}async function gg$($,J={}){let X=new $$,Q=G$(await X.GET("/v1/channels/{account_id}",{params:{path:{account_id:$}}}));if(J.json){console.log(JSON.stringify({channel:Q},null,2));return}og$(Q)}async function yg$($,J,X={}){let Q=new $$,W={provider:Xy$($),name:J,agent_id:X.agent??null,provider_token:Gy$(X),config:X.config?Wy$(X.config,"--config"):null,secrets:zy$(X.secret,X.secretEnv)},Y=G$(await Q.POST("/v1/channels",{body:W}));if(X.json){console.log(JSON.stringify({channel:Y},null,2));return}rg$(Y)}async function ug$($,J={}){let X=new $$,Q=G$(await X.GET("/v1/channels/{account_id}/agent-links",{params:{path:{account_id:$}}}));if(J.json){console.log(JSON.stringify({account_id:$,links:Q},null,2));return}if(Q.length===0){console.log("No agent links for this channel."),console.log(B.gray(`Create one: clawdi channel link ${$} --agent <agent-id>`));return}Vw(["LINK ID","AGENT ID","STATUS","CREATED"],Q.map((W)=>[v3(W.id),v3(W.agent_id),W.status,W.created_at]))}async function hg$($,J){let X=new $$,Q=G$(await X.POST("/v1/channels/{account_id}/agent-links",{params:{path:{account_id:$}},body:{agent_id:J.agent}}));if(J.json){console.log(JSON.stringify({link:Q},null,2));return}ig$(Q)}async function mg$($,J){let X=new $$,Q=G$(await X.POST("/v1/channels/{account_id}/agent-links/{link_id}/token",{params:{path:{account_id:$,link_id:J.link}}}));if(J.json){console.log(JSON.stringify({link:Q},null,2));return}ag$(Q)}async function cg$($,J={}){if(J.agent&&J.link){console.error(B.red("Pass either --agent or --link, not both.")),process.exitCode=1;return}let X=Qy$(J.ttl),Q=new $$,W=G$(await Q.POST("/v1/channels/{account_id}/pair-codes",{params:{path:{account_id:$}},body:{agent_id:J.agent??null,agent_link_id:J.link??null,ttl_seconds:X}}));if(J.json){console.log(JSON.stringify({pair_code:W},null,2));return}sg$(W)}async function lg$($,J){if(J.binding&&J.chat){console.error(B.red("Pass either --binding or --chat, not both.")),process.exitCode=1;return}if(!J.binding&&!J.chat){console.error(B.red("Pass --binding or --chat.")),process.exitCode=1;return}let X=new $$,Q=G$(await X.POST("/v1/channels/{account_id}/messages",{params:{path:{account_id:$}},body:{binding_id:J.binding??null,external_chat_id:J.chat??null,text:J.text}}));if(J.json){console.log(JSON.stringify({message:Q},null,2));return}tg$(Q)}async function dg$($,J={}){let X=new $$,Q=G$(await X.GET("/v1/channels/{account_id}/bindings",{params:{path:{account_id:$}}}));if(J.json){console.log(JSON.stringify({account_id:$,bindings:Q},null,2));return}if(Q.length===0){console.log("No paired chats for this channel.");return}Vw(["BINDING ID","CHAT","TYPE","LINK","STATUS"],Q.map((W)=>[v3(W.id),W.external_chat_name??W.external_chat_id,W.external_chat_type??"-",W.agent_link_id?v3(W.agent_link_id):"-",W.status]))}async function ng$($,J={}){let X=new $$,Q=G$(await X.POST("/v1/channels/{account_id}/commands/sync",{params:{path:{account_id:$}},body:{commands:J.commands?Yy$(J.commands):null,guild_id:J.guild??null}}));if(J.json){console.log(JSON.stringify({sync:Q},null,2));return}eg$(Q)}async function pg$($,J={}){if(!J.yes){if(!c0())throw Error("Cannot prompt for channel deletion in a non-interactive shell. Pass --yes to confirm explicitly.");if(!await S2(`Archive channel ${$}?`,!1)){console.log("Cancelled.");return}}let X=new $$;if(G$(await X.DELETE("/v1/channels/{account_id}",{params:{path:{account_id:$}}})),J.json){console.log(JSON.stringify({account_id:$,deleted:!0},null,2));return}console.log(`${B.green("✓")} Archived channel ${$}.`)}function og$($){console.log(`${B.bold($.name)} (${$.provider})`),console.log(` Channel ID: ${$.id}`),console.log(` Visibility: ${$.visibility}`),console.log(` Status: ${$.status}`),console.log(` Has provider token: ${$.has_provider_token?"yes":"no"}`),console.log(` Webhook URL: ${$.webhook_url}`),console.log(` Created: ${$.created_at}`),console.log(B.gray(`List links: clawdi channel links ${$.id}`))}function rg$($){if(console.log(`${B.green("✓")} Created ${$.provider} channel ${B.cyan($.name)}.`),console.log(` Channel ID: ${$.id}`),console.log(` Visibility: ${$.visibility}`),console.log(` Webhook URL: ${$.webhook_url}`),console.log(` Webhook secret: ${$.webhook_secret}`),console.log(B.gray(" Store the webhook secret now; it is shown once.")),$.agent_link_id)console.log(` Agent link ID: ${$.agent_link_id}`);if($.agent_token)console.log(` Agent SDK token: ${$.agent_token}`),console.log(B.gray(" Store the agent token now; it is shown once."));console.log(B.gray(`Generate a pair code: clawdi channel pair-code ${$.id}`))}function ig$($){if(console.log(`${B.green("✓")} Linked channel to agent.`),console.log(` Link ID: ${$.id}`),console.log(` Agent ID: ${$.agent_id}`),$.agent_token)console.log(` Agent SDK token: ${$.agent_token}`);console.log(B.gray(" Store the agent token now; it is shown once.")),console.log(B.gray(`Pair an external chat: clawdi channel pair-code ${$.account_id} --link ${$.id}`))}function ag$($){if(console.log(`${B.green("✓")} Rotated agent link token.`),console.log(` Link ID: ${$.id}`),console.log(` Agent ID: ${$.agent_id}`),$.agent_token)console.log(` Agent SDK token: ${$.agent_token}`),console.log(B.gray(" Store the new token now; it is shown once."))}function sg$($){if(console.log(`${B.green("✓")} Pair code created.`),console.log(` Code: ${B.cyan($.code)}`),console.log(` Agent link ID: ${$.agent_link_id}`),console.log(` Agent ID: ${$.agent_id}`),$.agent_token)console.log(` Agent SDK token: ${$.agent_token}`);console.log(` Expires at: ${$.expires_at}`),console.log(B.gray(`Send this in the external chat: ${$.pairing_command}`))}function tg$($){if(console.log(`${B.green("✓")} Queued outbound message.`),console.log(` Message ID: ${$.id}`),console.log(` Chat: ${$.external_chat_id}`),$.delivery_id)console.log(` Delivery ID: ${$.delivery_id}`);if($.delivery_status)console.log(` Delivery status: ${$.delivery_status}`)}function eg$($){if(console.log(`${B.green("✓")} Synced ${$.provider} commands.`),$.commands.length===0)return;Vw(["COMMAND","DESCRIPTION"],$.commands.map((J)=>[V$$(J.name??J.command??"-"),V$$(J.description??"-")]))}function $y$($){let J=Object.entries($.providers).flatMap(([X,Q])=>Q.map((W)=>[v3(W.id),X,W.access,W.visibility,W.status,Jy$(W.capabilities),W.name]));if(J.length===0){console.log("No available channel bots.");return}Vw(["ID","PROVIDER","ACCESS","VISIBILITY","STATUS","CAPABILITIES","NAME"],J)}function Jy$($){let J=[];if($.link_agent)J.push("link");if($.pair_chat)J.push("pair");if($.send_message)J.push("send");if($.manage_account)J.push("manage");if($.sync_commands)J.push("sync");return J.join(",")}function Xy$($){if($==="telegram"||$==="discord"||$==="whatsapp")return $;throw Error("provider must be one of: telegram, discord, whatsapp")}function Qy$($){if($===void 0)return 300;let J=Number($);if(!Number.isInteger(J)||J<60||J>86400)throw Error("--ttl must be an integer number of seconds between 60 and 86400.");return J}function Wy$($,J){let X;try{X=JSON.parse($)}catch{throw Error(`${J} must be valid JSON.`)}if(!q$$(X))throw Error(`${J} must be a JSON object.`);return X}function Yy$($){let J;try{J=JSON.parse($)}catch{throw Error("--commands must be valid JSON.")}if(!Array.isArray(J))throw Error("--commands must be a JSON array.");return J.map((X,Q)=>{if(!q$$(X))throw Error(`--commands[${Q}] must be a JSON object.`);return X})}function Gy$($){if($.providerToken&&$.providerTokenEnv)throw Error("Pass only one of --provider-token or --provider-token-env.");if($.providerTokenEnv)return U$$($.providerTokenEnv,"--provider-token-env");return $.providerToken??null}function zy$($,J){if((!$||$.length===0)&&(!J||J.length===0))return null;let X={};for(let Q of $??[]){let[W,Y]=H$$(Q,"--secret");w$$(X,W,Y)}for(let Q of J??[]){let[W,Y]=H$$(Q,"--secret-env");w$$(X,W,U$$(Y,"--secret-env"))}return X}function H$$($,J){let X=$.indexOf("=");if(X<=0)throw Error(`${J} must use NAME=value.`);let Q=$.slice(0,X).trim(),W=$.slice(X+1);if(!Q||!W)throw Error(`${J} must use NAME=value with non-empty name and value.`);return[Q,W]}function w$$($,J,X){if(Object.hasOwn($,J))throw Error(`Duplicate secret name: ${J}.`);$[J]=X}function U$$($,J){let X=$.trim();if(!X)throw Error(`${J} requires a non-empty environment variable name.`);let Q=process.env[X];if(Q===void 0||Q==="")throw Error(`${J} ${X} is not set or is empty.`);return Q}function q$$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function V$$($){if(typeof $==="string")return $;if($===null||$===void 0)return"-";return JSON.stringify($)}function v3($){return $.length>12?$.slice(0,8):$}function Vw($,J){let X=$.map((Q,W)=>Math.max(Q.length,...J.map((Y)=>Y[W]?.length??0)));console.log($.map((Q,W)=>B.bold(Q.padEnd(X[W]))).join(" "));for(let Q of J)console.log(Q.map((W,Y)=>W.padEnd(X[Y])).join(" "))}var B1=F(()=>{b$();t$();yH()});import{readFileSync as Hy$,rmSync as wy$}from"node:fs";function gK($){try{return B$$(Hy$($.daemonAuthToken,"utf-8"))}catch{return null}}function Vy$($,J){let X=B$$(J);if(!X)throw Error("runtime auth token must be non-empty and contain no control characters");return e4($,$.daemonAuthToken,`${X}
487
- `,{mode:f4,dirMode:K4}),$.daemonAuthToken}function Uy$($){return a4($,dS)}function Z$$($,J){let X=Uy$(J);if(X)return Vy$($,X);return wy$($.daemonAuthToken,{force:!0}),null}function B$$($){let J=$.trim();if(!J)return null;for(let X of J){let Q=X.charCodeAt(0);if(Q<=31||Q===127)return null}return J}var dS="secret://clawdi/auth-token";var nS=F(()=>{t4();L9();e6()});import{isAbsolute as qy$}from"node:path";function T9($,J){if($.projection?.sourceBundleVersion==="clawdi.hosted-runtime.bundle.v2")return J.userHome;let X=$.projection?.system;if(typeof X!=="object"||X===null||Array.isArray(X))return J.userHome;let Q=X.home;if(typeof Q!=="string")return J.userHome;let W=Q.trim();return W&&qy$(W)?W:J.userHome}var pS=()=>{};function qw($){let J=oS($),X=oS(J?.authCert),Q=oS(X?.PUBLIC_KEY),W=J?.capability,Y=X?.ISSUER,G=X?.SERIAL,z=Q?.data;if(!J||!rS(J,["authCert","capability","schemaVersion"])||J.schemaVersion!=="clawdi.managedWhatsAppSocket.v1"||typeof W!=="string"||!/^clawdi_[a-f0-9]{32}$/.test(W)||!X||!rS(X,["ISSUER","PUBLIC_KEY","SERIAL"])||typeof G!=="number"||!Number.isSafeInteger(G)||G<0||typeof Y!=="string"||Y.length===0||Y.trim()!==Y||Y.length>256||!Q||!rS(Q,["data","type"])||Q.type!=="Buffer"||typeof z!=="string"||!Zy$(z,32))throw Error("invalid Clawdi managed WhatsApp socket metadata");return{schemaVersion:"clawdi.managedWhatsAppSocket.v1",capability:W,authCert:{SERIAL:G,ISSUER:Y,PUBLIC_KEY:{type:"Buffer",data:z}}}}function oS($){return $&&typeof $==="object"&&!Array.isArray($)?$:null}function rS($,J){return Object.keys($).sort().join("\x00")===[...J].sort().join("\x00")}function Zy$($,J){let X=Buffer.from($,"base64");return X.length===J&&X.toString("base64")===$}var f3="x-clawdi-whatsapp-link-capability",Uw="clawdi.managedWhatsAppSocket",iS="clawdi.managedWhatsAppSocket.v1";import{createHash as By$}from"node:crypto";function K$$($){let J=Ky$($.controlPlaneApiUrl),X=[...$.links].sort((Q,W)=>Q.linkId.localeCompare(W.linkId)).map((Q)=>({id:`native-whatsapp-baileys-${Ly$(Q.linkId)}`,enabled:!0,kind:"websocket",match:{scheme:"wss",host:"web.whatsapp.com",path:{type:"equals",value:"/ws/chat"},headers:{[f3]:{type:"secretRefEquals",secretRef:Q.capabilitySecretRef}},query:{}},rewrite:{upstreamBaseUrl:J,preservePath:!1,removeHeaders:[f3],setHeaders:{authorization:{type:"secretRef",secretRef:Q.agentTokenSecretRef,prefix:"Bearer "}}},logging:{redactHeaders:[f3,"authorization"],redactUrlPatterns:[]},priority:40,owner:"clawdi-native-whatsapp",description:"Route one authenticated managed native Baileys websocket."}));return X.push({id:"native-whatsapp-baileys-invalid-capability",enabled:!0,kind:"deny",match:{host:"web.whatsapp.com",headers:{[f3]:{type:"exists"}},query:{}},logging:{redactHeaders:[f3],redactUrlPatterns:[]},priority:49,owner:"clawdi-native-whatsapp",description:"Fail closed when a managed WhatsApp capability is misplaced, stale, or invalid."}),X}function Ky$($){let J=new URL($);if(J.protocol==="https:")J.protocol="wss:";else if(J.protocol==="http:")J.protocol="ws:";else throw Error("WhatsApp egress control plane URL must use HTTP or HTTPS");return J.pathname="/v1/channels/whatsapp/baileys",J.search="",J.hash="",J.toString()}function Ly$($){return By$("sha256").update($).digest("hex").slice(0,16)}var L$$=()=>{};import{createHash as Ny$}from"node:crypto";import{join as F$$}from"node:path";function sS($,J=w$({mode:"hosted"})){if(!$.channelBindings)return $;let X=$.secretValues??{},Q=$.channelBindings.map((G)=>Fy$(G,X)),W=My$($.manifest,Q,J),Y=vy$(Q.filter((G)=>G.account.provider==="whatsapp"),W.projection?.channelCredentials);return{...$,manifest:W,sourceManifest:$.sourceManifest??$.manifest,secretValues:{...X,...Y}}}function Fy$($,J){let X=a4(J,$.agentTokenSecretRef),Q=a4(J,$.placeholderTokenSecretRef);if(!X)throw Error(`runtime bundle is missing ${$.agentTokenSecretRef}`);if(!Q)throw Error(`runtime bundle is missing ${$.placeholderTokenSecretRef}`);if($.provider==="whatsapp"){let W=gy$($.accountKey,$.linkId),Y=yy$($.accountKey,$.linkId),G=tS($.accountKey,$.linkId);if($.agentTokenSecretRef!==W)throw Error("runtime bundle WhatsApp agent token ref does not match its Link");if($.placeholderTokenSecretRef!==Y)throw Error("runtime bundle WhatsApp capability ref does not match its Link");if(Q!==G)throw Error("runtime bundle WhatsApp capability does not match its Link")}return{account:{id:$.provider==="whatsapp"?$.accountId:$.accountKey,provider:$.provider},accountKey:$.accountKey,linkId:$.provider==="whatsapp"?$.linkId:$.accountKey,secretRef:$.agentTokenSecretRef,placeholderSecretRef:$.placeholderTokenSecretRef,credential:$.provider==="whatsapp"?jy$($,J):void 0}}function jy$($,J){let X=$.credential.credsSecretRef,Q=uy$($.accountKey,$.credential.id);if(X!==Q)throw Error("runtime bundle WhatsApp credential ref does not match its credential");let W=a4(J,X);if(!W)throw Error(`runtime bundle is missing ${X}`);let Y;try{Y=JSON.parse(W)}catch(z){throw Error(`runtime bundle WhatsApp credential is invalid: ${z instanceof Error?z.message:String(z)}`)}let G=yK(Y);if(!G)throw Error("runtime bundle WhatsApp credential must be a JSON object");return{id:$.credential.id,credsSecretRef:X,material:{schemaVersion:"clawdi.whatsappBaileysAuthState.v1",creds:G,authCert:$.credential.authCert}}}function My$($,J,X){let Q=Cy$(J,$.controlPlane.apiUrl),W=T9($,X),Y=ly$($),G=Iy$(J,W,Y),z={...$,projection:{...$.projection??{},channels:by$(J,W,Y),channelCredentials:G},egressProfiles:xy$($.egressProfiles,Q)};return Ay$(_y$(z,J),J)}function by$($,J,X){let Q={};for(let W of $){let Y=W.account.provider;if(Y==="telegram"){let G=aS(Q,"telegram",W.accountKey);G.accounts[W.accountKey]={enabled:!0,botToken:N$$(W),dmPolicy:"open",groupPolicy:"open",allowFrom:["*"],capabilities:{inlineButtons:"all"},groups:{"*":{requireMention:!1}}};continue}if(Y==="discord"){let G=aS(Q,"discord",W.accountKey);G.accounts[W.accountKey]={enabled:!0,token:N$$(W),dmPolicy:"open",groupPolicy:"open",allowFrom:["*"],guilds:{"*":{requireMention:!1,users:["*"]}},actions:{stickers:!1,polls:!1,threads:!1,pins:!1,roles:!1,voiceStatus:!1,events:!1,moderation:!1,emojiUploads:!1,stickerUploads:!1,channels:!1,presence:!1}};continue}if(Y==="whatsapp"){let G=aS(Q,"whatsapp",W.accountKey),z=I$$(W,J,X);G.accounts[W.accountKey]={enabled:!0,...z?.targets.openclaw?{authDir:z.targets.openclaw.authDir}:{},dmPolicy:"allowlist",allowFrom:["*"],groupPolicy:"open",groupAllowFrom:["*"],groups:{"*":{requireMention:!1}}}}}return Q}function Iy$($,J,X){return $.map((Q)=>I$$(Q,J,X)).filter((Q)=>Q!==null).sort((Q,W)=>`${Q.provider}:${Q.accountKey}:${Q.credentialId}`.localeCompare(`${W.provider}:${W.accountKey}:${W.credentialId}`))}function _y$($,J){let X=$.runtimes.openclaw;if(!X?.enabled)return $;Py$(J);let Q=X.run??{env:{},prependPath:[]},W=Ty$(Q.secretEnv??{});for(let Y of J)W[b$$(Y)]=Y.placeholderSecretRef;if(!X.run&&Object.keys(W).length===0)return $;return{...$,runtimes:{...$.runtimes,openclaw:{...X,run:{...Q,secretEnv:W}}}}}function Ay$($,J){let X=$.runtimes.hermes;if(!X?.enabled)return $;let Q=Zw(J,"telegram"),W=Zw(J,"discord"),Y=Zw(J,"whatsapp"),G=X.run??{env:{},prependPath:[]},z=D$$(G.env??{},Oy$),H=D$$(G.secretEnv??{},Dy$);if(Q)z.TELEGRAM_ALLOW_ALL_USERS="true",z.HERMES_TELEGRAM_DISABLE_FALLBACK_IPS="true",H.TELEGRAM_BOT_TOKEN=Q.placeholderSecretRef;if(W)z.DISCORD_ALLOW_ALL_USERS="true",H.DISCORD_BOT_TOKEN=W.placeholderSecretRef;if(Y)z.WHATSAPP_MODE="bot",z.WHATSAPP_ALLOWED_USERS="*";return{...$,runtimes:{...$.runtimes,hermes:{...X,run:{...G,env:z,secretEnv:H}}}}}function Zw($,J){let X=$.filter((Q)=>Q.account.provider===J);if(X.length>1)throw Error(Ry$(J));return X[0]??null}function Py$($){for(let J of["telegram","discord","whatsapp"])Zw($,J)}function Ry$($){return`This Agent has multiple active ${$==="telegram"?"Telegram":$==="discord"?"Discord":$} bots. Unlink the extras until only one remains.`}function N$$($){return{source:"env",provider:"default",id:b$$($)}}function b$$($){return`${j$$}${O$$($.account.provider)}_${O$$($.accountKey)}${M$$}`}function O$$($){return $.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"CHANNEL"}function Ty$($){return Object.fromEntries(Object.entries($).filter(([J])=>!Ey$(J)))}function Ey$($){return $.startsWith(j$$)&&$.endsWith(M$$)}function D$$($,J){let X=new Set(J),Q={};for(let[W,Y]of Object.entries($))if(!X.has(W))Q[W]=Y;return Q}function aS($,J,X){let Q=$[J];if(Sy$(Q))return Q;let W={enabled:!0,defaultAccount:X,accounts:{}};return $[J]=W,W}function Sy$($){return typeof $==="object"&&$!==null&&!Array.isArray($)&&typeof $.accounts==="object"&&$.accounts!==null&&!Array.isArray($.accounts)}function Cy$($,J){let X=ny$(J),Q=[];for(let Y of $){let G=`${Y.account.provider}-${Y.accountKey}`;if(Y.account.provider==="telegram")for(let z of[{id:`native-${G}-managed`,pathPrefix:"/bot"},{id:`native-${G}-file-managed`,pathPrefix:"/file/bot"}])Q.push({id:z.id,enabled:!0,kind:"http",match:{scheme:"https",host:"api.telegram.org",pathPrefix:z.pathPrefix,path:{type:"secretRefPrefix",secretRef:Y.placeholderSecretRef,prefix:z.pathPrefix,suffix:"/"},headers:{},query:{}},rewrite:{upstreamBaseUrl:`${X}/v1/channels/telegram`,preservePath:!0,setHeaders:{authorization:{type:"secretRef",secretRef:Y.secretRef,prefix:"Bearer "}}},logging:{redactHeaders:["authorization"],redactUrlPatterns:[]},priority:100,owner:"clawdi-native-channels"});if(Y.account.provider==="discord")Q.push({id:`native-${G}-rest-managed`,enabled:!0,kind:"http",match:{scheme:"https",host:"discord.com",pathPrefix:"/api/",headers:{authorization:{type:"secretRefEquals",secretRef:Y.placeholderSecretRef,prefix:"Bot "}},query:{}},rewrite:{upstreamBaseUrl:`${X}/v1/channels/discord`,preservePath:!0,setHeaders:{authorization:{type:"secretRef",secretRef:Y.secretRef,prefix:"Bot "}}},logging:{redactHeaders:["authorization"],redactUrlPatterns:[]},priority:101,owner:"clawdi-native-channels"}),Q.push({id:`native-${G}-gateway-managed`,enabled:!0,kind:"websocket",match:{scheme:"wss",host:"gateway.discord.gg",pathPrefix:"/",headers:{},query:{}},rewrite:{upstreamBaseUrl:`${py$(X)}/v1/channels/discord/gateway`,preservePath:!1,setHeaders:{authorization:{type:"secretRef",secretRef:Y.secretRef,prefix:"Bearer "}}},logging:{redactHeaders:["authorization"],redactUrlPatterns:[]},priority:201,owner:"clawdi-native-channels"})}let W=Zw($,"whatsapp");if(W&&!eS(W))throw Error(`managed WhatsApp Link ${W.linkId} has no valid synthetic auth`);return Q.push(...K$$({controlPlaneApiUrl:J,links:W?[{linkId:W.linkId,agentTokenSecretRef:W.secretRef,capabilitySecretRef:W.placeholderSecretRef}]:[]})),Q}function xy$($,J){let X=[...$?.profiles??[]],Q=new Set(J.map((W)=>W.id));return{profiles:[...X.filter((W)=>!Q.has(W.id)&&!ky$(W)),...J]}}function ky$($){return $.owner==="clawdi-native-channels"||$.owner==="clawdi-native-whatsapp"||$.id==="direct-provider-passthrough"||$.id.startsWith("direct-provider-passthrough-")}function vy$($,J){let X={},Q=fy$(J);for(let W of $){let Y=eS(W);if(Y){let G=Y.credential.credsSecretRef;if(Q.has(G))X[G]=JSON.stringify(hy$(W,Y))}}return X}function fy$($){let J=new Set;if(!Array.isArray($))return J;for(let X of $){let Q=yK(X);if(Q?.provider!=="whatsapp"||Q.kind!=="whatsapp_baileys_auth_state")continue;let W=Array.isArray(Q.files)?Q.files:[];for(let Y of W){let G=yK(Y),z=dy$(G?.secretRef);if(G?.path==="creds.json"&&z)J.add(z)}}return J}function gy$($,J){return`secret://channels/whatsapp/${$}/links/${J}/agent-token`}function yy$($,J){return`secret://channels/whatsapp/${$}/links/${J}/egress-capability`}function uy$($,J){return`secret://channels/whatsapp/${$}/credentials/${J}/creds-json`}function tS($,J){return`clawdi_${Ny$("sha256").update(`whatsapp:${$}:${J}`).digest("hex").slice(0,32)}`}function I$$($,J,X){let Q=eS($);if(!Q)return null;let W=my$(J,$.accountKey),Y=cy$(J),G={};if(X.openclaw)G.openclaw={authDir:W};if(X.hermes)G.hermes={authDir:Y};let z=G.openclaw?.authDir??G.hermes?.authDir;if(!z)return null;return{provider:"whatsapp",kind:"whatsapp_baileys_auth_state",accountId:$.account.id,accountKey:$.accountKey,linkId:$.linkId,credentialId:Q.credential.id,authDir:z,files:[{path:"creds.json",secretRef:Q.credential.credsSecretRef}],targets:G}}function eS($){if($.account.provider!=="whatsapp")return null;let J=$.credential;if(!J)return null;let{material:X}=J,Q;try{Q=qw({schemaVersion:iS,capability:tS($.accountKey,$.linkId),authCert:X.authCert})}catch{return null}return{credential:J,creds:X.creds,authCert:Q.authCert}}function hy$($,J){let X=J.creds.additionalData,Q=X===void 0?{}:yK(X);if(!Q)throw Error("managed WhatsApp synthetic creds.additionalData must be an object");let W=qw({schemaVersion:iS,capability:tS($.accountKey,$.linkId),authCert:J.authCert});return{...J.creds,additionalData:{...Q,[Uw]:W}}}function my$($,J){return F$$($,".openclaw","credentials","whatsapp",J)}function cy$($){return F$$($,".hermes","platforms","whatsapp","session")}function ly$($){return{openclaw:$.runtimes.openclaw?.enabled===!0,hermes:$.runtimes.hermes?.enabled===!0}}function yK($){if(!$||typeof $!=="object"||Array.isArray($))return null;return $}function dy$($){return typeof $==="string"&&$.trim().length>0?$.trim():null}function ny$($){return $.replace(/\/+$/,"")}function py$($){if($.startsWith("https://"))return`wss://${$.slice(8)}`;if($.startsWith("http://"))return`ws://${$.slice(7)}`;return $}var Oy$,Dy$,j$$="CLAWDI_CHANNEL_",M$$="_AGENT_TOKEN";var _$$=F(()=>{w0();pS();L9();L$$();Oy$=["TELEGRAM_ALLOW_ALL_USERS","DISCORD_ALLOW_ALL_USERS","HERMES_TELEGRAM_DISABLE_FALLBACK_IPS","WHATSAPP_MODE","WHATSAPP_ALLOWED_USERS"],Dy$=["TELEGRAM_BOT_TOKEN","DISCORD_BOT_TOKEN"]});import{dirname as A$$,isAbsolute as P$$,relative as oy$,resolve as $C}from"node:path";function ay$(){return process.env.CLAWDI_RUNTIME_MODE?.trim().toLowerCase()||"missing"}function QC($,J={}){let X=J.expectedIdentity??R$$,Q=ay$(),W=Q==="hosted"&&$.mode==="hosted"?void 0:`hosted convergence requires CLAWDI_RUNTIME_MODE=hosted explicitly; resolved runtime mode is ${$.mode} (environment: ${Q})`,Y=$.userHome===X.home?void 0:`hosted runtime HOME must resolve to ${X.home}; resolved ${$.userHome}`,G=process.env.CLAWDI_RUNTIME_USER?.trim()??"",z,H=G||"missing";if(G!==X.user)z=G?`hosted runtime user must be ${X.user}; resolved ${G}`:`hosted runtime user must be ${X.user}; CLAWDI_RUNTIME_USER is missing`;else try{let w=(J.resolveUserIdentity??fn)(G);if(H=`${G} (${w.uid}:${w.gid})`,w.uid===0||w.gid===0)z=`hosted runtime user ${G} resolved to root identity ${w.uid}:${w.gid}`;else if(w.uid!==X.uid||w.gid!==X.gid)z=`hosted runtime user ${G} must resolve to ${X.uid}:${X.gid}; resolved ${w.uid}:${w.gid}`;else for(let[V,U,q]of[["CLAWDI_RUNTIME_UID",process.env.CLAWDI_RUNTIME_UID?.trim(),w.uid],["CLAWDI_RUNTIME_GID",process.env.CLAWDI_RUNTIME_GID?.trim(),w.gid]])if(U&&U!==String(q)){z=`${V} must match the resolved hosted runtime identity ${q}; resolved ${U}`;break}}catch(w){z=w instanceof Error?w.message:String(w)}return{mode:{ok:W===void 0,detail:$.mode,...W?{error:W}:{}},home:{ok:Y===void 0,detail:$.userHome,...Y?{error:Y}:{}},user:{ok:z===void 0,detail:H,...z?{error:z}:{}}}}function Bw($,J,X={}){let Q=QC($,X),W=[Q.mode,Q.home,Q.user].find((H)=>!H.ok)?.error;if(W)throw Error(W);let Y=$C($.clawdiHome),G=$C($.serviceStateRoot),z=oy$($C($.userHome),Y);if(z===""||!z.startsWith("..")&&!P$$(z))throw Error(`hosted CLAWDI_HOME must be outside the tenant home; resolved ${$.clawdiHome}`);if(!P$$($.clawdiHome)||Y===G||A$$(Y)!==A$$(G))throw Error(`hosted CLAWDI_HOME must be an absolute sibling of ${$.serviceStateRoot}; resolved ${$.clawdiHome}`);if(J.backend!=="incus")throw Error(`hosted v2 convergence requires runtime context backend incus; resolved ${String(J.backend??"missing")}`);if(X.platformRoots!=="deferred")hW($);return{identity:X.expectedIdentity??R$$,assertPlatformRoots:()=>hW($)}}var JC="/home/clawdi",XC="clawdi",ry$=10001,iy$=10001,R$$;var uK=F(()=>{V1();e6();R$$={home:JC,user:XC,uid:ry$,gid:iy$}});import{spawnSync as YC}from"node:child_process";import{createHash as sy$}from"node:crypto";import{accessSync as ty$,constants as ey$,existsSync as C$$,lstatSync as $u$,mkdirSync as Ju$,mkdtempSync as Xu$,readdirSync as Qu$,readFileSync as x$$,readlinkSync as k$$,renameSync as Wu$,rmSync as Lw,statSync as Yu$,symlinkSync as Gu$}from"node:fs";import{tmpdir as zu$}from"node:os";import{dirname as O8,join as N8,resolve as C9}from"node:path";function v$$($){if($.mode!=="hosted"||$.userHome!==JC||process.env.CLAWDI_RUNTIME_USER?.trim()!==XC||typeof process.geteuid==="function"&&process.geteuid()!==0)return;let J;try{J=$u$(Kw)}catch(Q){if(Q.code==="ENOENT")return;throw Q}if(!J.isSymbolicLink())throw Error(`hosted tenant PATH contains an unmanaged clawdi entrypoint: ${Kw}`);let X=C9(O8(Kw),k$$(Kw));if(X!==qu$)throw Error(`hosted tenant PATH contains an unmanaged clawdi symlink target: ${X}`);Lw(Kw)}function f$$($,J,X={}){let Q=pK(J,X);if(Q.selfReexec){let V=y3(J.cliBootstrapStatus);return g3("deferred",J,{packageSpec:$.clawdiCli?.packageSpec?.trim()||null,registry:V?.registry??null,npmPrefix:V?.npmPrefix??J.cliNpmPrefix,activeTarget:V?.activeTarget??null,version:V?.version??null,error:`CLI transaction recovery ${Q.status}; re-exec is required`},!0)}let W=$.clawdiCli?.packageSpec?.trim();if(!W)return g3("not_requested",J,{packageSpec:null,registry:null,activeTarget:null,version:null});Nu$(W);let Y=Lu$($),G=y3(J.cliBootstrapStatus);if(Ou$(G,J,W,Y))return g3("current",J,{packageSpec:W,registry:Y,npmPrefix:G.npmPrefix??Nw(G.activeTarget),activeTarget:G.activeTarget??null,version:G.version??null});let z=ju$(J,W);if(z)return s5(J,{packageSpec:W,registry:Y,npmPrefix:z.npmPrefix,activeTarget:z.activeTarget,version:z.version},z.verification),g3("current",J,{packageSpec:W,registry:Y,npmPrefix:z.npmPrefix,activeTarget:z.activeTarget,version:z.version});if(X.deferInstall)return g3("deferred",J,{packageSpec:W,registry:Y,npmPrefix:G?.npmPrefix??J.cliNpmPrefix,activeTarget:G?.activeTarget??null,version:G?.version??null,error:X.deferReason??"CLI install retry is in backoff"});let H=Fu$(J,G);if(H&&m6(J.cliManagedBin)===H.activeTarget&&(G?.status!=="installed"||G.source!=="npm"||G.packageSpec!==H.packageSpec||(G.registry??null)!==H.registry||G.npmPrefix!==H.npmPrefix||G.activePath!==J.cliManagedBin||G.activeTarget!==H.activeTarget||G.version!==H.version)){let V=S9(J,H);if(!V)throw Error("active clawdi CLI changed during verification");s5(J,H,V)}let w=Mu$(J,W,Y);return Iu$(J,{newIdentity:{packageSpec:W,registry:Y,npmPrefix:w.npmPrefix,activeTarget:w.activeTarget,version:w.version},previousIdentity:H,rollbackEligible:X.rollbackEligible===!0&&H!==null}),u$$(J.cliManagedBin,w.activeTarget),s5(J,{packageSpec:W,registry:Y,npmPrefix:w.npmPrefix,activeTarget:w.activeTarget,version:w.version},w.verification),m$$(J),u3(J,[w.npmPrefix,H?.npmPrefix??null]),g3("installed",J,{packageSpec:W,registry:Y,npmPrefix:w.npmPrefix,activeTarget:w.activeTarget,version:w.version},!0)}function g3($,J,X,Q=!1){return{status:$,...X,npmPrefix:X.npmPrefix??J.cliNpmPrefix,npmCache:X.npmCache??J.cliNpmCache,activePath:J.cliManagedBin,selfReexec:Q}}function Lu$($){let J=$.clawdiCli?.registry;if(typeof J!=="string"||!J.trim())return null;let X=J.trim(),Q;try{let W=new URL(X);W.pathname=W.pathname.replace(/\/+$/,""),W.search="",W.hash="",Q=W.toString().replace(/\/$/,"")}catch{throw Error(`unsupported clawdi CLI registry: ${X}`)}if(Q!=="https://registry.npmjs.org")throw Error(`unsupported clawdi CLI registry: ${X}`);return"https://registry.npmjs.org"}function Nu$($){if(nz.safeParse($).success)return;throw Error(`clawdi CLI packageSpec must be clawdi@<exact-semver> or a managed bootstrap tarball: ${$}`)}function y3($){if(!C$$($))return null;try{let J=JSON.parse(x$$($,"utf-8"));if(typeof J!=="object"||J===null||Array.isArray(J))return null;return J}catch{return null}}function pQ($){Ju$($,{recursive:!0})}function GC($,J){let X=C9($.cliNpmPrefix),Q=C9(J);return Q===X||Q.startsWith(`${X}/`)}function lK($,J){return GC($,J)&&J.endsWith("/bin/clawdi")}function Ou$($,J,X,Q){if(!$)return!1;if($.status!=="installed"||$.source!=="npm")return!1;if($.activePath!==J.cliManagedBin)return!1;if(!$.activeTarget)return!1;if(!lK(J,$.activeTarget))return!1;if(m6(J.cliManagedBin)!==$.activeTarget)return!1;if(!$.npmPrefix||C9($.npmPrefix)!==C9(Nw($.activeTarget)))return!1;if(!t5($.activeTarget))return!1;if(!$.version)return!1;let W=h3(X);if(W&&$.version!==W)return!1;let Y=process.env.CLAWDI_RUNTIME_ALLOW_TEST_INSTALLERS==="1"&&$.packageSpec===z8&&W===$.version;if($.packageSpec!==X&&!Y)return!1;if(($.registry??null)!==Q)return!1;if(!t5(J.cliManagedBin))return!1;let G=oQ($.activeTarget);if(G&&$.verification&&dK($.verification,G)&&y$$($.verification))return!0;if(!G)return!1;try{if(Dw($.activeTarget)!==$.version)return!1;Fw($.activeTarget);let z=Ow($.activeTarget,G);return s5(J,{packageSpec:Y?z8:X,registry:Q,npmPrefix:$.npmPrefix,activeTarget:$.activeTarget,version:$.version},z),!0}catch{return!1}}function Du$($,J){let X=m6($.cliManagedBin);if(!X||!lK($,X))return null;let Q=Nw(X);if(!GC($,Q))return null;if(!t5(X)||!t5($.cliManagedBin))return null;try{let W=oQ(X);if(!W)return null;let Y=Dw(X);Fw(X),Ow(X,W);let G=`clawdi@${Y}`;if(!o7.safeParse(G).success)return null;let z=J?.packageSpec,H=J?.registry??null,w=z?h3(z):null,V=J?.status==="installed"&&J.source==="npm"&&J.activePath===$.cliManagedBin&&J.activeTarget===X&&J.npmPrefix!==void 0&&C9(J.npmPrefix)===C9(Q)&&J.version===Y&&z!==void 0&&nz.safeParse(z).success&&(w===null||w===Y)&&(H===null||H==="https://registry.npmjs.org");return{packageSpec:V&&z?z:G,registry:V?H:null,npmPrefix:Q,activeTarget:X,version:Y}}catch{return null}}function Fu$($,J){let X=Du$($,J);if(!X)return null;let Q=TJ($).transaction;if(Q?.phase!=="activated"||Q.rollback||!Q.rollbackEligible||!Q.previousIdentity||Q.newIdentity.activeTarget!==X.activeTarget)return X;return S9($,Q.previousIdentity)?Q.previousIdentity:X}function ju$($,J){let X=h3(J);if(!X)return null;let Q=g$$($,X),W=m6($.cliManagedBin);if(W!==N8(Q,"bin","clawdi"))return null;if(!lK($,W))return null;if(!t5(W)||!t5($.cliManagedBin))return null;let Y=oQ(W);if(!Y)return null;let G=Dw(W);if(G!==X)return null;Fw(W);let z=Ow(W,Y);return{npmPrefix:Nw(W),activeTarget:W,version:G,verification:z}}function h3($){if(!o7.safeParse($).success)return null;return $.slice(7)}function Mu$($,J,X){let Q=bu$($,J,X);if(Pu$($,J,X,Q.version))throw Error(`clawdi CLI ${Q.version} is marked bad after rollback; waiting for a newer resolved version`);let W=Q.npmPrefix;pQ(O8(O8($.cliManagedBin))),pQ(O8($.cliManagedBin)),pQ($.cliNpmPrefix),pQ(W),pQ($.cliNpmCache);let Y=["install","-g","--prefix",W,"--cache",$.cliNpmCache,"--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?["--registry",X]:[],Q.installPackageSpec],G=YC("npm",Y,{encoding:"utf8",timeout:Hu$,env:{...process.env,NO_UPDATE_NOTIFIER:"1",NPM_CONFIG_UPDATE_NOTIFIER:"false"}});if(G.status!==0)throw Error(`npm install ${Q.installPackageSpec} failed${G.status===null?"":` (${G.status})`}${G.error?`: ${G.error.message}`:""}${mK(G.stdout,G.stderr)}`);let z=`${W}/bin/clawdi`;if(!t5(z))throw Error(`npm install completed but clawdi bin is missing: ${z}`);let H=oQ(z);if(!H)throw Error(`installed clawdi bin disappeared before verification: ${z}`);let w=Dw(z),V=h3(J);if(V&&w!==V)throw Error(`npm install ${Q.installPackageSpec} reported version ${w}, expected ${V}`);Fw(z);let U=Ow(z,H);return{npmPrefix:W,activeTarget:z,version:w,verification:U}}function bu$($,J,X){let Q=h3(J);if(Q)return{installPackageSpec:`clawdi@${Q}`,npmPrefix:g$$($,Q),version:Q};let W=sy$("sha256").update(JSON.stringify({packageSpec:J,registry:X})).digest("hex").slice(0,16);return{installPackageSpec:J,npmPrefix:N8($.cliNpmPrefix,"packages",`tarball-${W}`),version:`tarball-${W}`}}function g$$($,J){if(!/^[0-9A-Za-z._+-]+$/.test(J))throw Error(`resolved clawdi CLI version contains unsafe path characters: ${J}`);return N8($.cliNpmPrefix,"packages",J)}function Nw($){return O8(O8($))}function oQ($){try{let J=Yu$($);return{device:J.dev,inode:J.ino,size:J.size,modifiedAtMs:J.mtimeMs}}catch{return null}}function dK($,J){return $.device===J.device&&$.inode===J.inode&&$.size===J.size&&$.modifiedAtMs===J.modifiedAtMs}function y$$($){let J=Date.parse($.verifiedAt),X=Date.now()-J;return Number.isFinite(J)&&X>=0&&X<Uu$}function Ow($,J){let X=oQ($);if(!X||!dK(J,X))throw Error(`clawdi CLI target changed during verification: ${$}`);return{verifiedAt:new Date().toISOString(),...X}}function m6($){try{return C9(O8($),k$$($))}catch{return null}}function u3($,J){let X=N8($.cliNpmPrefix,"packages"),Q=new Set(J.filter((W)=>Boolean(W)));try{for(let W of Qu$(X,{withFileTypes:!0})){if(!W.isDirectory())continue;let Y=N8(X,W.name);if(!Q.has(Y))Lw(Y,{recursive:!0,force:!0})}}catch{}}function mK($,J){let X=[$,J].filter(Boolean).join(`
487
+ `,{mode:f4,dirMode:K4}),$.daemonAuthToken}function Uy$($){return a4($,dS)}function Z$$($,J){let X=Uy$(J);if(X)return Vy$($,X);return wy$($.daemonAuthToken,{force:!0}),null}function B$$($){let J=$.trim();if(!J)return null;for(let X of J){let Q=X.charCodeAt(0);if(Q<=31||Q===127)return null}return J}var dS="secret://clawdi/auth-token";var nS=F(()=>{t4();L9();e6()});import{isAbsolute as qy$}from"node:path";function T9($,J){if($.projection?.sourceBundleVersion==="clawdi.hosted-runtime.bundle.v2")return J.userHome;let X=$.projection?.system;if(typeof X!=="object"||X===null||Array.isArray(X))return J.userHome;let Q=X.home;if(typeof Q!=="string")return J.userHome;let W=Q.trim();return W&&qy$(W)?W:J.userHome}var pS=()=>{};function qw($){let J=oS($),X=oS(J?.authCert),Q=oS(X?.PUBLIC_KEY),W=J?.capability,Y=X?.ISSUER,G=X?.SERIAL,z=Q?.data;if(!J||!rS(J,["authCert","capability","schemaVersion"])||J.schemaVersion!=="clawdi.managedWhatsAppSocket.v1"||typeof W!=="string"||!/^clawdi_[a-f0-9]{32}$/.test(W)||!X||!rS(X,["ISSUER","PUBLIC_KEY","SERIAL"])||typeof G!=="number"||!Number.isSafeInteger(G)||G<0||typeof Y!=="string"||Y.length===0||Y.trim()!==Y||Y.length>256||!Q||!rS(Q,["data","type"])||Q.type!=="Buffer"||typeof z!=="string"||!Zy$(z,32))throw Error("invalid Clawdi managed WhatsApp socket metadata");return{schemaVersion:"clawdi.managedWhatsAppSocket.v1",capability:W,authCert:{SERIAL:G,ISSUER:Y,PUBLIC_KEY:{type:"Buffer",data:z}}}}function oS($){return $&&typeof $==="object"&&!Array.isArray($)?$:null}function rS($,J){return Object.keys($).sort().join("\x00")===[...J].sort().join("\x00")}function Zy$($,J){let X=Buffer.from($,"base64");return X.length===J&&X.toString("base64")===$}var f3="x-clawdi-whatsapp-link-capability",Uw="clawdi.managedWhatsAppSocket",iS="clawdi.managedWhatsAppSocket.v1";import{createHash as By$}from"node:crypto";function K$$($){let J=Ky$($.controlPlaneApiUrl),X=[...$.links].sort((Q,W)=>Q.linkId.localeCompare(W.linkId)).map((Q)=>({id:`native-whatsapp-baileys-${Ly$(Q.linkId)}`,enabled:!0,kind:"websocket",match:{scheme:"wss",host:"web.whatsapp.com",path:{type:"equals",value:"/ws/chat"},headers:{[f3]:{type:"secretRefEquals",secretRef:Q.capabilitySecretRef}},query:{}},rewrite:{upstreamBaseUrl:J,preservePath:!1,removeHeaders:[f3],setHeaders:{authorization:{type:"secretRef",secretRef:Q.agentTokenSecretRef,prefix:"Bearer "}}},logging:{redactHeaders:[f3,"authorization"],redactUrlPatterns:[]},priority:40,owner:"clawdi-native-whatsapp",description:"Route one authenticated managed native Baileys websocket."}));return X.push({id:"native-whatsapp-baileys-invalid-capability",enabled:!0,kind:"deny",match:{host:"web.whatsapp.com",headers:{[f3]:{type:"exists"}},query:{}},logging:{redactHeaders:[f3],redactUrlPatterns:[]},priority:49,owner:"clawdi-native-whatsapp",description:"Fail closed when a managed WhatsApp capability is misplaced, stale, or invalid."}),X}function Ky$($){let J=new URL($);if(J.protocol==="https:")J.protocol="wss:";else if(J.protocol==="http:")J.protocol="ws:";else throw Error("WhatsApp egress control plane URL must use HTTP or HTTPS");return J.pathname="/v1/channels/whatsapp/baileys",J.search="",J.hash="",J.toString()}function Ly$($){return By$("sha256").update($).digest("hex").slice(0,16)}var L$$=()=>{};import{createHash as Ny$}from"node:crypto";import{join as F$$}from"node:path";function sS($,J=w$({mode:"hosted"})){if(!$.channelBindings)return $;let X=$.secretValues??{},Q=$.channelBindings.map((G)=>Fy$(G,X)),W=My$($.manifest,Q,J),Y=vy$(Q.filter((G)=>G.account.provider==="whatsapp"),W.projection?.channelCredentials);return{...$,manifest:W,sourceManifest:$.sourceManifest??$.manifest,secretValues:{...X,...Y}}}function Fy$($,J){let X=a4(J,$.agentTokenSecretRef),Q=a4(J,$.placeholderTokenSecretRef);if(!X)throw Error(`runtime bundle is missing ${$.agentTokenSecretRef}`);if(!Q)throw Error(`runtime bundle is missing ${$.placeholderTokenSecretRef}`);if($.provider==="whatsapp"){let W=gy$($.accountKey,$.linkId),Y=yy$($.accountKey,$.linkId),G=tS($.accountKey,$.linkId);if($.agentTokenSecretRef!==W)throw Error("runtime bundle WhatsApp agent token ref does not match its Link");if($.placeholderTokenSecretRef!==Y)throw Error("runtime bundle WhatsApp capability ref does not match its Link");if(Q!==G)throw Error("runtime bundle WhatsApp capability does not match its Link")}return{account:{id:$.provider==="whatsapp"?$.accountId:$.accountKey,provider:$.provider},accountKey:$.accountKey,linkId:$.provider==="whatsapp"?$.linkId:$.accountKey,secretRef:$.agentTokenSecretRef,placeholderSecretRef:$.placeholderTokenSecretRef,credential:$.provider==="whatsapp"?jy$($,J):void 0}}function jy$($,J){let X=$.credential.credsSecretRef,Q=uy$($.accountKey,$.credential.id);if(X!==Q)throw Error("runtime bundle WhatsApp credential ref does not match its credential");let W=a4(J,X);if(!W)throw Error(`runtime bundle is missing ${X}`);let Y;try{Y=JSON.parse(W)}catch(z){throw Error(`runtime bundle WhatsApp credential is invalid: ${z instanceof Error?z.message:String(z)}`)}let G=yK(Y);if(!G)throw Error("runtime bundle WhatsApp credential must be a JSON object");return{id:$.credential.id,credsSecretRef:X,material:{schemaVersion:"clawdi.whatsappBaileysAuthState.v1",creds:G,authCert:$.credential.authCert}}}function My$($,J,X){let Q=Cy$(J,$.controlPlane.apiUrl),W=T9($,X),Y=ly$($),G=Iy$(J,W,Y),z={...$,projection:{...$.projection??{},channels:by$(J,W,Y),channelCredentials:G},egressProfiles:xy$($.egressProfiles,Q)};return Ay$(_y$(z,J),J)}function by$($,J,X){let Q={};for(let W of $){let Y=W.account.provider;if(Y==="telegram"){let G=aS(Q,"telegram",W.accountKey);G.accounts[W.accountKey]={enabled:!0,botToken:N$$(W),dmPolicy:"open",groupPolicy:"open",allowFrom:["*"],capabilities:{inlineButtons:"all"},groups:{"*":{requireMention:!1}}};continue}if(Y==="discord"){let G=aS(Q,"discord",W.accountKey);G.accounts[W.accountKey]={enabled:!0,token:N$$(W),dmPolicy:"open",groupPolicy:"open",allowFrom:["*"],guilds:{"*":{requireMention:!1,users:["*"]}},actions:{stickers:!1,polls:!1,threads:!1,pins:!1,roles:!1,voiceStatus:!1,events:!1,moderation:!1,emojiUploads:!1,stickerUploads:!1,channels:!1,presence:!1}};continue}if(Y==="whatsapp"){let G=aS(Q,"whatsapp",W.accountKey),z=I$$(W,J,X);G.accounts[W.accountKey]={enabled:!0,...z?.targets.openclaw?{authDir:z.targets.openclaw.authDir}:{},dmPolicy:"allowlist",allowFrom:["*"],groupPolicy:"open",groupAllowFrom:["*"],groups:{"*":{requireMention:!1}}}}}return Q}function Iy$($,J,X){return $.map((Q)=>I$$(Q,J,X)).filter((Q)=>Q!==null).sort((Q,W)=>`${Q.provider}:${Q.accountKey}:${Q.credentialId}`.localeCompare(`${W.provider}:${W.accountKey}:${W.credentialId}`))}function _y$($,J){let X=$.runtimes.openclaw;if(!X?.enabled)return $;Py$(J);let Q=X.run??{env:{},prependPath:[]},W=Ty$(Q.secretEnv??{});for(let Y of J)W[b$$(Y)]=Y.placeholderSecretRef;if(!X.run&&Object.keys(W).length===0)return $;return{...$,runtimes:{...$.runtimes,openclaw:{...X,run:{...Q,secretEnv:W}}}}}function Ay$($,J){let X=$.runtimes.hermes;if(!X?.enabled)return $;let Q=Zw(J,"telegram"),W=Zw(J,"discord"),Y=Zw(J,"whatsapp"),G=X.run??{env:{},prependPath:[]},z=D$$(G.env??{},Oy$),H=D$$(G.secretEnv??{},Dy$);if(Q)z.TELEGRAM_ALLOW_ALL_USERS="true",z.HERMES_TELEGRAM_DISABLE_FALLBACK_IPS="true",H.TELEGRAM_BOT_TOKEN=Q.placeholderSecretRef;if(W)z.DISCORD_ALLOW_ALL_USERS="true",H.DISCORD_BOT_TOKEN=W.placeholderSecretRef;if(Y)z.WHATSAPP_MODE="bot",z.WHATSAPP_ALLOWED_USERS="*",z.WHATSAPP_ALLOW_ALL_USERS="true";return{...$,runtimes:{...$.runtimes,hermes:{...X,run:{...G,env:z,secretEnv:H}}}}}function Zw($,J){let X=$.filter((Q)=>Q.account.provider===J);if(X.length>1)throw Error(Ry$(J));return X[0]??null}function Py$($){for(let J of["telegram","discord","whatsapp"])Zw($,J)}function Ry$($){return`This Agent has multiple active ${$==="telegram"?"Telegram":$==="discord"?"Discord":$} bots. Unlink the extras until only one remains.`}function N$$($){return{source:"env",provider:"default",id:b$$($)}}function b$$($){return`${j$$}${O$$($.account.provider)}_${O$$($.accountKey)}${M$$}`}function O$$($){return $.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"CHANNEL"}function Ty$($){return Object.fromEntries(Object.entries($).filter(([J])=>!Ey$(J)))}function Ey$($){return $.startsWith(j$$)&&$.endsWith(M$$)}function D$$($,J){let X=new Set(J),Q={};for(let[W,Y]of Object.entries($))if(!X.has(W))Q[W]=Y;return Q}function aS($,J,X){let Q=$[J];if(Sy$(Q))return Q;let W={enabled:!0,defaultAccount:X,accounts:{}};return $[J]=W,W}function Sy$($){return typeof $==="object"&&$!==null&&!Array.isArray($)&&typeof $.accounts==="object"&&$.accounts!==null&&!Array.isArray($.accounts)}function Cy$($,J){let X=ny$(J),Q=[];for(let Y of $){let G=`${Y.account.provider}-${Y.accountKey}`;if(Y.account.provider==="telegram")for(let z of[{id:`native-${G}-managed`,pathPrefix:"/bot"},{id:`native-${G}-file-managed`,pathPrefix:"/file/bot"}])Q.push({id:z.id,enabled:!0,kind:"http",match:{scheme:"https",host:"api.telegram.org",pathPrefix:z.pathPrefix,path:{type:"secretRefPrefix",secretRef:Y.placeholderSecretRef,prefix:z.pathPrefix,suffix:"/"},headers:{},query:{}},rewrite:{upstreamBaseUrl:`${X}/v1/channels/telegram`,preservePath:!0,setHeaders:{authorization:{type:"secretRef",secretRef:Y.secretRef,prefix:"Bearer "}}},logging:{redactHeaders:["authorization"],redactUrlPatterns:[]},priority:100,owner:"clawdi-native-channels"});if(Y.account.provider==="discord")Q.push({id:`native-${G}-rest-managed`,enabled:!0,kind:"http",match:{scheme:"https",host:"discord.com",pathPrefix:"/api/",headers:{authorization:{type:"secretRefEquals",secretRef:Y.placeholderSecretRef,prefix:"Bot "}},query:{}},rewrite:{upstreamBaseUrl:`${X}/v1/channels/discord`,preservePath:!0,setHeaders:{authorization:{type:"secretRef",secretRef:Y.secretRef,prefix:"Bot "}}},logging:{redactHeaders:["authorization"],redactUrlPatterns:[]},priority:101,owner:"clawdi-native-channels"}),Q.push({id:`native-${G}-gateway-managed`,enabled:!0,kind:"websocket",match:{scheme:"wss",host:"gateway.discord.gg",pathPrefix:"/",headers:{},query:{}},rewrite:{upstreamBaseUrl:`${py$(X)}/v1/channels/discord/gateway`,preservePath:!1,setHeaders:{authorization:{type:"secretRef",secretRef:Y.secretRef,prefix:"Bearer "}}},logging:{redactHeaders:["authorization"],redactUrlPatterns:[]},priority:201,owner:"clawdi-native-channels"})}let W=Zw($,"whatsapp");if(W&&!eS(W))throw Error(`managed WhatsApp Link ${W.linkId} has no valid synthetic auth`);return Q.push(...K$$({controlPlaneApiUrl:J,links:W?[{linkId:W.linkId,agentTokenSecretRef:W.secretRef,capabilitySecretRef:W.placeholderSecretRef}]:[]})),Q}function xy$($,J){let X=[...$?.profiles??[]],Q=new Set(J.map((W)=>W.id));return{profiles:[...X.filter((W)=>!Q.has(W.id)&&!ky$(W)),...J]}}function ky$($){return $.owner==="clawdi-native-channels"||$.owner==="clawdi-native-whatsapp"||$.id==="direct-provider-passthrough"||$.id.startsWith("direct-provider-passthrough-")}function vy$($,J){let X={},Q=fy$(J);for(let W of $){let Y=eS(W);if(Y){let G=Y.credential.credsSecretRef;if(Q.has(G))X[G]=JSON.stringify(hy$(W,Y))}}return X}function fy$($){let J=new Set;if(!Array.isArray($))return J;for(let X of $){let Q=yK(X);if(Q?.provider!=="whatsapp"||Q.kind!=="whatsapp_baileys_auth_state")continue;let W=Array.isArray(Q.files)?Q.files:[];for(let Y of W){let G=yK(Y),z=dy$(G?.secretRef);if(G?.path==="creds.json"&&z)J.add(z)}}return J}function gy$($,J){return`secret://channels/whatsapp/${$}/links/${J}/agent-token`}function yy$($,J){return`secret://channels/whatsapp/${$}/links/${J}/egress-capability`}function uy$($,J){return`secret://channels/whatsapp/${$}/credentials/${J}/creds-json`}function tS($,J){return`clawdi_${Ny$("sha256").update(`whatsapp:${$}:${J}`).digest("hex").slice(0,32)}`}function I$$($,J,X){let Q=eS($);if(!Q)return null;let W=my$(J,$.accountKey),Y=cy$(J),G={};if(X.openclaw)G.openclaw={authDir:W};if(X.hermes)G.hermes={authDir:Y};let z=G.openclaw?.authDir??G.hermes?.authDir;if(!z)return null;return{provider:"whatsapp",kind:"whatsapp_baileys_auth_state",accountId:$.account.id,accountKey:$.accountKey,linkId:$.linkId,credentialId:Q.credential.id,authDir:z,files:[{path:"creds.json",secretRef:Q.credential.credsSecretRef}],targets:G}}function eS($){if($.account.provider!=="whatsapp")return null;let J=$.credential;if(!J)return null;let{material:X}=J,Q;try{Q=qw({schemaVersion:iS,capability:tS($.accountKey,$.linkId),authCert:X.authCert})}catch{return null}return{credential:J,creds:X.creds,authCert:Q.authCert}}function hy$($,J){let X=J.creds.additionalData,Q=X===void 0?{}:yK(X);if(!Q)throw Error("managed WhatsApp synthetic creds.additionalData must be an object");let W=qw({schemaVersion:iS,capability:tS($.accountKey,$.linkId),authCert:J.authCert});return{...J.creds,additionalData:{...Q,[Uw]:W}}}function my$($,J){return F$$($,".openclaw","credentials","whatsapp",J)}function cy$($){return F$$($,".hermes","platforms","whatsapp","session")}function ly$($){return{openclaw:$.runtimes.openclaw?.enabled===!0,hermes:$.runtimes.hermes?.enabled===!0}}function yK($){if(!$||typeof $!=="object"||Array.isArray($))return null;return $}function dy$($){return typeof $==="string"&&$.trim().length>0?$.trim():null}function ny$($){return $.replace(/\/+$/,"")}function py$($){if($.startsWith("https://"))return`wss://${$.slice(8)}`;if($.startsWith("http://"))return`ws://${$.slice(7)}`;return $}var Oy$,Dy$,j$$="CLAWDI_CHANNEL_",M$$="_AGENT_TOKEN";var _$$=F(()=>{w0();pS();L9();L$$();Oy$=["TELEGRAM_ALLOW_ALL_USERS","DISCORD_ALLOW_ALL_USERS","HERMES_TELEGRAM_DISABLE_FALLBACK_IPS","WHATSAPP_MODE","WHATSAPP_ALLOWED_USERS","WHATSAPP_ALLOW_ALL_USERS"],Dy$=["TELEGRAM_BOT_TOKEN","DISCORD_BOT_TOKEN"]});import{dirname as A$$,isAbsolute as P$$,relative as oy$,resolve as $C}from"node:path";function ay$(){return process.env.CLAWDI_RUNTIME_MODE?.trim().toLowerCase()||"missing"}function QC($,J={}){let X=J.expectedIdentity??R$$,Q=ay$(),W=Q==="hosted"&&$.mode==="hosted"?void 0:`hosted convergence requires CLAWDI_RUNTIME_MODE=hosted explicitly; resolved runtime mode is ${$.mode} (environment: ${Q})`,Y=$.userHome===X.home?void 0:`hosted runtime HOME must resolve to ${X.home}; resolved ${$.userHome}`,G=process.env.CLAWDI_RUNTIME_USER?.trim()??"",z,H=G||"missing";if(G!==X.user)z=G?`hosted runtime user must be ${X.user}; resolved ${G}`:`hosted runtime user must be ${X.user}; CLAWDI_RUNTIME_USER is missing`;else try{let w=(J.resolveUserIdentity??fn)(G);if(H=`${G} (${w.uid}:${w.gid})`,w.uid===0||w.gid===0)z=`hosted runtime user ${G} resolved to root identity ${w.uid}:${w.gid}`;else if(w.uid!==X.uid||w.gid!==X.gid)z=`hosted runtime user ${G} must resolve to ${X.uid}:${X.gid}; resolved ${w.uid}:${w.gid}`;else for(let[V,U,q]of[["CLAWDI_RUNTIME_UID",process.env.CLAWDI_RUNTIME_UID?.trim(),w.uid],["CLAWDI_RUNTIME_GID",process.env.CLAWDI_RUNTIME_GID?.trim(),w.gid]])if(U&&U!==String(q)){z=`${V} must match the resolved hosted runtime identity ${q}; resolved ${U}`;break}}catch(w){z=w instanceof Error?w.message:String(w)}return{mode:{ok:W===void 0,detail:$.mode,...W?{error:W}:{}},home:{ok:Y===void 0,detail:$.userHome,...Y?{error:Y}:{}},user:{ok:z===void 0,detail:H,...z?{error:z}:{}}}}function Bw($,J,X={}){let Q=QC($,X),W=[Q.mode,Q.home,Q.user].find((H)=>!H.ok)?.error;if(W)throw Error(W);let Y=$C($.clawdiHome),G=$C($.serviceStateRoot),z=oy$($C($.userHome),Y);if(z===""||!z.startsWith("..")&&!P$$(z))throw Error(`hosted CLAWDI_HOME must be outside the tenant home; resolved ${$.clawdiHome}`);if(!P$$($.clawdiHome)||Y===G||A$$(Y)!==A$$(G))throw Error(`hosted CLAWDI_HOME must be an absolute sibling of ${$.serviceStateRoot}; resolved ${$.clawdiHome}`);if(J.backend!=="incus")throw Error(`hosted v2 convergence requires runtime context backend incus; resolved ${String(J.backend??"missing")}`);if(X.platformRoots!=="deferred")hW($);return{identity:X.expectedIdentity??R$$,assertPlatformRoots:()=>hW($)}}var JC="/home/clawdi",XC="clawdi",ry$=10001,iy$=10001,R$$;var uK=F(()=>{V1();e6();R$$={home:JC,user:XC,uid:ry$,gid:iy$}});import{spawnSync as YC}from"node:child_process";import{createHash as sy$}from"node:crypto";import{accessSync as ty$,constants as ey$,existsSync as C$$,lstatSync as $u$,mkdirSync as Ju$,mkdtempSync as Xu$,readdirSync as Qu$,readFileSync as x$$,readlinkSync as k$$,renameSync as Wu$,rmSync as Lw,statSync as Yu$,symlinkSync as Gu$}from"node:fs";import{tmpdir as zu$}from"node:os";import{dirname as O8,join as N8,resolve as C9}from"node:path";function v$$($){if($.mode!=="hosted"||$.userHome!==JC||process.env.CLAWDI_RUNTIME_USER?.trim()!==XC||typeof process.geteuid==="function"&&process.geteuid()!==0)return;let J;try{J=$u$(Kw)}catch(Q){if(Q.code==="ENOENT")return;throw Q}if(!J.isSymbolicLink())throw Error(`hosted tenant PATH contains an unmanaged clawdi entrypoint: ${Kw}`);let X=C9(O8(Kw),k$$(Kw));if(X!==qu$)throw Error(`hosted tenant PATH contains an unmanaged clawdi symlink target: ${X}`);Lw(Kw)}function f$$($,J,X={}){let Q=pK(J,X);if(Q.selfReexec){let V=y3(J.cliBootstrapStatus);return g3("deferred",J,{packageSpec:$.clawdiCli?.packageSpec?.trim()||null,registry:V?.registry??null,npmPrefix:V?.npmPrefix??J.cliNpmPrefix,activeTarget:V?.activeTarget??null,version:V?.version??null,error:`CLI transaction recovery ${Q.status}; re-exec is required`},!0)}let W=$.clawdiCli?.packageSpec?.trim();if(!W)return g3("not_requested",J,{packageSpec:null,registry:null,activeTarget:null,version:null});Nu$(W);let Y=Lu$($),G=y3(J.cliBootstrapStatus);if(Ou$(G,J,W,Y))return g3("current",J,{packageSpec:W,registry:Y,npmPrefix:G.npmPrefix??Nw(G.activeTarget),activeTarget:G.activeTarget??null,version:G.version??null});let z=ju$(J,W);if(z)return s5(J,{packageSpec:W,registry:Y,npmPrefix:z.npmPrefix,activeTarget:z.activeTarget,version:z.version},z.verification),g3("current",J,{packageSpec:W,registry:Y,npmPrefix:z.npmPrefix,activeTarget:z.activeTarget,version:z.version});if(X.deferInstall)return g3("deferred",J,{packageSpec:W,registry:Y,npmPrefix:G?.npmPrefix??J.cliNpmPrefix,activeTarget:G?.activeTarget??null,version:G?.version??null,error:X.deferReason??"CLI install retry is in backoff"});let H=Fu$(J,G);if(H&&m6(J.cliManagedBin)===H.activeTarget&&(G?.status!=="installed"||G.source!=="npm"||G.packageSpec!==H.packageSpec||(G.registry??null)!==H.registry||G.npmPrefix!==H.npmPrefix||G.activePath!==J.cliManagedBin||G.activeTarget!==H.activeTarget||G.version!==H.version)){let V=S9(J,H);if(!V)throw Error("active clawdi CLI changed during verification");s5(J,H,V)}let w=Mu$(J,W,Y);return Iu$(J,{newIdentity:{packageSpec:W,registry:Y,npmPrefix:w.npmPrefix,activeTarget:w.activeTarget,version:w.version},previousIdentity:H,rollbackEligible:X.rollbackEligible===!0&&H!==null}),u$$(J.cliManagedBin,w.activeTarget),s5(J,{packageSpec:W,registry:Y,npmPrefix:w.npmPrefix,activeTarget:w.activeTarget,version:w.version},w.verification),m$$(J),u3(J,[w.npmPrefix,H?.npmPrefix??null]),g3("installed",J,{packageSpec:W,registry:Y,npmPrefix:w.npmPrefix,activeTarget:w.activeTarget,version:w.version},!0)}function g3($,J,X,Q=!1){return{status:$,...X,npmPrefix:X.npmPrefix??J.cliNpmPrefix,npmCache:X.npmCache??J.cliNpmCache,activePath:J.cliManagedBin,selfReexec:Q}}function Lu$($){let J=$.clawdiCli?.registry;if(typeof J!=="string"||!J.trim())return null;let X=J.trim(),Q;try{let W=new URL(X);W.pathname=W.pathname.replace(/\/+$/,""),W.search="",W.hash="",Q=W.toString().replace(/\/$/,"")}catch{throw Error(`unsupported clawdi CLI registry: ${X}`)}if(Q!=="https://registry.npmjs.org")throw Error(`unsupported clawdi CLI registry: ${X}`);return"https://registry.npmjs.org"}function Nu$($){if(nz.safeParse($).success)return;throw Error(`clawdi CLI packageSpec must be clawdi@<exact-semver> or a managed bootstrap tarball: ${$}`)}function y3($){if(!C$$($))return null;try{let J=JSON.parse(x$$($,"utf-8"));if(typeof J!=="object"||J===null||Array.isArray(J))return null;return J}catch{return null}}function pQ($){Ju$($,{recursive:!0})}function GC($,J){let X=C9($.cliNpmPrefix),Q=C9(J);return Q===X||Q.startsWith(`${X}/`)}function lK($,J){return GC($,J)&&J.endsWith("/bin/clawdi")}function Ou$($,J,X,Q){if(!$)return!1;if($.status!=="installed"||$.source!=="npm")return!1;if($.activePath!==J.cliManagedBin)return!1;if(!$.activeTarget)return!1;if(!lK(J,$.activeTarget))return!1;if(m6(J.cliManagedBin)!==$.activeTarget)return!1;if(!$.npmPrefix||C9($.npmPrefix)!==C9(Nw($.activeTarget)))return!1;if(!t5($.activeTarget))return!1;if(!$.version)return!1;let W=h3(X);if(W&&$.version!==W)return!1;let Y=process.env.CLAWDI_RUNTIME_ALLOW_TEST_INSTALLERS==="1"&&$.packageSpec===z8&&W===$.version;if($.packageSpec!==X&&!Y)return!1;if(($.registry??null)!==Q)return!1;if(!t5(J.cliManagedBin))return!1;let G=oQ($.activeTarget);if(G&&$.verification&&dK($.verification,G)&&y$$($.verification))return!0;if(!G)return!1;try{if(Dw($.activeTarget)!==$.version)return!1;Fw($.activeTarget);let z=Ow($.activeTarget,G);return s5(J,{packageSpec:Y?z8:X,registry:Q,npmPrefix:$.npmPrefix,activeTarget:$.activeTarget,version:$.version},z),!0}catch{return!1}}function Du$($,J){let X=m6($.cliManagedBin);if(!X||!lK($,X))return null;let Q=Nw(X);if(!GC($,Q))return null;if(!t5(X)||!t5($.cliManagedBin))return null;try{let W=oQ(X);if(!W)return null;let Y=Dw(X);Fw(X),Ow(X,W);let G=`clawdi@${Y}`;if(!o7.safeParse(G).success)return null;let z=J?.packageSpec,H=J?.registry??null,w=z?h3(z):null,V=J?.status==="installed"&&J.source==="npm"&&J.activePath===$.cliManagedBin&&J.activeTarget===X&&J.npmPrefix!==void 0&&C9(J.npmPrefix)===C9(Q)&&J.version===Y&&z!==void 0&&nz.safeParse(z).success&&(w===null||w===Y)&&(H===null||H==="https://registry.npmjs.org");return{packageSpec:V&&z?z:G,registry:V?H:null,npmPrefix:Q,activeTarget:X,version:Y}}catch{return null}}function Fu$($,J){let X=Du$($,J);if(!X)return null;let Q=TJ($).transaction;if(Q?.phase!=="activated"||Q.rollback||!Q.rollbackEligible||!Q.previousIdentity||Q.newIdentity.activeTarget!==X.activeTarget)return X;return S9($,Q.previousIdentity)?Q.previousIdentity:X}function ju$($,J){let X=h3(J);if(!X)return null;let Q=g$$($,X),W=m6($.cliManagedBin);if(W!==N8(Q,"bin","clawdi"))return null;if(!lK($,W))return null;if(!t5(W)||!t5($.cliManagedBin))return null;let Y=oQ(W);if(!Y)return null;let G=Dw(W);if(G!==X)return null;Fw(W);let z=Ow(W,Y);return{npmPrefix:Nw(W),activeTarget:W,version:G,verification:z}}function h3($){if(!o7.safeParse($).success)return null;return $.slice(7)}function Mu$($,J,X){let Q=bu$($,J,X);if(Pu$($,J,X,Q.version))throw Error(`clawdi CLI ${Q.version} is marked bad after rollback; waiting for a newer resolved version`);let W=Q.npmPrefix;pQ(O8(O8($.cliManagedBin))),pQ(O8($.cliManagedBin)),pQ($.cliNpmPrefix),pQ(W),pQ($.cliNpmCache);let Y=["install","-g","--prefix",W,"--cache",$.cliNpmCache,"--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?["--registry",X]:[],Q.installPackageSpec],G=YC("npm",Y,{encoding:"utf8",timeout:Hu$,env:{...process.env,NO_UPDATE_NOTIFIER:"1",NPM_CONFIG_UPDATE_NOTIFIER:"false"}});if(G.status!==0)throw Error(`npm install ${Q.installPackageSpec} failed${G.status===null?"":` (${G.status})`}${G.error?`: ${G.error.message}`:""}${mK(G.stdout,G.stderr)}`);let z=`${W}/bin/clawdi`;if(!t5(z))throw Error(`npm install completed but clawdi bin is missing: ${z}`);let H=oQ(z);if(!H)throw Error(`installed clawdi bin disappeared before verification: ${z}`);let w=Dw(z),V=h3(J);if(V&&w!==V)throw Error(`npm install ${Q.installPackageSpec} reported version ${w}, expected ${V}`);Fw(z);let U=Ow(z,H);return{npmPrefix:W,activeTarget:z,version:w,verification:U}}function bu$($,J,X){let Q=h3(J);if(Q)return{installPackageSpec:`clawdi@${Q}`,npmPrefix:g$$($,Q),version:Q};let W=sy$("sha256").update(JSON.stringify({packageSpec:J,registry:X})).digest("hex").slice(0,16);return{installPackageSpec:J,npmPrefix:N8($.cliNpmPrefix,"packages",`tarball-${W}`),version:`tarball-${W}`}}function g$$($,J){if(!/^[0-9A-Za-z._+-]+$/.test(J))throw Error(`resolved clawdi CLI version contains unsafe path characters: ${J}`);return N8($.cliNpmPrefix,"packages",J)}function Nw($){return O8(O8($))}function oQ($){try{let J=Yu$($);return{device:J.dev,inode:J.ino,size:J.size,modifiedAtMs:J.mtimeMs}}catch{return null}}function dK($,J){return $.device===J.device&&$.inode===J.inode&&$.size===J.size&&$.modifiedAtMs===J.modifiedAtMs}function y$$($){let J=Date.parse($.verifiedAt),X=Date.now()-J;return Number.isFinite(J)&&X>=0&&X<Uu$}function Ow($,J){let X=oQ($);if(!X||!dK(J,X))throw Error(`clawdi CLI target changed during verification: ${$}`);return{verifiedAt:new Date().toISOString(),...X}}function m6($){try{return C9(O8($),k$$($))}catch{return null}}function u3($,J){let X=N8($.cliNpmPrefix,"packages"),Q=new Set(J.filter((W)=>Boolean(W)));try{for(let W of Qu$(X,{withFileTypes:!0})){if(!W.isDirectory())continue;let Y=N8(X,W.name);if(!Q.has(Y))Lw(Y,{recursive:!0,force:!0})}}catch{}}function mK($,J){let X=[$,J].filter(Boolean).join(`
488
488
  `).trim();return X?`: ${X.slice(0,1000)}`:""}function Dw($){let J=YC($,["--version"],{encoding:"utf8",timeout:wu$,env:{...process.env,CLAWDI_NO_AUTO_UPDATE:"1",CLAWDI_NO_UPDATE_CHECK:"1"}});if(J.status!==0)throw Error(`installed clawdi did not pass --version smoke check${J.status===null?"":` (${J.status})`}${J.error?`: ${J.error.message}`:""}${mK(J.stdout,J.stderr)}`);let X=J.stdout.trim().split(/\r?\n/,1)[0]?.trim();if(!X)throw Error("installed clawdi --version returned empty output");return X}function Fw($){let J=Xu$(N8(zu$(),"clawdi-runtime-verify-")),X;try{X=YC($,["runtime","verify","--json"],{encoding:"utf8",timeout:Vu$,env:{...process.env,HOME:N8(J,"home"),CLAWDI_SERVICE_STATE_DIR:N8(J,"state"),CLAWDI_RUN_DIR:N8(J,"run"),CLAWDI_NO_AUTO_UPDATE:"1",CLAWDI_NO_UPDATE_CHECK:"1"}})}finally{Lw(J,{recursive:!0,force:!0})}if(X.status!==0)throw Error(`installed clawdi did not pass runtime verify self-check${X.status===null?"":` (${X.status})`}${X.error?`: ${X.error.message}`:""}${mK(X.stdout,X.stderr)}`);let Q=X.stdout.trim();if(!Q)throw Error("installed clawdi runtime verify self-check returned empty output");try{let W=JSON.parse(Q);if(!W||typeof W!=="object"||Array.isArray(W)||W.status!=="ok")throw Error("status was not ok")}catch(W){throw Error(`installed clawdi runtime verify self-check returned invalid JSON: ${W instanceof Error?W.message:String(W)}${mK(X.stdout,X.stderr)}`)}}function u$$($,J){let X=O8($);pQ(O8(X)),pQ(X);let Q=`${X}/.clawdi.next.${process.pid}.${Date.now()}`;try{Lw(Q,{force:!0}),Gu$(J,Q),Wu$(Q,$)}catch(W){throw Lw(Q,{force:!0}),W}}function s5($,J,X){let Q=oQ(J.activeTarget);if(X&&(!Q||!dK(X,Q)))throw Error(`clawdi CLI target changed after verification: ${J.activeTarget}`);e4($,$.cliBootstrapStatus,`${JSON.stringify({schemaVersion:"clawdi.cliNpmBootstrapStatus.v1",generatedAt:new Date().toISOString(),status:"installed",source:"npm",packageSpec:J.packageSpec,registry:J.registry,npmPrefix:J.npmPrefix,npmCache:$.cliNpmCache,activePath:$.cliManagedBin,activeTarget:J.activeTarget,version:J.version,verification:X,error:null},null,2)}
489
489
  `,{mode:384,dirMode:493})}function h$$($,J){let X=null;try{X=TJ($).transaction??null,pK($)}catch(W){return S$$(X,W)}let Q=TJ($);if(X=Q.transaction??null,!X)return{status:"not_pending",version:null,previousVersion:null,activeTarget:null,previousActiveTarget:null};if(!X.rollbackEligible||!X.previousIdentity)return{status:"not_pending",version:X.newIdentity.version,previousVersion:X.previousIdentity?.version??null,activeTarget:X.newIdentity.activeTarget,previousActiveTarget:X.previousIdentity?.activeTarget??null};if(!S9($,X.previousIdentity))return{status:"error",version:X.newIdentity.version,previousVersion:X.previousIdentity.version,activeTarget:X.newIdentity.activeTarget,previousActiveTarget:X.previousIdentity.activeTarget,error:"previous clawdi CLI identity is missing, inconsistent, or not executable"};if(m6($.cliManagedBin)!==X.newIdentity.activeTarget)return{status:"error",version:X.newIdentity.version,previousVersion:X.previousIdentity.version,activeTarget:X.newIdentity.activeTarget,previousActiveTarget:X.previousIdentity.activeTarget,error:"pending clawdi CLI target is no longer active"};try{let W={...X,rollback:{reason:J,markedAt:new Date().toISOString()}};return D8($,{...Q,transaction:W}),cK($,W),{status:"rolled_back",version:X.newIdentity.version,previousVersion:X.previousIdentity.version,activeTarget:X.newIdentity.activeTarget,previousActiveTarget:X.previousIdentity.activeTarget,error:null}}catch(W){return S$$(X,W)}}function nK($,J){let X=pK($,{runningVersion:J});if(X.selfReexec)return X;let Q=TJ($),W=Q.transaction??null;if(W?.phase!=="activated"||W.rollback)return X;if(W.newIdentity.version!==J)return X;if(m6($.cliManagedBin)!==W.newIdentity.activeTarget)return X;if(!S9($,W.newIdentity))return X;let Y=HC(Q);return Y.transaction=null,D8($,Y),u3($,[W.newIdentity.npmPrefix]),X}function zC($,J){return pK($,{runningVersion:J})}function Iu$($,J){let X=HC(TJ($));X.transaction={phase:"prepared",previousIdentity:J.previousIdentity,newIdentity:J.newIdentity,rollbackEligible:J.rollbackEligible,installedAt:new Date().toISOString(),rollback:null},D8($,X)}function m$$($){let J=TJ($),X=J.transaction;if(X?.phase!=="prepared")throw Error("prepared clawdi CLI upgrade transaction is missing");if(m6($.cliManagedBin)!==X.newIdentity.activeTarget)throw Error("prepared clawdi CLI target is not active");D8($,{...J,transaction:{...X,phase:"activated"}})}function pK($,J={}){let X=TJ($),Q=X.transaction??null;if(!Q)return{status:"unchanged",selfReexec:!1};if(Q.rollback)return cK($,Q),E9($,"rolled_back",J.runningVersion);let W=m6($.cliManagedBin),Y=Q.previousIdentity?.activeTarget??null;if(Q.phase==="prepared"){if(W===Q.newIdentity.activeTarget){let G=S9($,Q.newIdentity);if(!G)return hK($,Q),E9($,"rolled_back",J.runningVersion);return s5($,Q.newIdentity,G),m$$($),u3($,[Q.newIdentity.npmPrefix,Q.previousIdentity?.npmPrefix??null]),E9($,"activated",J.runningVersion)}if(W===Y){if(Q.previousIdentity){let G=S9($,Q.previousIdentity);if(!G)throw Error("prepared clawdi CLI transaction has an invalid previous identity");s5($,Q.previousIdentity,G)}return D8($,{...X,transaction:null}),u3($,[Q.previousIdentity?.npmPrefix??null]),E9($,"unchanged",J.runningVersion)}return hK($,Q),E9($,"rolled_back",J.runningVersion)}if(W===Q.newIdentity.activeTarget){if(!S9($,Q.newIdentity))return hK($,Q),E9($,"rolled_back",J.runningVersion);return E9($,"unchanged",J.runningVersion)}if(Q.previousIdentity&&W===Y){let G=c$$(Q);return D8($,{...X,transaction:G}),cK($,G),E9($,"rolled_back",J.runningVersion)}if(_u$($,Q))return E9($,"activated",J.runningVersion);return hK($,Q),E9($,"rolled_back",J.runningVersion)}function _u$($,J){let X=E$$($);if(!X)return!1;let Q=TJ($);if(!Au$(Q.transaction??null,J))throw Error("clawdi CLI transaction changed during bootstrap ownership handoff");let W=E$$($);if(!W||!WC(W,X))throw Error("clawdi CLI bootstrap identity changed during ownership handoff");if(D8($,{...Q,transaction:{phase:"activated",previousIdentity:null,newIdentity:X,rollbackEligible:!1,installedAt:new Date().toISOString(),rollback:null}}),m6($.cliManagedBin)!==X.activeTarget)throw Error("clawdi CLI bootstrap identity changed after ownership handoff");return u3($,[X.npmPrefix]),!0}function Au$($,J){if($===null||J===null)return $===J;return $.phase===J.phase&&WC($.previousIdentity,J.previousIdentity)&&WC($.newIdentity,J.newIdentity)&&$.rollbackEligible===J.rollbackEligible&&$.installedAt===J.installedAt&&$.rollback?.reason===J.rollback?.reason&&$.rollback?.markedAt===J.rollback?.markedAt}function WC($,J){if($===null||J===null)return $===J;return $.packageSpec===J.packageSpec&&$.registry===J.registry&&$.npmPrefix===J.npmPrefix&&$.activeTarget===J.activeTarget&&$.version===J.version}function E$$($){let J=y3($.cliBootstrapStatus),X=m6($.cliManagedBin);if(J?.schemaVersion!=="clawdi.cliNpmBootstrapStatus.v1"||J.status!=="installed"||J.source!=="npm"||J.error!==null||J.activePath!==$.cliManagedBin||J.activeTarget!==X||J.npmCache!==$.cliNpmCache||typeof J.packageSpec!=="string"||J.registry!==null&&typeof J.registry!=="string"||typeof J.npmPrefix!=="string"||typeof J.activeTarget!=="string"||typeof J.version!=="string")return null;let Q={packageSpec:J.packageSpec,registry:J.registry,npmPrefix:J.npmPrefix,activeTarget:J.activeTarget,version:J.version};if(!S9($,Q))return null;let W=y3($.cliBootstrapStatus);return m6($.cliManagedBin)===Q.activeTarget&&l$$(W,$,Q)&&W?.schemaVersion==="clawdi.cliNpmBootstrapStatus.v1"&&W.error===null&&W.npmCache===$.cliNpmCache?Q:null}function E9($,J,X){let Q=y3($.cliBootstrapStatus),W=m6($.cliManagedBin),Y=Q?.activeTarget===W?Q.version:void 0;return{status:J,selfReexec:X!==void 0&&Y!==void 0&&Y!==X}}function hK($,J){if(!J.previousIdentity||!S9($,J.previousIdentity))throw Error("clawdi CLI transaction cannot restore a verified previous identity");let X=c$$(J),Q=TJ($);D8($,{...Q,transaction:X}),cK($,X)}function c$$($){return{...$,rollback:{reason:"recovered interrupted or inconsistent clawdi CLI transaction",markedAt:new Date().toISOString()}}}function cK($,J){let X=J.previousIdentity;if(!J.rollback||!X)throw Error("clawdi CLI rollback transaction is incomplete");let Q=S9($,X);if(!Q)throw Error("previous clawdi CLI identity failed rollback verification");if(m6($.cliManagedBin)!==X.activeTarget)u$$($.cliManagedBin,X.activeTarget);s5($,X,Q);let Y=TJ($);D8($,{...Y,transaction:null,badVersions:Tu$(Y.badVersions??[],{packageSpec:J.newIdentity.packageSpec,registry:J.newIdentity.registry,version:J.newIdentity.version,reason:J.rollback.reason,markedAt:J.rollback.markedAt})}),u3($,[X.npmPrefix])}function S9($,J){if(!nz.safeParse(J.packageSpec).success||J.registry!==null&&J.registry!=="https://registry.npmjs.org"||!lK($,J.activeTarget)||!GC($,J.npmPrefix)||C9(Nw(J.activeTarget))!==C9(J.npmPrefix)||!t5(J.activeTarget))return null;let X=h3(J.packageSpec);if(X&&X!==J.version)return null;let Q=y3($.cliBootstrapStatus),W=oQ(J.activeTarget);if(l$$(Q,$,J)&&W&&Q?.verification&&dK(Q.verification,W)&&y$$(Q.verification))return Q.verification;if(!W)return null;try{if(Dw(J.activeTarget)!==J.version)return null;Fw(J.activeTarget);let Y=Ow(J.activeTarget,W);if(m6($.cliManagedBin)===J.activeTarget)s5($,J,Y);return Y}catch{return null}}function l$$($,J,X){return $?.status==="installed"&&$.source==="npm"&&$.packageSpec===X.packageSpec&&($.registry??null)===X.registry&&$.npmPrefix===X.npmPrefix&&$.activePath===J.cliManagedBin&&$.activeTarget===X.activeTarget&&$.version===X.version}function S$$($,J){return{status:"error",version:$?.newIdentity.version??null,previousVersion:$?.previousIdentity?.version??null,activeTarget:$?.newIdentity.activeTarget??null,previousActiveTarget:$?.previousIdentity?.activeTarget??null,error:J instanceof Error?J.message:String(J)}}function Pu$($,J,X,Q){return(TJ($).badVersions??[]).some((Y)=>Y.packageSpec===J&&(Y.registry??null)===X&&Y.version===Q)}function TJ($){if(!C$$($.cliUpgradeState))return Ru$();let J;try{J=JSON.parse(x$$($.cliUpgradeState,"utf-8"))}catch(Q){throw Error(`invalid clawdi CLI upgrade transaction JSON: ${Q instanceof Error?Q.message:String(Q)}`)}let X=typeof J==="object"&&J!==null&&!Array.isArray(J)?J.schemaVersion:void 0;if(X==="clawdi.cliUpgradeState.v2"){let Q=Ku$.safeParse(J);if(!Q.success)throw Error(`invalid clawdi CLI upgrade transaction: ${Q.error.issues[0]?.message}`);return Q.data}throw Error(`unsupported clawdi CLI upgrade transaction schema: ${String(X)}`)}function D8($,J){e4($,$.cliUpgradeState,`${JSON.stringify(HC(J),null,2)}
490
490
  `,{mode:384,dirMode:493})}function HC($){return{schemaVersion:"clawdi.cliUpgradeState.v2",transaction:$.transaction??null,badVersions:$.badVersions??[]}}function Ru$(){return{schemaVersion:"clawdi.cliUpgradeState.v2",transaction:null,badVersions:[]}}function Tu$($,J){let X=$.filter((Q)=>Q.packageSpec!==J.packageSpec||(Q.registry??null)!==J.registry||Q.version!==J.version);return X.push(J),X}function t5($){try{return ty$($,ey$.X_OK),!0}catch{return!1}}var Hu$=180000,wu$=20000,Vu$=20000,Uu$=300000,Kw="/usr/local/bin/clawdi",qu$="/usr/local/lib/node_modules/clawdi/bin/clawdi.mjs",T$$,Zu$,Bu$,Ku$;var wC=F(()=>{J6();uK();rz();e6();T$$=L.object({packageSpec:L.string().min(1),registry:L.string().min(1).nullable(),npmPrefix:L.string().min(1),activeTarget:L.string().min(1),version:L.string().min(1)}).strict(),Zu$=L.object({packageSpec:L.string().min(1),registry:L.string().min(1).nullable(),version:L.string().min(1),reason:L.string(),markedAt:L.string().min(1)}).strict(),Bu$=L.object({phase:L.enum(["prepared","activated"]),previousIdentity:T$$.nullable(),newIdentity:T$$,rollbackEligible:L.boolean(),installedAt:L.string().min(1),rollback:L.object({reason:L.string(),markedAt:L.string().min(1)}).strict().nullable()}).strict(),Ku$=L.object({schemaVersion:L.literal("clawdi.cliUpgradeState.v2"),transaction:Bu$.nullable(),badVersions:L.array(Zu$)}).strict()});import{createHash as Eu$}from"node:crypto";import{existsSync as d$$,lstatSync as n$$,mkdtempSync as Su$,readdirSync as p$$,readFileSync as VC,rmSync as Cu$}from"node:fs";import{tmpdir as xu$}from"node:os";import{join as m3}from"node:path";function oK($){return Eu$("sha256").update($).digest("hex")}function jw($,J){return J.type==="github"?["github",$,J.url,J.path,J.commit].join("\x00"):["project",$,J.projectId,J.contentHash].join("\x00")}function r$$($,J,X){let Q=oK(jw(J,X)),W=m3($.hostedSkillArchiveRoot,Q);return{archive:m3(W,"skill.tar.gz"),receipt:m3(W,"receipt.json")}}function fu$($,J,X){let Q=r$$($,J,X);if(!d$$(Q.archive)||!d$$(Q.receipt))return null;try{let W=n$$(Q.archive),Y=n$$(Q.receipt);if(!W.isFile()||W.isSymbolicLink()||W.size>ku$||!Y.isFile()||Y.isSymbolicLink())return null;let G=JSON.parse(VC(Q.receipt,"utf8"));if(!gu$(G))return null;if(G.skillId!==J||jw(G.skillId,G.source)!==jw(J,X))return null;let z=VC(Q.archive);if(oK(z)!==G.sha256)return null;return{archiveSha256:G.sha256,tarBytes:z}}catch{return null}}function gu$($){if(typeof $!=="object"||$===null||Array.isArray($))return!1;let J=$;if(J.schemaVersion!==o$$||typeof J.skillId!=="string"||typeof J.sha256!=="string"||!/^[a-f0-9]{64}$/.test(J.sha256)||typeof J.source!=="object"||J.source===null||Array.isArray(J.source))return!1;let X=J.source;return X.type==="github"?typeof X.url==="string"&&typeof X.path==="string"&&typeof X.commit==="string":X.type==="project"&&typeof X.projectId==="string"&&typeof X.contentHash==="string"&&typeof X.archiveUrl==="string"&&typeof X.installUrl==="string"}function yu$($,J,X){let Q=new URL($.controlPlane.apiUrl),W=new URL(X.archiveUrl),Y=new URL(X.installUrl);if(W.origin!==Q.origin||Y.origin!==Q.origin)throw Error(`Project Skill ${J} download endpoints do not match the control plane`);let G=/^\/v1\/runtime\/project-skill-archives\/([0-9a-f-]{36})\/([0-9a-f-]{36})\/([0-9a-f-]{36})\/([a-f0-9]{64})\/([a-f0-9]{64})\/([a-z0-9-]+)\.tar\.gz$/.exec(W.pathname),z=/^\/v1\/runtime\/project-skill-files\/([0-9a-f-]{36})\/([0-9a-f-]{36})\/([a-f0-9]{64})\/([a-f0-9]{64})\/SKILL\.md$/.exec(Y.pathname);if(!G||!z||G[1]!==$.environmentId||G[2]!==X.projectId||G[4]!==X.contentHash||G[6]!==J||z[1]!==$.environmentId||z[2]!==G[3]||z[3]!==X.contentHash||z[4]!==G[5])throw Error(`Project Skill ${J} install endpoint is invalid`)}async function uu$($,J,X){let Q=new Headers({Accept:"application/gzip"});if(X.authToken)Q.set("Authorization",`Bearer ${X.authToken}`);let W=await(X.fetcher??fetch)(new URL(J.archiveUrl),{headers:Q,redirect:"error"});if(!W.ok)throw Error(`Project Skill ${$} download failed (${W.status})`);let Y=await HQ(W,vu$,{resourceLabel:"Project Skill archive",limitLabel:"25 MB"}),G=Su$(m3(xu$(),"clawdi-project-skill-"));try{await i9(G,Y);let z=p$$(G);if(z.length!==1||z[0]!==$)throw Error(`Project Skill ${$} archive has an unexpected root layout`);let H=m3(G,$),w=await e0(H,G,$),V=p$$(H),U=V.length===1&&V[0]==="SKILL.md"&&oK(VC(m3(H,"SKILL.md")))===J.contentHash;if(w.hash!==J.contentHash&&!U)throw Error(`Project Skill ${$} archive does not match its content identity`);return w.archive}finally{Cu$(G,{recursive:!0,force:!0})}}function hu$($,J,X,Q){let W=oK(Q),Y=r$$($,J,X);return e4($,Y.archive,Q,{mode:384,dirMode:448}),e4($,Y.receipt,`${JSON.stringify({schemaVersion:o$$,skillId:J,source:X,sha256:W},null,2)}
@@ -665,7 +665,7 @@ if (action === "inspect") {
665
665
  `,{mode:384,dirMode:448}),Q.afterWrite?.($,xh$($)),W}function QL($){if(!$)return null;return{nativeProfileId:$.nativeProfileId,credentialRevision:$.credentialRevision,state:$.state,...$.operation?{operation:$.operation}:{},...$.credentialFingerprint?{credentialFingerprint:$.credentialFingerprint}:{},...$.beforeCredentialFingerprint?{beforeCredentialFingerprint:$.beforeCredentialFingerprint}:{},...$.targetCredentialFingerprint?{targetCredentialFingerprint:$.targetCredentialFingerprint}:{}}}var PC="clawdi.oauthCredentialOwnership.v2",AC,vh$;var b4$=F(()=>{J6();t4();AC=L.object({schemaVersion:L.literal(PC),runtime:L.enum(["hermes","openclaw"]),providerId:L.string().min(1),nativeProfileId:L.string().min(1),credentialRevision:L.string().min(1).max(64),state:L.enum(["intent","seeded","adopted","revoked","retired"]),operation:L.enum(["seed","upsert","remove"]).optional(),credentialFingerprint:L.string().regex(/^sha256:[a-f0-9]{64}$/).optional(),beforeCredentialFingerprint:L.string().regex(/^sha256:[a-f0-9]{64}$/).optional(),targetCredentialFingerprint:L.string().regex(/^sha256:[a-f0-9]{64}$/).optional()}).strict().superRefine(($,J)=>{if($.state==="intent"&&!$.operation)J.addIssue({code:"custom",message:"intent ledger requires an operation"});if($.state==="intent"&&($.operation==="seed"||$.operation==="upsert")&&!$.targetCredentialFingerprint)J.addIssue({code:"custom",message:"credential write intent requires target evidence"});if($.state==="intent"&&($.operation==="upsert"||$.operation==="remove")&&!$.beforeCredentialFingerprint)J.addIssue({code:"custom",message:"credential mutation intent requires before evidence"});if($.state!=="intent"&&$.operation)J.addIssue({code:"custom",message:"stable ledger cannot carry an operation"});if($.state!=="intent"&&($.beforeCredentialFingerprint||$.targetCredentialFingerprint))J.addIssue({code:"custom",message:"stable ledger cannot carry intent evidence"})}),vh$=L.object({schemaVersion:L.literal("clawdi.runtimeOAuthCredential.v1"),runtime:L.enum(["hermes","openclaw"]),providerId:L.string().min(1),nativeProfileId:L.string().min(1),credentialRevision:L.string().min(1).max(64),state:L.enum(["seeded","adopted","revoked"]),credentialFingerprint:L.string().regex(/^sha256:[a-f0-9]{64}$/).optional()}).strict()});import{spawnSync as _w}from"node:child_process";import{chmodSync as fh$,existsSync as gh$,lstatSync as TC,mkdtempSync as yh$,readdirSync as uh$,rmSync as hh$}from"node:fs";import{join as P4$}from"node:path";function p3($,J){let X=_w($,J,{encoding:"utf8",maxBuffer:65536,timeout:30000});if(X.status!==0){let Q=[X.error?.message,X.stderr,X.stdout].filter((W)=>typeof W==="string"&&W.trim().length>0).join(`
666
666
  `).trim().slice(-2000);throw Error(`Files service isolation command failed: ${$}${Q?`: ${Q}`:""}`)}return X.stdout.trim()}function I4$($){let J=_w("getent",["group",$],{encoding:"utf8"});if(J.status!==0)return null;let X=J.stdout.trim().split(":"),Q=Number.parseInt(X[2]??"",10);if(!Number.isInteger(Q)||Q<=0)throw Error(`Files service group ${$} has an invalid gid`);return Q}function _4$($){let J=_w("getent",["passwd",$],{encoding:"utf8"});if(J.status!==0)return null;let X=J.stdout.trim().split(":"),Q=Number.parseInt(X[2]??"",10),W=Number.parseInt(X[3]??"",10);if(!Number.isInteger(Q)||Q<=0||!Number.isInteger(W)||W<=0)throw Error(`Files service user ${$} has an invalid filesystem identity`);return{uid:Q,gid:W,home:X[5]??"",shell:X[6]??""}}function WL($){let X=p3("id",["-G",$]).split(/\s+/).map((Q)=>Number.parseInt(Q,10));if(X.length===0||X.some((Q)=>!Number.isInteger(Q)||Q<=0))throw Error(`Files service identity ${$} has invalid group membership`);return[...new Set(X)]}function mh$($){let J=_w("getent",["group",String($)],{encoding:"utf8"}),X=J.status===0?J.stdout.trim().split(":")[0]?.trim():"";if(!X)throw Error(`Files service identity group ${$} cannot be resolved`);return X}function A4$($,J){p3("gpasswd",["--delete",$,mh$(J)])}function ch$($){let J=I4$(n3);if(J===null)p3("groupadd",["--system",n3]),J=I4$(n3);if(J===null)throw Error("Files service group was not created");let X=_4$(M8);if(X===null)p3("useradd",["--system","--gid",n3,"--home-dir","/nonexistent","--no-create-home","--shell","/usr/sbin/nologin",M8]),X=_4$(M8);if(X===null)throw Error("Files service user was not created");let Q=H1($),W=S5($);if(X.uid===0||X.uid===Q||X.gid!==J||X.gid===W)throw Error("Files service identity is not distinct from the tenant runtime identity");if(X.home!=="/nonexistent"||!X.shell.endsWith("/nologin"))throw Error("Files service identity must be non-login with no home directory");if(WL($).includes(J))A4$($,J);for(let Y of WL(M8))if(Y!==J)A4$(M8,Y);if(WL($).includes(J)||WL(M8).some((Y)=>Y!==J))throw Error("Files service identity has unsafe supplementary group membership");return{uid:X.uid,gid:J}}function lh$($,J,X,Q){if(!gh$(J))throw Error(`Files source root does not exist: ${J}`);if(J!==$.userHome||/\s/.test(J))throw Error("Files source root must be the canonical tenant home path");if(!BQ("systemd-tmpfiles"))throw Error("Files service isolation requires systemd-tmpfiles");if(!/(?:^|\s)\+ACL(?:\s|$)/.test(p3("systemd-tmpfiles",["--version"])))throw Error("Files service isolation requires systemd-tmpfiles POSIX ACL support");let W=TC($.runRoot);if(!W.isDirectory()||W.isSymbolicLink()||W.uid!==0)throw Error("Files service isolation requires a trusted root-owned runtime directory");let Y=yh$($.fileBrowserAclTempPrefix);fh$(Y,448);try{let G=P4$(Y,"filebrowser.conf"),z=[`u:${X}:rwx`,`g:${Q.gid}:rwx`,"m::rwx",`d:u:${X}:rwx`,`d:g:${Q.gid}:rwx`,"d:m::rwx"].join(","),H=[`u:${X}:rw-`,`g:${Q.gid}:rw-`,"m::rwx"].join(","),w=dh$(J,X,Q.uid).map((V)=>`a+ ${nh$(V.path)} - - - - ${V.directory?z:H}`).join(`
667
667
  `);Z$(G,`${w}
668
- `,{mode:384,dirMode:448}),p3("systemd-tmpfiles",["--create",G])}finally{hh$(Y,{recursive:!0,force:!0})}for(let G of["-r","-w","-x"]){let z=DJ(M8,"/nonexistent","/usr/bin/test",[G,J],{currentUid:0,runtimeUid:Q.uid,runtimeGid:Q.gid});if(_w(z.command,z.args,{env:{...process.env,...z.env}}).status!==0)throw Error("Files service identity cannot access the tenant workspace ACL")}}function dh$($,J,X){let Q=TC($);if(!Q.isDirectory()||Q.isSymbolicLink())throw Error("Files source root must be a trusted directory");if(Q.uid!==J)throw Error("Files source root must be owned by the tenant runtime user");let W=[{path:$,directory:!0}],Y=(G)=>{for(let z of uh$(G,{withFileTypes:!0}).sort((H,w)=>H.name.localeCompare(w.name))){if(z.name.startsWith("."))continue;let H=P4$(G,z.name),w;try{w=TC(H)}catch(V){if(ph$(V)==="ENOENT")continue;throw V}if(w.isSymbolicLink())continue;if(w.uid===X)continue;if(w.uid!==J)continue;if(w.isFile()){W.push({path:H,directory:!1});continue}if(!w.isDirectory()||w.dev!==Q.dev)continue;W.push({path:H,directory:!0}),Y(H)}};return Y($),W}function nh$($){let J="";for(let X of Buffer.from($)){if(X===37){J+="%%";continue}if(X>=48&&X<=57||X>=65&&X<=90||X>=97&&X<=122||[45,46,47,95].includes(X)){J+=String.fromCharCode(X);continue}J+=`\\x${X.toString(16).padStart(2,"0")}`}return J}function ph$($){if(typeof $!=="object"||$===null||!("code"in $))return null;return typeof $.code==="string"?$.code:null}function R4$($,J){if(!Q6())throw Error("Files service isolation requires root reconciliation");let X=process.env.CLAWDI_RUNTIME_USER?.trim()||"clawdi";if(X==="root"||X==="0")throw Error("Files service isolation requires a non-root tenant runtime user");for(let W of["getent","gpasswd","groupadd","id","useradd"])if(!BQ(W))throw Error(`Files service isolation requires ${W}`);let Q=ch$(X);return lh$($,J,H1(X),Q),Q}var M8="clawdi-files",n3="clawdi-files";var EC=F(()=>{t4();V1()});import{spawnSync as E4$}from"node:child_process";import{createHash as oh$}from"node:crypto";import{chmodSync as CC,chownSync as xC,existsSync as S4$,lstatSync as $X,mkdirSync as rh$,mkdtempSync as ih$,readdirSync as C4$,readFileSync as x4$,renameSync as ah$,rmSync as YL}from"node:fs";import{basename as sh$,join as I8}from"node:path";function Aw($){return $.companions?.filebrowser??null}function e5($){return I8($.fileBrowserInstallRoot,th$)}function Pw($,J){return I8(e5($),J.toLowerCase())}function GL($,J){return I8(Pw($,J),k4$)}function zL($,J){if(J==="x64")return $.assets.amd64;if(J==="arm64")return $.assets.arm64;throw Error(`Files companion does not support runtime architecture ${J}`)}function g4$($){try{let J=$X($);if(!J.isFile()||J.isSymbolicLink())return null;return oh$("sha256").update(x4$($)).digest("hex")}catch{return null}}function HL($,J){try{let X=$X(Pw($,J));if(!X.isDirectory()||X.isSymbolicLink())return!1;let Q=b8();if(X.uid!==Q.uid||X.gid!==Q.gid||(X.mode&511)!==493)return!1}catch{return!1}try{let X=$X(GL($,J)),Q=b8();return X.isFile()&&!X.isSymbolicLink()&&X.uid===Q.uid&&X.gid===Q.gid&&(X.mode&511)===493&&g4$(GL($,J))===J.toLowerCase()}catch{return!1}}function y4$($,J,X=process.arch){let Q=Aw($);if(!Q)return{rootTrustedRoots:[],rootTargets:[]};let W=zL(Q,X),Y=Pw(J,W.sha256);return{rootTrustedRoots:[J.fileBrowserInstallRoot],rootTargets:[...HL(J,W.sha256)?[]:[Y],J.fileBrowserConfig]}}function $m$($,J){return R3({server:{listen:$.listen,port:$.port,baseURL:$.baseURL,database:I8(J.fileBrowserStateRoot,"filebrowser.db"),cacheDir:I8(J.fileBrowserStateRoot,"cache"),disableUpdateCheck:!0,disableWebDAV:!0,sources:[{path:$.sourceRoot,name:"Files",config:{defaultEnabled:!0,private:!0,rules:[{folderPath:"/",ignoreHidden:!0,ignoreSymlinks:!0}]}}]},frontend:{name:"Files",disableDefaultLinks:!0,disableUsedPercentage:!1},http:{trustedHeaders:[]},auth:{methods:{password:{enabled:!1,signup:!1},passkey:{enabled:!1},jwt:{enabled:!0,secret:$.auth.secret,algorithm:$.auth.algorithm,header:$.auth.header,userIdentifier:$.auth.userIdentifier,groupsClaim:$.auth.groupsClaim,userGroups:[$.auth.requiredGroup]}}},userDefaults:{account:{lockPassword:!0,disableSettings:!0,disableUpdateNotifications:!0,loginMethod:"jwt",permissions:{admin:!1,api:!1,modify:!0,share:!1,realtime:!1,delete:!0,create:!0,download:!0}}}})}function b8(){if(Q6())return{uid:0,gid:0};return{uid:typeof process.geteuid==="function"?process.geteuid():0,gid:typeof process.getegid==="function"?process.getegid():0}}function SC($,J,X){if(!S4$($))rh$($,{recursive:!0,mode:X});let Q=$X($);if(!Q.isDirectory()||Q.isSymbolicLink())throw Error(`Files companion managed path is not a trusted directory: ${$}`);xC($,J.uid,J.gid),CC($,X)}function Jm$($,J,X){let Q=E4$("curl",["-fsSL","--proto","=https","--tlsv1.2","--retry","3","-o",J,$],{cwd:X.fileBrowserInstallRoot,encoding:"utf8",maxBuffer:65536,timeout:300000});if(Q.status!==0){let W=[Q.stderr,Q.stdout].filter((Y)=>typeof Y==="string"&&Y.trim().length>0).join(`
668
+ `,{mode:384,dirMode:448}),p3("systemd-tmpfiles",["--create",G])}finally{hh$(Y,{recursive:!0,force:!0})}for(let G of["-r","-w","-x"]){let z=DJ(M8,"/nonexistent","/usr/bin/test",[G,J],{currentUid:0,runtimeUid:Q.uid,runtimeGid:Q.gid});if(_w(z.command,z.args,{env:{...process.env,...z.env}}).status!==0)throw Error("Files service identity cannot access the tenant workspace ACL")}}function dh$($,J,X){let Q=TC($);if(!Q.isDirectory()||Q.isSymbolicLink())throw Error("Files source root must be a trusted directory");if(Q.uid!==J)throw Error("Files source root must be owned by the tenant runtime user");let W=[{path:$,directory:!0}],Y=(G)=>{for(let z of uh$(G,{withFileTypes:!0}).sort((H,w)=>H.name.localeCompare(w.name))){if(z.name.startsWith("."))continue;let H=P4$(G,z.name),w;try{w=TC(H)}catch(V){if(ph$(V)==="ENOENT")continue;throw V}if(w.isSymbolicLink())continue;if(w.uid===X)continue;if(w.uid!==J)continue;if(w.isFile()){W.push({path:H,directory:!1});continue}if(!w.isDirectory()||w.dev!==Q.dev)continue;W.push({path:H,directory:!0}),Y(H)}};return Y($),W}function nh$($){let J="";for(let X of Buffer.from($)){if(X===37){J+="%%";continue}if(X>=48&&X<=57||X>=65&&X<=90||X>=97&&X<=122||[45,46,47,95].includes(X)){J+=String.fromCharCode(X);continue}J+=`\\x${X.toString(16).padStart(2,"0")}`}return J}function ph$($){if(typeof $!=="object"||$===null||!("code"in $))return null;return typeof $.code==="string"?$.code:null}function R4$($,J){if(!Q6())throw Error("Files service isolation requires root reconciliation");let X=process.env.CLAWDI_RUNTIME_USER?.trim()||"clawdi";if(X==="root"||X==="0")throw Error("Files service isolation requires a non-root tenant runtime user");for(let W of["getent","gpasswd","groupadd","id","useradd"])if(!BQ(W))throw Error(`Files service isolation requires ${W}`);let Q=ch$(X);return lh$($,J,H1(X),Q),Q}var M8="clawdi-files",n3="clawdi-files";var EC=F(()=>{t4();V1()});import{spawnSync as E4$}from"node:child_process";import{createHash as oh$}from"node:crypto";import{chmodSync as CC,chownSync as xC,existsSync as S4$,lstatSync as $X,mkdirSync as rh$,mkdtempSync as ih$,readdirSync as C4$,readFileSync as x4$,renameSync as ah$,rmSync as YL}from"node:fs";import{basename as sh$,join as I8}from"node:path";function Aw($){return $.companions?.filebrowser??null}function e5($){return I8($.fileBrowserInstallRoot,th$)}function Pw($,J){return I8(e5($),J.toLowerCase())}function GL($,J){return I8(Pw($,J),k4$)}function zL($,J){if(J==="x64")return $.assets.amd64;if(J==="arm64")return $.assets.arm64;throw Error(`Files companion does not support runtime architecture ${J}`)}function g4$($){try{let J=$X($);if(!J.isFile()||J.isSymbolicLink())return null;return oh$("sha256").update(x4$($)).digest("hex")}catch{return null}}function HL($,J){try{let X=$X(Pw($,J));if(!X.isDirectory()||X.isSymbolicLink())return!1;let Q=b8();if(X.uid!==Q.uid||X.gid!==Q.gid||(X.mode&511)!==493)return!1}catch{return!1}try{let X=$X(GL($,J)),Q=b8();return X.isFile()&&!X.isSymbolicLink()&&X.uid===Q.uid&&X.gid===Q.gid&&(X.mode&511)===493&&g4$(GL($,J))===J.toLowerCase()}catch{return!1}}function y4$($,J,X=process.arch){let Q=Aw($);if(!Q)return{rootTrustedRoots:[],rootTargets:[]};let W=zL(Q,X),Y=Pw(J,W.sha256);return{rootTrustedRoots:[J.fileBrowserInstallRoot],rootTargets:[...HL(J,W.sha256)?[]:[Y],J.fileBrowserConfig]}}function $m$($,J){return R3({server:{listen:$.listen,port:$.port,baseURL:$.baseURL,database:I8(J.fileBrowserStateRoot,"filebrowser.db"),cacheDir:I8(J.fileBrowserStateRoot,"cache"),disableUpdateCheck:!0,disableWebDAV:!0,sources:[{path:$.sourceRoot,name:"Files",config:{defaultEnabled:!0,private:!0,rules:[{folderPath:"/",ignoreSymlinks:!0}]}}]},frontend:{name:"Files",disableDefaultLinks:!0,disableUsedPercentage:!1},http:{trustedHeaders:[]},auth:{methods:{password:{enabled:!1,signup:!1},passkey:{enabled:!1},jwt:{enabled:!0,secret:$.auth.secret,algorithm:$.auth.algorithm,header:$.auth.header,userIdentifier:$.auth.userIdentifier,groupsClaim:$.auth.groupsClaim,userGroups:[$.auth.requiredGroup]}}},userDefaults:{sidebar:{sticky:!1},listing:{showHidden:!0},account:{lockPassword:!0,disableSettings:!1,disableUpdateNotifications:!0,loginMethod:"jwt",permissions:{admin:!1,api:!1,modify:!0,share:!1,realtime:!1,delete:!0,create:!0,download:!0}}}})}function b8(){if(Q6())return{uid:0,gid:0};return{uid:typeof process.geteuid==="function"?process.geteuid():0,gid:typeof process.getegid==="function"?process.getegid():0}}function SC($,J,X){if(!S4$($))rh$($,{recursive:!0,mode:X});let Q=$X($);if(!Q.isDirectory()||Q.isSymbolicLink())throw Error(`Files companion managed path is not a trusted directory: ${$}`);xC($,J.uid,J.gid),CC($,X)}function Jm$($,J,X){let Q=E4$("curl",["-fsSL","--proto","=https","--tlsv1.2","--retry","3","-o",J,$],{cwd:X.fileBrowserInstallRoot,encoding:"utf8",maxBuffer:65536,timeout:300000});if(Q.status!==0){let W=[Q.stderr,Q.stdout].filter((Y)=>typeof Y==="string"&&Y.trim().length>0).join(`
669
669
  `).trim().slice(-2000);throw Error(`Files companion download failed${W?`: ${W}`:""}`)}}function Xm$($,J,X,Q){let W=Pw(J,X.sha256);if(HL(J,X.sha256))return;YL(W,{recursive:!0,force:!0});let Y=ih$(I8(e5(J),".staging-"));try{let G=I8(Y,k4$);if(Q.download)Q.download(X.url,G);else Jm$(X.url,G,J);let z=g4$(G);if(z!==X.sha256.toLowerCase())throw Error(`Files companion SHA256 mismatch: expected ${X.sha256.toLowerCase()}, got ${z??"unreadable"}`);if(CC(G,493),xC(G,b8().uid,b8().gid),CC(Y,493),Q.versionProbe){let H=Q.versionProbe(G);if(!H.includes($.version)||!H.includes($.commit.slice(0,7)))throw Error("Files companion version probe did not match the pinned release")}ah$(Y,W)}finally{YL(Y,{recursive:!0,force:!0})}}function Qm$($){let J=[];for(let X of C4$(e5($)).sort()){if(!X.startsWith(".staging-"))continue;let Q=I8(e5($),X),W=$X(Q);if(!W.isDirectory()||W.isSymbolicLink())throw Error(`Files companion staging entry is not a trusted directory: ${X}`);YL(Q,{recursive:!0}),J.push(Q)}return J}function u4$($,J){return $0({version:$.version,commit:$.commit,assets:$.assets,config:J})}function T4$($,J,X,Q,W){if(!HL(J,X))return null;try{let Y=b8(),G=$X(J.fileBrowserConfigRoot);if(!G.isDirectory()||G.isSymbolicLink()||G.uid!==Y.uid||G.gid!==W.gid||(G.mode&511)!==v4$)return null;let z=$X(J.fileBrowserConfig);if(!z.isFile()||z.isSymbolicLink()||z.uid!==Y.uid||z.gid!==W.gid||(z.mode&511)!==f4$)return null;if(x4$(J.fileBrowserConfig,"utf8")!==Q)return null}catch{return null}return u4$($,Q)}function h4$($,J,X,Q={}){let W=Aw($);if(!W)return null;let Y=zL(W,Q.arch??process.arch),G=$m$(W,J),z=u4$(W,G),H=(Q.serviceIsolation??R4$)(J,W.sourceRoot),w=T4$(W,J,Y.sha256,G,H),V=HL(J,Y.sha256),U=X?.desiredRevision===z&&X.currentRevision===w;if(SC(J.fileBrowserInstallRoot,b8(),493),SC(e5(J),b8(),493),SC(J.fileBrowserConfigRoot,{uid:b8().uid,gid:H.gid},v4$),Qm$(J),!U||w===null)Xm$(W,J,Y,Q),Z$(J.fileBrowserConfig,G,{mode:f4$,trustedRoot:J.runRoot}),xC(J.fileBrowserConfig,b8().uid,H.gid);let q=()=>T4$(W,J,Y.sha256,G,H),Z=q();if(Z!==z)throw Error("Files companion candidate did not pass activation verification");return{receiptKey:eh$,receiptTarget:{desiredRevision:z,currentRevision:q,expectedCurrentRevision:Z},activeBinary:GL(J,Y.sha256),installed:!V}}function m4$($,J){let X=Aw($);if(!X)return null;let Q=zL(X,process.arch);return{programKind:"file-browser",runtime:"files",service:null,command:GL(J,Q.sha256),args:["-c",J.fileBrowserConfig],cwd:X.sourceRoot,env:{},resolvedSecretEnv:{}}}function c4$($,J={}){let X=Aw($);if(!X)return;let Q=`http://127.0.0.1:${X.port}${X.healthPath}`;if(!(J.probe?J.probe(Q):E4$("curl",["-fsS","--retry","5","--retry-connrefused","--retry-delay","1","--max-time","2",Q],{encoding:"utf8",timeout:12000}).status===0))throw Error(`Files companion readiness failed at ${Q}`)}function l4$($,J,X=process.arch){let Q=Aw($);if(!Q||!S4$(e5(J)))return[];let W=Pw(J,zL(Q,X).sha256),Y=[];for(let G of C4$(e5(J)).sort()){let z=I8(e5(J),G);if(z===W)continue;let H=$X(z);if(!H.isDirectory()||H.isSymbolicLink())throw Error(`Files companion candidate is not a trusted directory: ${sh$(z)}`);YL(z,{recursive:!0}),Y.push(z)}return Y}var k4$="filebrowser",th$="candidates",eh$="filebrowser",v4$=488,f4$=288;var d4$=F(()=>{Hw();t4();H8();EC();V1()});import{createHash as Wm$}from"node:crypto";function n4$($){let J=$.egressProfiles!==void 0?mz.parse($.egressProfiles):{profiles:[]};return Km$(J,[...Gm$(),...Hm$($),...Ym$($)])}function Ym$($){if(typeof $.mcp!=="object"||$.mcp===null||Array.isArray($.mcp)||!Object.hasOwn($.mcp,"servers"))return[];let J=wQ.parse($.mcp),X=[];for(let[Q,W]of Object.entries(J.servers)){if(!("url"in W))continue;let Y=Object.entries(W.headers).filter((H)=>typeof H[1]!=="string");if(Y.length===0)continue;let G=new URL(W.url),z=G.port||(G.protocol==="https:"?"443":"80");X.push({id:`managed-mcp-${p4$(Q)}`,enabled:!0,kind:"provider",match:{scheme:G.protocol.slice(0,-1),host:`${G.hostname.toLowerCase()}:${z}`,path:{type:"equals",value:G.pathname||"/"},headers:Object.fromEntries(Y.map(([H,w])=>[H,{type:"equals",value:vC(Q,H),prefix:w.prefix}])),query:{}},rewrite:{preservePath:!0,setHeaders:Object.fromEntries(Y.map(([H,w])=>[H,{type:"secretRef",secretRef:w.secretRef,prefix:w.prefix}]))},logging:{redactHeaders:Y.map(([H])=>H),redactUrlPatterns:[]},priority:70,owner:"mcp-projection",description:`Managed remote MCP credentials for ${Q}.`})}return X}function vC($,J){let X=Wm$("sha256").update(`${$}\x00${J.toLowerCase()}`).digest("hex").slice(0,16);return`${VQ}-mcp-${X}`}function Gm$(){let $=(J,X,Q,W)=>({id:J,enabled:!0,kind:"passthrough",match:{scheme:"https",host:X,pathPrefix:Q,headers:{},query:{}},logging:{redactHeaders:[],redactUrlPatterns:[]},priority:200,owner:"runtime-installer",description:W});return[$("runtime-installer-openclaw-install","openclaw.ai","/install-cli.sh","OpenClaw official installer script."),$("runtime-installer-nodejs-dist","nodejs.org","/dist/","Node.js release artifacts used by the OpenClaw official installer."),$("runtime-installer-npm-registry","registry.npmjs.org","/","npm package metadata and tarballs used by the OpenClaw official installer."),$("runtime-installer-hermes-install","hermes-agent.nousresearch.com","/install.sh","Hermes official installer script."),$("runtime-installer-uv","astral.sh","/uv/","uv installer bootstrap."),$("runtime-installer-uv-releases","releases.astral.sh","/installers/uv/","uv installer release script."),$("runtime-installer-github","github.com","/","Installer release metadata."),$("runtime-installer-github-api","api.github.com","/","Installer release metadata API."),$("runtime-installer-github-raw","raw.githubusercontent.com","/","Installer release script assets."),$("runtime-installer-github-objects","objects.githubusercontent.com","/","Installer release binary assets."),$("runtime-installer-github-release-assets","release-assets.githubusercontent.com","/","Installer release binary assets."),$("runtime-installer-pypi","pypi.org","/simple/","Hermes Python package index."),$("runtime-installer-pythonhosted","files.pythonhosted.org","/","Hermes Python package artifacts.")]}function zm$($){return $==="openai_chat"||$==="openai_responses"}function Hm$($){let J=[],X=new Set;for(let[Q,W]of wm$($)){let Y=Vm$(Q,W);if(!Y)continue;let G=VL(W.apiKeySecretRef),z=[Y.match.scheme,Y.match.host,Y.match.pathPrefix??"",G??""].join(":");if(X.has(z))continue;X.add(z),J.push(Y)}return J}function wm$($){let J=qm$($.providers),X=kC($.terminalTooling),Q=kC(X?.codex),W=Zm$(Q?.provider),Y=wL(typeof Q?.provider_id==="string"?Q.provider_id:null);if(Y&&W)J.push([Y,W]);return J}function Vm$($,J){let X=Bm$(J?.baseUrl),Q=wL(J?.apiMode),W=VL(J?.apiKeySecretRef);if(!iQ(J)||!X||!W||!zm$(Q))return null;if(wL(J.status)&&wL(J.status)!=="ok")return null;let Y=new URL(X),G=Y9($)?x1:$;return{id:G==="default"?"managed-provider":`managed-provider-${p4$(G)}`,enabled:!0,kind:"provider",match:{scheme:Y.protocol.replace(/:$/,""),host:Y.host.toLowerCase(),pathPrefix:Um$(Y.pathname),headers:{authorization:{type:"equals",value:VQ,prefix:"Bearer "}},query:{}},rewrite:{preservePath:!0,setHeaders:{authorization:{type:"secretRef",secretRef:W,prefix:"Bearer "}}},logging:{redactHeaders:["authorization"],redactUrlPatterns:[]},priority:80,owner:"provider-projection"}}function Um$($){if($==="/")return $;return`${$.replace(/\/+$/,"")}/`}function VL($){let J=$?.trim();return J?.startsWith("secret://")&&J.length>9?J:null}function iQ($){return $.managed_by==="clawdi"}function qm$($){if(!$||typeof $!=="object"||Array.isArray($))return[];return Object.entries($).filter((J)=>{let[X,Q]=J;return X.trim().length>0&&typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}).sort(([J],[X])=>{if(J==="default")return-1;if(X==="default")return 1;return J.localeCompare(X)})}function Zm$($){let J=kC($);if(!J)return null;return{baseUrl:Rw(J.baseUrl),apiMode:Rw(J.apiMode),apiKeySecretRef:Rw(J.apiKeySecretRef),managed_by:Rw(J.managed_by),status:Rw(J.status)}}function kC($){return typeof $==="object"&&$!==null&&!Array.isArray($)?$:null}function wL($){return $?.trim()||null}function Rw($){return $===null||typeof $==="string"?$:void 0}function Bm$($){if(!$)return null;try{let J=new URL($);if(!["http:","https:","ws:","wss:"].includes(J.protocol))return null;return J.toString().replace(/\/+$/,"")}catch{return null}}function Km$($,J){let X=new Set(J.map((Q)=>Q.id));return{profiles:[...$.profiles.filter((Q)=>!X.has(Q.id)),...J]}}function p4$($){return $.toLowerCase().replace(/[^a-z0-9-_.]+/g,"-").replace(/^[^a-z0-9]+/,"").replace(/[^a-z0-9]+$/,"")||"provider"}var UL=F(()=>{B8();G8();n7();PB()});import{existsSync as o4$,rmSync as r4$}from"node:fs";import{join as ZL}from"node:path";function Lm$($,J){for(let X of[ZL(J,"venv","bin","hermes"),ZL($,".local","bin","hermes")])if(X6(X))return X;throw Error("installed Hermes Skill CLI is unavailable")}function i4$($,J,X){return{path:s4$($,J),schemaVersion:a4$,skillId:J,ownershipIdentity:X,target:qL($,J)}}function Nm$($){if($.source.type==="project")return $.source.installUrl;let J=new URL($.source.url),[X,Q]=J.pathname.slice(1).split("/");if(!X||!Q)throw Error("Hermes exact-source URL requires a canonical GitHub repository");let W=$.source.path.split("/").map((G)=>encodeURIComponent(G)).join("/"),Y=W?`${W}/SKILL.md`:"SKILL.md";return`https://raw.githubusercontent.com/${encodeURIComponent(X)}/${encodeURIComponent(Q)}/${$.source.commit}/${Y}`}function fC($,J){return V0(Lm$($.home,$.appRoot),J,$.home,$.appRoot,{timeoutMs:120000,maxBufferBytes:1048576})}function Fm$($){let J=E1($),X=J?.get("SKILL.md");if(!J||!X)return null;let Q=X.toString("utf8").replaceAll("\\","/");if(/(?:references|templates|scripts|assets|examples)\/(?:[^\s)`"'<>]*\/)?\.\.(?:\/|$)/m.test(Q))return null;let W=new Map([["SKILL.md",X]]);for(let Y of Q.matchAll(Dm$)){let G;try{G=decodeURIComponent((Y[1]??"").replace(/[.,;:]+$/,"").split(/[?#]/,1)[0]??"")}catch{return null}let z=G.split("/");if(!Om$.has(z[0]??"")||z.some((w)=>!w||w==="."||w===".."))return null;let H=J.get(G);if(!H)return null;W.set(G,H)}return W}function gC($,J){return sW(Fm$($),E1(J))}var a4$="clawdi.hermesManifestSkillReceipt.v2",qL=($,J)=>ZL($,".hermes","skills",J),s4$=($,J)=>ZL($,".hermes","skills",".clawdi-manifest-receipts",`${J}.json`),Om$,Dm$,t4$;var e4$=F(()=>{Kq();V1();Om$=new Set(["references","templates","scripts","assets","examples"]),Dm$=/(?:\]\(|`|(?:^|[\s"']))((?:references|templates|scripts|assets|examples)\/[^\s)`"'<>]+)/gm;t4$={install($){return tW($.skill,(J)=>{let X=qL($.home,$.skill.skillId),Q=i4$($.home,$.skill.skillId,$.skill.sourceIdentity),W=o4$(X);if(W&&!$.previouslyReserved)throw Error("Hermes Skill target is not paired with a manifest reservation");if(gC(J,X)&&dX(Q))return"unchanged";if(W&&!qh(Q))throw Error("refusing to replace a Hermes Skill without a matching Clawdi ownership receipt");return Bq({target:X,receipt:Q.path,operation:()=>{let Y=["skills","install",Nm$($.skill),"--name",$.skill.skillId,"--yes"];if($.previouslyReserved)Y.push("--force");let G=fC($,Y);if(G.status!==0)throw Error(`Hermes official Skill install failed: ${String(G.stderr||G.stdout).trim()||"unknown error"}`);if(!gC(J,X)){if(!W){let z=fC($,["skills","uninstall",$.skill.skillId,"--yes"]);if(z.status!==0)throw Error(`Hermes official install produced invalid Skill bytes and native rollback failed: ${String(z.stderr||z.stdout).trim()||"unknown error"}`)}throw Error("Hermes official install did not preserve the exact native catalog projection")}return Zq(Q),"installed"}})})},verifyOwned($){return tW($.skill,(J)=>gC(J,qL($.home,$.skill.skillId))&&dX(i4$($.home,$.skill.skillId,$.skill.sourceIdentity)))},uninstall($){let J=qL($.home,$.skillId),X={path:s4$($.home,$.skillId),schemaVersion:a4$,skillId:$.skillId,ownershipIdentity:$.ownershipIdentity,target:J};if(!o4$(J))return r4$(X.path,{force:!0}),"absent";if(!dX(X))throw Error("Hermes Skill bytes no longer match the manifest ownership receipt");let Q=fC($,["skills","uninstall",$.skillId,"--yes"]);if(Q.status!==0)throw Error(`Hermes official Skill uninstall failed: ${String(Q.stderr||Q.stdout).trim()||"unknown error"}`);return r4$(X.path,{force:!0}),"removed"}}});import{existsSync as $0$,rmSync as yC}from"node:fs";import{isAbsolute as jm$,join as LL,resolve as X0$}from"node:path";function Im$($){for(let J of[LL($,".local","bin","openclaw"),LL($,".openclaw","bin","openclaw")])if(X6(J))return J;return null}function Y0$($){let J=Im$($);if(J)return J;throw Error("installed OpenClaw Skill CLI is unavailable")}function BL($,J,X){return{path:_m$($,J),schemaVersion:bm$,skillId:J,ownershipIdentity:X,target:KL($,J),exclude:W0$}}function G0$($){let J=Y0$($),X=V0(J,["agents","list","--json"],$,$,{timeoutMs:15000,maxBufferBytes:1048576});if(X.status!==0)throw Error("OpenClaw official agent workspace roster is unavailable");let Q;try{Q=Jj(String(X.stdout))}catch{throw Error("OpenClaw official agent workspace roster is malformed")}let W=Q.filter((Y)=>Y.id===Q0$);if(W.length!==1||!jm$(W[0].workspace))throw Error("OpenClaw official agent workspace roster is malformed");return X0$(W[0].workspace)}function J0$($){if(G0$($.home)!==X0$($.workspaceRoot))throw Error("OpenClaw official agent workspace changed during Skill reconciliation")}function uC($,J){return sW(E1($),E1(J,{exclude:W0$}))}function Am$($){let J=[];if($.error)J.push(`spawn error: ${$.error.message}`);if($.signal)J.push(`terminated by signal ${$.signal}`);for(let X of[$.stderr,$.stdout])if(typeof X==="string"&&X.trim()){J.push(X.trim());break}if(J.length===0&&typeof $.status==="number")J.push(`exit code ${$.status} without output`);return J.join("; ")||"process failed without details"}var Q0$="main",Mm$=".openclaw/source-origin.json",W0$,bm$="clawdi.openclawManifestSkillReceipt.v2",KL=($,J)=>LL($,"skills",J),_m$=($,J)=>LL($,"skills",".clawdi-manifest-receipts",`${J}.json`),z0$;var H0$=F(()=>{Nq();Kq();V1();W0$=new Set([Mm$]);z0$={resolveWorkspace($){return G0$($.home)},installDirectory($){let J=KL($.workspaceRoot,$.skillId),X=BL($.workspaceRoot,$.skillId,$.ownershipIdentity);if(uC($.sourceDir,J)&&dX(X))return"unchanged";if($0$(J)&&!Uh(X))throw Error("refusing to replace an OpenClaw Skill without a matching Clawdi ownership receipt");return J0$($),Bq({target:J,receipt:X.path,operation:()=>{let Q=V0(Y0$($.home),["skills","install",$.sourceDir,"--agent",Q0$,"--as",$.skillId,"--force"],$.home,$.home,{timeoutMs:120000,maxBufferBytes:1048576});if(Q.status!==0)throw Error(`OpenClaw official Skill install failed: ${Am$(Q)}`);if(!uC($.sourceDir,J))throw Error(`OpenClaw installed Skill outside the configured agent workspace or changed exact source bytes: ${J}`);return J0$($),Zq(X),"installed"}})},install($){return tW($.skill,(J)=>this.installDirectory({home:$.home,workspaceRoot:$.workspaceRoot,skillId:$.skill.skillId,sourceDir:J,ownershipIdentity:$.skill.sourceIdentity}))},hasOwnershipReceipt($){return eF(BL($.workspaceRoot,$.skillId,$.ownershipIdentity))},verifyOwned($){return tW($.skill,(J)=>uC(J,KL($.workspaceRoot,$.skill.skillId))&&eF(BL($.workspaceRoot,$.skill.skillId,$.skill.sourceIdentity)))},cleanupManifestOwned($){let J=KL($.workspaceRoot,$.skillId),X=BL($.workspaceRoot,$.skillId,$.ownershipIdentity);if(!$0$(J))return yC(X.path,{force:!0}),"absent";if(!dX(X))throw Error("refusing manifest cleanup because OpenClaw Skill bytes no longer match the ownership receipt");return yC(J,{recursive:!0}),yC(X.path,{force:!0}),"removed"}}});function NL($,J){let X=$.projection?.providers;if(!X||Object.keys(X).length===0)return null;let Q=hC(X,J,$),W=Tm$($,J);if(!W)return null;let Y=Q.map(([G,z])=>{if(typeof z!=="object"||z===null||Array.isArray(z))return null;let H=z,w=typeof H.baseUrl==="string"?H.baseUrl:void 0,V=w0$(H),U=typeof H.apiKeySecretRef==="string"?H.apiKeySecretRef:void 0,q=cC(G,H,J);if(xm$(H))return null;if(!w)return null;let Z=Cm$(H,Boolean(U));if(!Z)return null;let K=Em$(H,G===W.provider_id?W:null);return{id:G,type:Sm$(H),base_url:w,api_mode:V,managed_by:Rm$(H),auth:Z,runtime_env_name:U||Z.type!=="none"?q:void 0,models:K}}).filter((G)=>G!==null);if(Y.length===0)return null;return{catalog:{schema_version:1,providers:Y,defaults:{chat_provider_id:W.provider_id}},primaryModel:W}}function Rm$($){let J=$.managed_by;return J==="clawdi"||J==="user"?J:void 0}function hC($,J,X){if(!J)return Object.entries($).sort(([W],[Y])=>W.localeCompare(Y));return(X?.runtimes?.[J]?.provider_ids??[]).filter((W)=>Object.hasOwn($,W)).map((W)=>[W,$[W]])}function Tm$($,J){return(J?$.runtimes[J]:void 0)?.primary_model??null}function Em$($,J){let X=w0$($),Q=EJ($.model),G=(Array.isArray($.models)?$.models:[]).map((z)=>aQ(z)?z:null).filter((z)=>z!==null).map((z)=>{let H=EJ(z.id);if(!H)return null;let w=EJ(z.api_mode);return{...z,id:H,...w&&rX(w)?{api_mode:w}:{}}}).filter((z)=>z!==null);if(Q&&!G.some((z)=>z.id===Q))G.unshift({id:Q,api_mode:X});if(J&&!G.some((z)=>z.id===J.model))G.unshift({id:J.model,api_mode:X});return G.filter((z,H,w)=>w.findIndex((V)=>V.id===z.id)===H)}function w0$($){let J=$.apiMode;if(typeof J==="string"&&rX(J))return J;return"openai_chat"}function Sm$($){let J=EJ($.type);return J&&oG(J)?J:"custom_openai_compatible"}function Cm$($,J){let X=aQ($.auth);if(X){let Q=EJ(X.type),W=EJ(X.tool),Y=EJ(X.profile);if(Q==="agent_profile"&&W==="codex"&&Y)return{type:"agent_profile",tool:"codex",profile:Y};if(Q==="api_key"||Q==="secret_ref"){if(J)return{type:"api_key",source:"managed"};return null}if(Q&&Q!=="none")return null}if(J)return{type:"api_key",source:"managed"};if(mC($))return null;return{type:"none"}}function xm$($){let J=EJ($.status);return Boolean(J&&J!=="ok")}function mC($){if($.apiKeyRequired===!0)return!0;let J=aQ($.auth),X=J?EJ(J.type):null;return X==="api_key"||X==="secret_ref"}function cC($,J,X){if(X==="openclaw"&&iQ(J))return Pm$;let Q=typeof J.runtimeEnvName==="string"?J.runtimeEnvName:null;if(Q&&lC(Q))return Q;return`CLAWDI_PROVIDER_${$.toUpperCase().replace(/[^A-Z0-9]/g,"_")}_API_KEY`}function km$($,J){let X=aQ($.projection?.providers);if(!X)return{};let Q={};for(let[W,Y]of hC(X,J,$)){let G=aQ(Y);if(!G)continue;if(!iQ(G))continue;if(!EJ(G.apiKeySecretRef))continue;let H=cC(W,G,J);if(!lC(H))continue;Q[H]=VQ}return Q}function vm$($,J){let X=aQ($.projection?.providers);if(!X)return{};let Q={};for(let[W,Y]of hC(X,J,$)){let G=aQ(Y);if(!G)continue;if(iQ(G))continue;let z=EJ(G.apiKeySecretRef);if(!z)continue;let H=cC(W,G,J);if(!lC(H))continue;Q[H]=z}return Q}function Tw($,J,X={}){let Q=km$($,J),W=vm$($,J);if(X.validateOverlap)fm$(J??"default",Q,W);return{placeholderEnv:Q,secretEnv:W}}function fm$($,J,X){for(let Q of Object.keys(J)){if(X[Q]===void 0)continue;throw Error(`runtime ${$} provider env ${Q} is both managed and BYOK-backed`)}}function OL($,J,X){if(Object.keys(X).length===0)return J;let Q=J?.env??{};for(let W of Object.keys(X))if(J?.secretEnv?.[W]!==void 0)throw Error(`runtime ${$} provider placeholder ${W} conflicts with secretEnv`);return{...J??{},prependPath:J?.prependPath??[],env:{...Q,...X}}}function V0$($,J,X,Q){if(Object.keys(Q).length===0)return X;for(let W of Object.keys(Q))if(X.secretEnv?.[W]!==void 0)throw Error(`runtime ${$} service ${J} provider placeholder ${W} conflicts with secretEnv`);return{...X,env:{...X.env??{},...Q}}}function aQ($){return typeof $==="object"&&$!==null&&!Array.isArray($)?$:null}function EJ($){return typeof $==="string"&&$.trim()?$.trim():null}function lC($){return/^[A-Za-z_][A-Za-z0-9_]*$/.test($)}var Pm$="CLAWDI_OPENCLAW_API_KEY";var U0$=F(()=>{B8();G8();UL()});import{lstatSync as gm$,readFileSync as ym$}from"node:fs";function B0$(){return{schemaVersion:"clawdi.runtimeInstallReceipts.v1",officialServices:{},channelPlugins:{},companions:{}}}function o3($){return $.installReceipts}function pC($){let J=o3($),X;try{X=gm$(J)}catch(Y){if(Y.code==="ENOENT")return null;throw nC("could not be inspected",Y)}if(!X.isFile())throw Error("runtime install receipts are not a trusted regular file");if((X.mode&511)!==384)throw Error("runtime install receipts do not have private file permissions");if(typeof process.getuid==="function"&&X.uid!==process.getuid())throw Error("runtime install receipts do not have the expected file owner");let Q;try{Q=JSON.parse(ym$(J,"utf8"))}catch(Y){throw nC("could not be decoded",Y)}let W=Z0$.safeParse(Q);if(!W.success)throw Error("runtime install receipts do not match the expected schema");return W.data}function K0$($,J){let X=Z0$.parse($);try{e4(J,o3(J),`${JSON.stringify(X,null,2)}
670
670
  `,{mode:384,dirMode:493})}catch(W){throw nC("could not be persisted",W)}let Q=pC(J);if(!Q||JSON.stringify(Q)!==JSON.stringify(X))throw Error("runtime install receipts did not pass post-write verification")}function nC($,J){let X=typeof J==="object"&&J!==null&&"code"in J&&typeof J.code==="string"?` (${J.code})`:"";return Error(`runtime install receipts ${$}${X}`)}var q0$,dC,Z0$;var oC=F(()=>{J6();e6();q0$=L.string().regex(/^[a-f0-9]{64}$/),dC=L.object({desiredRevision:q0$,currentRevision:q0$}).strict(),Z0$=L.object({schemaVersion:L.literal("clawdi.runtimeInstallReceipts.v1"),officialServices:L.record(L.string().min(1),dC),channelPlugins:L.record(L.string().min(1),dC),companions:L.object({filebrowser:dC.optional()}).strict().default({})}).strict()});import{chmodSync as rC,chownSync as um$,existsSync as aC,lchownSync as hm$,lstatSync as r3,mkdirSync as iC,readdirSync as tC,readFileSync as O0$,readlinkSync as mm$,rmSync as L0$,symlinkSync as cm$,writeFileSync as lm$}from"node:fs";import{basename as dm$,dirname as Ew,isAbsolute as nm$,join as SJ,relative as pm$,resolve as FL}from"node:path";function D0$($,J){let X=new Set([J.managedConfig,J.syncState,J.providerHealthStatus,J.egressEngineStatus,J.manifestLastGood,J.managedSecretCacheFile,J.appliedState,J.oauthCredentialRoot,o3(J),J.runConfigRoot,J.egressProfileBundle,J.installInventory,J.managedResourceRoot,J.projectionRoot,SJ(J.instanceRoot,$.instanceId),J.daemonAuthToken,SJ(J.managedSecretRoot,"egress-secrets.json"),J.instanceData,J.sensitiveInstanceData,J.egressAddon,J.egressTransparentEnv,J.egressSystemCaFile,J.liveSyncEnvironmentIndex]);for(let Q of["clawdi-runtime-watch","clawdi-daemon","clawdi-runtime-sidecar"]){let W=`${Q}.service`;X.add(SJ(J.systemdSystemRoot,W)),X.add(SJ(J.systemdEnvRoot,`${W}.env`))}if($.companions?.filebrowser)X.add(SJ(J.systemdSystemRoot,"clawdi-files.service")),X.add(SJ(J.systemdEnvRoot,"clawdi-files.service.env"));return im$(J,X),[...X].sort()}function eC($){om$($.runtimeUserTargets,$.runtimeUserTrustedRoots,$.runtimeUserSymlinkTargets);let J=[...new Set($.rootTargets)].sort();for(let z of $.trustedRootDirectories)rm$(z);let X=[...new Set($.runtimeUserTargets)].sort(),Q=J.find((z)=>X.includes(z));if(Q)throw Error(`runtime mutation target has multiple owners: ${Q}`);let W=[...J,...X].sort();for(let[z,H]of W.entries()){let w=W.slice(z+1).find((V)=>V.startsWith(`${H}/`));if(w)throw Error(`runtime mutation targets overlap: ${H} and ${w}`)}let Y=[...new Set([...$.metadataTargets,...am$(W)])].sort(),G=Y.find((z)=>W.includes(z));if(G)throw Error(`runtime mutation target also used as metadata target: ${G}`);return{entries:new Map([...J.map((z)=>[z,sC(z,!0)]),...X.map((z)=>[z,sC(z,!1)]),...Y.map((z)=>[z,sm$(z)])])}}function om$($,J,X){let Q=[...new Set(J.map((G)=>FL(G)))].sort((G,z)=>z.length-G.length),W=[...new Set($.map((G)=>FL(G)))].sort(),Y=new Set(X.map((G)=>FL(G)));for(let G of Y)if(!W.includes(G))throw Error(`runtime-user symlink target is not a mutation target: ${G}`);for(let G of W){let z=Q.find((w)=>{let V=pm$(w,G);return V===""||!V.startsWith("..")&&!nm$(V)});if(!z)throw Error(`runtime-user mutation target is outside trusted roots: ${G}`);let H=G;while(!0){try{let V=r3(H);if(V.isSymbolicLink()&&(H!==G||!Y.has(G)))throw Error(`runtime-user mutation path contains a symlink: ${H}`);if(H!==G&&!V.isDirectory())throw Error(`runtime-user mutation ancestor is not a directory: ${H}`)}catch(V){if(!(V instanceof Error&&("code"in V)&&V.code==="ENOENT"))throw V}if(H===z)break;let w=Ew(H);if(w===H)throw Error(`runtime-user mutation target has no trusted boundary: ${G}`);H=w}}}function F0$($,J){return[J.runConfigRoot,J.systemdEnvRoot,J.installInventory,J.oauthCredentialRoot,J.managedResourceRoot,J.projectionRoot,SJ(J.instanceRoot,$.instanceId)]}function rm$($){let J;try{J=r3($)}catch(X){if(X.code==="ENOENT")return;throw X}if(!J.isDirectory()||J.isSymbolicLink())throw Error(`runtime managed directory is not a real directory: ${$}`);if((J.mode&18)!==0&&!j0$($))throw Error(`runtime managed directory is group/world writable: ${$}`);if(Q6()&&J.uid!==0)throw Error(`runtime managed directory is not root-owned: ${$}`)}function j0$($){let J=process.geteuid?.()??process.getuid?.(),X=Ew(FL($));for(;;){let Q=r3(X);if(Q.isSymbolicLink()||!Q.isDirectory())return!1;if(Q.uid===J&&(Q.mode&63)===0)return!0;let W=Ew(X);if(W===X)return!1;X=W}}function i3($){for(let[X,Q]of $.entries)if(Q.kind!=="metadata")jL(X,Q);let J=[...$.entries].filter((X)=>X[1].kind==="metadata");for(let[X,Q]of J.filter(([,W])=>W.existed).sort(([W],[Y])=>W.length-Y.length))jL(X,Q);for(let[X,Q]of J.filter(([,W])=>!W.existed).sort(([W],[Y])=>Y.length-W.length))jL(X,Q)}function im$($,J){if(!aC($.systemdSystemRoot))return;for(let X of tC($.systemdSystemRoot)){let Q=SJ($.systemdSystemRoot,X);if(X.endsWith(".service")&&(X.startsWith("clawdi-")||N0$(Q)))J.add(Q);if(!X.endsWith(".service.d"))continue;let W=SJ(Q,"10-clawdi-hosted.conf");if(N0$(W))J.add(W)}}function N0$($){try{return O9(O0$($,"utf-8"))}catch{return!1}}function am$($){return[...new Set($.filter((J)=>dm$(J)==="10-clawdi-hosted.conf").map((J)=>Ew(J)))].sort()}function sC($,J){let X;try{X=r3($)}catch(W){if(W.code==="ENOENT")return{kind:"missing"};throw W}if(X.isSymbolicLink())return{kind:"symlink",target:mm$($),uid:X.uid,gid:X.gid};if(X.isFile())return{kind:"file",content:O0$($),mode:X.mode&511,uid:X.uid,gid:X.gid};if(!X.isDirectory())throw Error(`unsupported runtime live-state path: ${$}`);let Q=X.mode&511;if(J&&(Q&18)!==0&&!j0$($))throw Error(`runtime live-state snapshot directory is group/world writable: ${$}`);if(J&&Q6()&&X.uid!==0)throw Error(`runtime live-state snapshot directory is not root-owned: ${$}`);return{kind:"directory",mode:Q,uid:X.uid,gid:X.gid,entries:new Map(tC($).sort().map((W)=>[W,sC(SJ($,W),J)]))}}function sm$($){try{let J=r3($);if(!J.isDirectory()||J.isSymbolicLink())throw Error(`runtime mutation metadata target is not a real directory: ${$}`);return{kind:"metadata",existed:!0,mode:J.mode&511,uid:J.uid,gid:J.gid}}catch(J){if(J.code==="ENOENT")return{kind:"metadata",existed:!1};throw J}}function DL($,J,X,Q){let W=r3($);if(W.uid===J&&W.gid===X)return;if(Q)hm$($,J,X);else um$($,J,X)}function jL($,J){if(J.kind==="metadata"){if(!J.existed){if(aC($)&&tC($).length===0)L0$($,{recursive:!0});return}if(!aC($))iC($,{recursive:!0,mode:J.mode});rC($,J.mode),DL($,J.uid,J.gid,!1);return}if(L0$($,{recursive:!0,force:!0}),J.kind==="missing")return;if(iC(Ew($),{recursive:!0}),J.kind==="symlink"){cm$(J.target,$),DL($,J.uid,J.gid,!0);return}if(J.kind==="file"){lm$($,J.content,{mode:J.mode}),rC($,J.mode),DL($,J.uid,J.gid,!1);return}iC($,{recursive:!0,mode:J.mode}),rC($,J.mode);for(let[X,Q]of J.entries)jL(SJ($,X),Q);DL($,J.uid,J.gid,!1)}var M0$=F(()=>{oC();V1()});import{createHash as P0$,randomUUID as R0$}from"node:crypto";import{chmodSync as T0$,closeSync as s3,existsSync as JX,fsyncSync as $x,lstatSync as Sw,mkdirSync as tm$,openSync as AL,readFileSync as PL,readSync as em$,realpathSync as RL,renameSync as E0$,rmSync as TL,statSync as $c$,writeSync as S0$}from"node:fs";import{basename as C0$,dirname as EL,join as W0,relative as Jc$,resolve as l1}from"node:path";function v0$($){return W0($.installInventory,Xc$)}function f0$($){let J=Wx(v0$($.paths));if(J)r0$(J,$.home);let X=new Set;if($.desiredRuntime)X.add($.desiredRuntime);if(J)X.add(J.artifact.runtime);return[...X]}function g0$($){let J=u0$($);if($.runtime==="hermes"&&!JX(W0(J.root,"package.json")))return[W0(a3(J),"node_modules")];let X=J.targets.map((Q)=>W0(J.root,Q.relativePath));if($.runtime==="hermes")X.push(W0(a3(J),"node_modules",".hermes-pkg-hash"));return X}function y0$($){let J=v0$($.paths),X=Wx(J);if(X)r0$(X,$.home);if(!$.desiredRuntime)return I0$(J,$.home);if(!$.appRoot)throw Error(`managed WhatsApp ${$.desiredRuntime} artifact root is unavailable`);if($.desiredRuntime==="hermes")Qc$($.home,$.appRoot);let Q=u0$({runtime:$.desiredRuntime,home:$.home,appRoot:$.appRoot}),W=h0$(Q),Y=W.version,G=Q.targets.map((Z)=>m0$(Q,Z));if(l0$(Q,G),X&&!Qx(X.artifact,Q)){let Z=I0$(J,$.home);if(Z.status==="rollback-refused")throw Error(`managed WhatsApp compatibility could not recover the previous artifact: ${Z.errors.join(", ")}`);X=null}let z=G.flatMap((Z)=>Z.hunks);if(!X){if(z.every((Z)=>Z.state==="after")){if(Q.runtime==="hermes")ML(a3(Q));return{status:"compatible",receiptPath:J}}if(!z.every((Z)=>Z.state==="before"))throw Error(`managed WhatsApp compatibility refused mixed before/after hunks without an ownership receipt for ${Q.runtime}`)}let H=X?X.artifact.baileys.observedVersion!==Y:!1,w=z.filter((Z)=>Z.state==="before");if(X&&H&&w.length===0){if(i0$(J),Q.runtime==="hermes")ML(a3(Q));return{status:"compatible",receiptPath:J}}if(X&&w.length===0){if(Q.runtime==="hermes")ML(a3(Q));return{status:"already-patched",receiptPath:J}}let V=Wc$(G,X,H),U=G.map((Z)=>d0$(Z,new Set(Z.hunks.filter((K)=>K.state==="before").map((K)=>K.hunk.id)),"after")),q=wc$(Q,Y,U,V);if(zc$(J,q),n0$(U,[{path:W.path,expectedSha256:W.sha256}]),Q.runtime==="hermes")ML(a3(Q));return{status:"applied",receiptPath:J}}function I0$($,J){let X=Wx($);if(!X)return{status:"inert",receiptPath:$};let Q=_L(X.artifact.runtime,J),W=[];if(!Qx(X.artifact,Q))W.push("managed WhatsApp compatibility receipt does not match the audited artifact");else if(Vc$(Q.root)){let Y=null;try{Y=h0$(Q)}catch(z){W.push(String(z))}let G=[];if(W.length===0)for(let z of Q.targets)try{G.push(m0$(Q,z))}catch(H){W.push(String(H))}if(W.length===0)try{l0$(Q,G)}catch(z){W.push(String(z))}if(W.length>0)return{status:"rollback-refused",receiptPath:$,errors:W};if(Y?.version===X.artifact.baileys.observedVersion){let z=new Map(X.artifact.targets.map((w)=>[w.relativePath,w])),H=G.map((w)=>{let V=z.get(w.target.relativePath);if(!V)throw Error("managed WhatsApp receipt target is missing");return d0$(w,new Set(V.ownedHunkIds),"before")});n0$(H,[{path:Y.path,expectedSha256:Y.sha256}])}}return i0$($),{status:"rolled-back",receiptPath:$}}function Qc$($,J){let X=W0($,".hermes","hermes-agent");if(l1(J)!==l1(X))throw Error(`managed WhatsApp Hermes app root must be ${X}`);let Q=W0(J,"scripts","whatsapp-bridge"),W=W0(Q,"node_modules","@whiskeysockets","baileys","package.json");if(JX(W))return;for(let z of["package.json","package-lock.json"])if(!JX(W0(Q,z)))throw Error(`managed WhatsApp Hermes bridge is missing ${z}`);let Y=W0($,".local","bin","npm"),G=V0(JX(Y)?Y:"npm",["ci","--ignore-scripts","--silent"],$,Q,{timeoutMs:300000});if(G.status!==0){let z=String(G.stderr||G.stdout||"npm ci failed").trim().slice(-1000);throw Error(`managed WhatsApp Hermes dependency install failed: ${z}`)}if(!JX(W))throw Error("managed WhatsApp Hermes dependency install did not produce Baileys")}function ML($){let J=W0($,"package.json"),X=W0($,"node_modules",".hermes-pkg-hash"),Q=`${Yx(J).slice(0,16)}
671
671
  `;if(JX(X)){if(!Sw(X).isFile()||RL(X)!==l1(X))throw Error(`managed WhatsApp Hermes dependency stamp must be a real file: ${X}`);if(PL(X,"utf8")===Q)return}p0$(X,Q,420,493),b4(X)}function u0$($){if($.runtime==="openclaw"){let X=W0($.home,".openclaw");if(l1($.appRoot)!==l1(X))throw Error(`managed WhatsApp OpenClaw app root must be ${X}`);return _L("openclaw",$.home)}let J=W0($.home,".hermes","hermes-agent");if(l1($.appRoot)!==l1(J))throw Error(`managed WhatsApp Hermes app root must be ${J}`);return _L("hermes",$.home)}function _L($,J){if($==="openclaw")return{runtime:$,root:W0(J,".openclaw","extensions","whatsapp","node_modules","baileys"),packageName:"baileys",targets:b0$};let X=W0(J,".hermes","hermes-agent","scripts","whatsapp-bridge");return{runtime:$,root:W0(X,"node_modules","@whiskeysockets","baileys"),packageName:"@whiskeysockets/baileys",targets:b0$,hermesBridgeRoot:X}}function a3($){if(!$.hermesBridgeRoot)throw Error("managed WhatsApp Hermes bridge root is missing");return $.hermesBridgeRoot}function h0$($){Hc$($.root);let J=W0($.root,"package.json");o0$($.root,J);let X=PL(J,"utf8"),Q;try{Q=JSON.parse(X)}catch(z){throw Error(`managed WhatsApp compatibility could not read ${J}: ${String(z)}`)}let W=Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:null,Y=W?Reflect.get(W,"name"):null,G=W?Reflect.get(W,"version"):null;if(Y!==$.packageName)throw Error(`managed WhatsApp compatibility requires package ${$.packageName}; found ${String(Y)}`);if(typeof G!=="string"||!n4(G)||!G.startsWith("7."))throw Error(`managed WhatsApp compatibility requires valid Baileys SemVer major 7; found ${String(G)}`);return{version:G,path:J,sha256:Gx(X)}}function m0$($,J){let X=W0($.root,J.relativePath);if(!JX(X))throw Error(`managed WhatsApp compatibility artifact is missing ${X}`);o0$($.root,X);let Q=PL(X,"utf8");return{target:J,path:X,content:Q,sha256:Gx(Q),hunks:J.hunks.map((W)=>c0$(Q,W))}}function c0$($,J){let X=_0$($,J.before),Q=_0$($,J.after);return{hunk:J,beforeMatches:X,afterMatches:Q,state:X.length===1&&Q.length===0?"before":X.length===0&&Q.length===1?"after":"unknown"}}function _0$($,J){let X=[],Q=0;while(Q<=$.length-J.length){let W=$.indexOf(J,Q);if(W<0)break;X.push(W),Q=W+1}return X}function l0$($,J){let X=J.flatMap((Q)=>Q.hunks.flatMap((W)=>W.state==="unknown"?[`${Q.path}#${W.hunk.id} (before=${W.beforeMatches.length}, after=${W.afterMatches.length})`]:[]));if(X.length>0)throw Error(`managed WhatsApp compatibility patch refused non-unique or changed ${$.runtime} hunks: ${X.join(", ")}`)}function Wc$($,J,X){let Q=new Map((J?.artifact.targets??[]).map((W)=>[W.relativePath,W]));return new Map($.map((W)=>{let Y=new Set;if(!X)for(let G of Q.get(W.target.relativePath)?.ownedHunkIds??[])Y.add(G);for(let G of W.hunks)if(G.state==="before")Y.add(G.hunk.id);return[W.target.relativePath,Y]}))}function d0$($,J,X){let Q=new Set($.hunks.map((z)=>z.hunk.id));for(let z of J)if(!Q.has(z))throw Error(`managed WhatsApp patch references unknown hunk ${z}`);let Y=[...$.hunks.flatMap((z)=>{if(!J.has(z.hunk.id)||z.state===X)return[];if(z.state==="unknown")throw Error(`managed WhatsApp patch cannot mutate unknown hunk ${z.hunk.id}`);let H=z.state==="before"?z.hunk.before:z.hunk.after,w=X==="after"?z.hunk.after:z.hunk.before,U=(z.state==="before"?z.beforeMatches:z.afterMatches)[0];if(U===void 0)throw Error(`managed WhatsApp hunk ${z.hunk.id} is missing`);return[{id:z.hunk.id,offset:U,source:H,replacement:w}]})].sort((z,H)=>z.offset-H.offset);for(let z=1;z<Y.length;z+=1){let H=Y[z-1],w=Y[z];if(H&&w&&H.offset+H.source.length>w.offset)throw Error(`managed WhatsApp patch hunks overlap: ${H.id} and ${w.id}`)}let G=$.content;for(let z of Y.reverse())G=`${G.slice(0,z.offset)}${z.replacement}${G.slice(z.offset+z.source.length)}`;for(let z of $.hunks){let H=c0$(G,z.hunk),w=J.has(z.hunk.id)?X:z.state;if(H.state!==w)throw Error(`managed WhatsApp hunk mutation verification failed for ${z.hunk.id}`)}return{state:$,content:G,observedBeforeSha256:$.sha256,observedAfterSha256:Gx(G)}}function n0$($,J=[]){let X=$.flatMap((Q)=>Q.content===Q.state.content?[]:[{path:Q.state.path,expectedSha256:Q.observedBeforeSha256,content:Q.content}]);Gc$(X,[...J,...$.map((Q)=>({path:Q.state.path,expectedSha256:Q.observedBeforeSha256}))]);for(let Q of $)if(Yx(Q.state.path)!==Q.observedAfterSha256)throw Error(`managed WhatsApp compatibility verification failed for ${Q.state.path}`)}function Yc$($,J){let X=W0(EL($),`.${C0$($)}.clawdi-stage-${R0$()}`),Q=$c$($).mode&511,W=null;try{W=AL(X,"wx",Q);let Y=Buffer.from(J),G=0;while(G<Y.length)G+=S0$(W,Y,G);return $x(W),s3(W),W=null,T0$(X,Q),b4(X),X}catch(Y){throw TL(X,{force:!0}),Y}finally{if(W!==null)s3(W)}}function Gc$($,J=$){let X=[];try{for(let Q of $)X.push({...Q,stagingPath:Yc$(Q.path,Q.content)});for(let Q of J)if(Yx(Q.path)!==Q.expectedSha256)throw Error(`managed WhatsApp compatibility artifact changed during reconcile: ${Q.path}`);for(let Q of X)E0$(Q.stagingPath,Q.path),b4(Q.path),Xx(EL(Q.path))}finally{for(let Q of X)TL(Q.stagingPath,{force:!0})}}function zc$($,J){p0$($,`${JSON.stringify(J,null,2)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clawdi",
3
- "version": "0.13.56",
3
+ "version": "0.13.58",
4
4
  "description": "iCloud for AI Agents — cross-agent sessions, skills, memory, and vault.",
5
5
  "license": "MIT",
6
6
  "type": "module",