clawdi 0.13.82 → 0.13.83

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 +1 -1
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -489,7 +489,7 @@ ${W.errors.join(`
489
489
  `)}
490
490
  `}}function Hn$($){return`'${$.replace(/'/g,"'\\''")}'`}function cJ$($,J){S$($,J,{mode:e4})}function Bn$($){let J=YJ($,"OpenClaw config"),X=YJ(J.models,"OpenClaw models"),Q=YJ(X.providers,"OpenClaw models.providers"),W=[];for(let[G,z]of Object.entries(Q)){if(!y8(G))continue;let U=YJ(z,`OpenClaw provider ${G}`),H=f4(U,"baseUrl")??f4(U,"base_url");if(!H)continue;let B=Kn$(f4(U,"api"))??Ff(f4(U,"apiMode")??f4(U,"api_mode")),V=Of(f4(U,"type")??f4(U,"provider")??dJ$(G,H,{api_mode:B??f4(U,"api")})),w=f4(U,"keyEnv")??f4(U,"key_env")??PJ$(U.apiKey)??PJ$(U.api_key),q=On$(U.models),K={id:G,type:V,base_url:H,auth:w?{type:"secret_ref",ref:`env:${w}`}:{type:"none"}};if(q)K.models=[{id:q}];if(K.api_mode=B??tQ(V),w)K.runtime_env_name=w;W.push(K)}let Y=Fn$(J);return{schema_version:1,providers:W,defaults:Y}}function Vn$($){let J;try{J=S1($)}catch(G){throw Error(`Hermes config is not valid YAML: ${G instanceof Error?G.message:String(G)}`)}let X=YJ(J,"Hermes config"),Q=[...wn$(RJ$(X,"providers")),...qn$(X.custom_providers)];if(Q.length===0)throw Error("Hermes config does not contain a providers block.");let W=RJ$(X,"model"),Y=W?Nn$(f4(W,"provider")):void 0;return{schema_version:1,providers:Q,defaults:Y?{chat_provider_id:Y}:void 0}}function wn$($){if(!$)return[];let J=[];for(let[X,Q]of Object.entries($)){if(!y8(X))continue;let W=YJ(Q,`Hermes provider ${X}`),Y=lJ$(X,W);if(Y)J.push(Y)}return J}function qn$($){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=YJ(X,"Hermes custom provider"),W=f4(Q,"name");if(!W)continue;let Y=Dn$(W),G=lJ$(Y,Q);if(G)J.push(G)}return J}function lJ$($,J){let X=f4(J,"api")??f4(J,"url")??f4(J,"base_url")??f4(J,"baseUrl");if(!X)return;let Q=f4(J,"key_env")??f4(J,"api_key_env"),W=Of(f4(J,"type")??dJ$($,X,J)),Y={id:$,type:W,base_url:X,auth:Q?{type:"secret_ref",ref:`env:${Q}`}:{type:"none"}},G=f4(J,"default_model")??f4(J,"model")??f4(J,"default");if(G)Y.models=[{id:G}];let z=Ff(Ln$(f4(J,"transport"))??f4(J,"api_mode")??tQ(W));if(z)Y.api_mode=z;if(Q)Y.runtime_env_name=Q;let U=f4(J,"name");if(U)Y.label=U;return Y}function dJ$($,J,X){let Q=$.toLowerCase(),W=pJ$(J).toLowerCase(),Y=f4(X,"transport")??f4(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 Ln$($){if($==="chat_completions")return"openai_chat";if($==="codex_responses")return"openai_responses";if($==="anthropic_messages")return"anthropic_messages";return}function Kn$($){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 Nn$($){if(!$)return;let J=$.startsWith("custom:")?$.slice(7):$;return y8(J)?J:void 0}function Dn$($){let X=$.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[^a-z]+/,"").replace(/-+/g,"-").replace(/[-.]+$/g,"").slice(0,63).replace(/[-.]+$/g,"");if(y8(X))return X;let W=`provider-${X.replace(/^[^a-z0-9]+/,"").slice(0,54).replace(/[-.]+$/g,"")||"custom"}`.slice(0,63).replace(/[-.]+$/g,"");return y8(W)?W:"provider-custom"}function RJ$($,J){let X=$[J];if(X===void 0||X===null)return;return YJ(X,J)}function DO($,J){let X=$.providers.find((Q)=>Q.id===J);if(!X)throw Error(`AI Provider not found: ${J}`);return X}function YJ($,J){if(typeof $!=="object"||$===null||Array.isArray($))throw Error(`${J} must be an object.`);return $}function f4($,J){let X=$[J];return typeof X==="string"&&X.trim()?X.trim():void 0}function On$($){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 Fn$($){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 y8(Y)?{chat_provider_id:Y}:void 0}function PJ$($){if(typeof $!=="object"||$===null||Array.isArray($))return;let J=$;if(J.source!=="env")return;return typeof J.id==="string"?J.id:void 0}function jn$($){if($.type==="secret_ref")return In$($.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 Zn$($,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 Mn$($){return $.models?.find((J)=>J.id.trim())?.id}function _n$($){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 In$($){if($.startsWith("env:"))return $;if($.startsWith("clawdi://"))return"clawdi://...";return"redacted"}function pJ$($){try{return new URL($).host}catch{return $}}function nJ$($,J,X){if(X){console.log(JSON.stringify({[$]:J.id,provider:J},null,2));return}console.log(N.green(`✓ ${bn$($)} AI Provider ${J.id}`)),console.log(N.dim(`Catalog: ${WO()}`))}function An$($,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 bn$($){return`${$.slice(0,1).toUpperCase()}${$.slice(1)}`}var TJ$="codex",Pp$="codex",Ep$,Kf;var N9=j(()=>{aJ();k$();MW();$f();zf();L4();C6();KO();Ep$={host:"localhost",path:"/auth/callback",ports:[1455,1457]};Kf=class Kf extends Error{constructor(){super("Timed out waiting for OAuth callback.")}}});var f1={};V$(f1,{channelSyncCommandsCommand:()=>gn$,channelSendCommand:()=>fn$,channelRotateTokenCommand:()=>kn$,channelPairCodeCommand:()=>xn$,channelListCommand:()=>Rn$,channelLinksCommand:()=>Sn$,channelLinkCommand:()=>Cn$,channelGetCommand:()=>En$,channelDeleteCommand:()=>yn$,channelCreateCommand:()=>Tn$,channelBindingsCommand:()=>vn$,channelAvailableCommand:()=>Pn$});async function Rn$($={}){let J=new W$,X=L$(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(N.gray("Create a private bot: clawdi channel create telegram my-bot")),console.log(N.gray("List available channel bots: clawdi channel available"));return}nB(["ID","PROVIDER","VISIBILITY","STATUS","NAME"],X.map((Q)=>[QG(Q.id),Q.provider,Q.visibility,Q.status,Q.name]))}async function Pn$($={}){let J=new W$,X=L$(await J.GET("/v1/channels/bot-pool"));if($.json){console.log(JSON.stringify({bot_pool:X},null,2));return}nn$(X)}async function En$($,J={}){let X=new W$,Q=L$(await X.GET("/v1/channels/{account_id}",{params:{path:{account_id:$}}}));if(J.json){console.log(JSON.stringify({channel:Q},null,2));return}hn$(Q)}async function Tn$($,J,X={}){let Q=new W$,W={provider:in$($),name:J,agent_id:X.agent??null,provider_token:tn$(X),config:X.config?an$(X.config,"--config"):null,secrets:en$(X.secret,X.secretEnv)},Y=L$(await Q.POST("/v1/channels",{body:W}));if(X.json){console.log(JSON.stringify({channel:Y},null,2));return}un$(Y)}async function Sn$($,J={}){let X=new W$,Q=L$(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(N.gray(`Create one: clawdi channel link ${$} --agent <agent-id>`));return}nB(["LINK ID","AGENT ID","STATUS","CREATED"],Q.map((W)=>[QG(W.id),QG(W.agent_id),W.status,W.created_at]))}async function Cn$($,J){let X=new W$,Q=L$(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}mn$(Q)}async function kn$($,J){let X=new W$,Q=L$(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}cn$(Q)}async function xn$($,J={}){if(J.agent&&J.link){console.error(N.red("Pass either --agent or --link, not both.")),process.exitCode=1;return}let X=rn$(J.ttl),Q=new W$,W=L$(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}ln$(W)}async function fn$($,J){if(J.binding&&J.chat){console.error(N.red("Pass either --binding or --chat, not both.")),process.exitCode=1;return}if(!J.binding&&!J.chat){console.error(N.red("Pass --binding or --chat.")),process.exitCode=1;return}let X=new W$,Q=L$(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}dn$(Q)}async function vn$($,J={}){let X=new W$,Q=L$(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}nB(["BINDING ID","CHAT","TYPE","LINK","STATUS"],Q.map((W)=>[QG(W.id),W.external_chat_name??W.external_chat_id,W.external_chat_type??"-",W.agent_link_id?QG(W.agent_link_id):"-",W.status]))}async function gn$($,J={}){let X=new W$,Q=L$(await X.POST("/v1/channels/{account_id}/commands/sync",{params:{path:{account_id:$}},body:{commands:J.commands?sn$(J.commands):null,guild_id:J.guild??null}}));if(J.json){console.log(JSON.stringify({sync:Q},null,2));return}pn$(Q)}async function yn$($,J={}){if(!J.yes){if(!V0())throw Error("Cannot prompt for channel deletion in a non-interactive shell. Pass --yes to confirm explicitly.");if(!await JO(`Archive channel ${$}?`,!1)){console.log("Cancelled.");return}}let X=new W$;if(L$(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(`${N.green("✓")} Archived channel ${$}.`)}function hn$($){console.log(`${N.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(N.gray(`List links: clawdi channel links ${$.id}`))}function un$($){if(console.log(`${N.green("✓")} Created ${$.provider} channel ${N.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(N.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(N.gray(" Store the agent token now; it is shown once."));console.log(N.gray(`Generate a pair code: clawdi channel pair-code ${$.id}`))}function mn$($){if(console.log(`${N.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(N.gray(" Store the agent token now; it is shown once.")),console.log(N.gray(`Pair an external chat: clawdi channel pair-code ${$.account_id} --link ${$.id}`))}function cn$($){if(console.log(`${N.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(N.gray(" Store the new token now; it is shown once."))}function ln$($){if(console.log(`${N.green("✓")} Pair code created.`),console.log(` Code: ${N.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(N.gray(`Send this in the external chat: ${$.pairing_command}`))}function dn$($){if(console.log(`${N.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 pn$($){if(console.log(`${N.green("✓")} Synced ${$.provider} commands.`),$.commands.length===0)return;nB(["COMMAND","DESCRIPTION"],$.commands.map((J)=>[rJ$(J.name??J.command??"-"),rJ$(J.description??"-")]))}function nn$($){let J=Object.entries($.providers).flatMap(([X,Q])=>Q.map((W)=>[QG(W.id),X,W.access,W.visibility,W.status,on$(W.capabilities),W.name]));if(J.length===0){console.log("No available channel bots.");return}nB(["ID","PROVIDER","ACCESS","VISIBILITY","STATUS","CAPABILITIES","NAME"],J)}function on$($){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 in$($){if($==="telegram"||$==="discord"||$==="whatsapp")return $;throw Error("provider must be one of: telegram, discord, whatsapp")}function rn$($){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 an$($,J){let X;try{X=JSON.parse($)}catch{throw Error(`${J} must be valid JSON.`)}if(!sJ$(X))throw Error(`${J} must be a JSON object.`);return X}function sn$($){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(!sJ$(X))throw Error(`--commands[${Q}] must be a JSON object.`);return X})}function tn$($){if($.providerToken&&$.providerTokenEnv)throw Error("Pass only one of --provider-token or --provider-token-env.");if($.providerTokenEnv)return aJ$($.providerTokenEnv,"--provider-token-env");return $.providerToken??null}function en$($,J){if((!$||$.length===0)&&(!J||J.length===0))return null;let X={};for(let Q of $??[]){let[W,Y]=oJ$(Q,"--secret");iJ$(X,W,Y)}for(let Q of J??[]){let[W,Y]=oJ$(Q,"--secret-env");iJ$(X,W,aJ$(Y,"--secret-env"))}return X}function oJ$($,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 iJ$($,J,X){if(Object.hasOwn($,J))throw Error(`Duplicate secret name: ${J}.`);$[J]=X}function aJ$($,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 sJ$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function rJ$($){if(typeof $==="string")return $;if($===null||$===void 0)return"-";return JSON.stringify($)}function QG($){return $.length>12?$.slice(0,8):$}function nB($,J){let X=$.map((Q,W)=>Math.max(Q.length,...J.map((Y)=>Y[W]?.length??0)));console.log($.map((Q,W)=>N.bold(Q.padEnd(X[W]))).join(" "));for(let Q of J)console.log(Q.map((W,Y)=>W.padEnd(X[Y])).join(" "))}var v1=j(()=>{k$();L4();dB()});function OO($){return jf($).entries}function jf($){let J=[],X=[];for(let Q of $.split(/\r?\n/)){let W=Q.trim();if(!W||W.startsWith("#"))continue;let Y=/^(?:export\s+)?([^=\s]+)\s*=\s*(.*)$/.exec(W);if(!Y)continue;if(!$o$.test(Y[1])){X.push(Y[1]);continue}J.push([Y[1],Jo$(Y[2].trim())])}return{entries:J,skippedInvalidIdentifiers:X}}function Jo$($){if($.startsWith('"')){let X=tJ$($,'"');if(X!==-1)return $.slice(1,X).replace(/\\n/g,`
491
491
  `).replace(/\\"/g,'"').replace(/\\\\/g,"\\")}if($.startsWith("'")){let X=tJ$($,"'");if(X!==-1)return $.slice(1,X)}let J=$.indexOf(" #");return J===-1?$:$.slice(0,J).trimEnd()}function tJ$($,J){for(let X=1;X<$.length;X+=1){if($[X]!==J)continue;if(J==='"'&&Xo$($,X))continue;return X}return-1}function Xo$($,J){let X=0;for(let Q=J-1;Q>=0&&$[Q]==="\\";Q-=1)X+=1;return X%2===1}var $o$;var FO=j(()=>{$o$=/^[A-Za-z_][A-Za-z0-9_]*$/});import{readFileSync as Qo$,rmSync as Wo$}from"node:fs";function jO($){try{return $8$(Qo$($.daemonAuthToken,"utf-8"))}catch{return null}}function Yo$($,J){let X=$8$(J);if(!X)throw Error("runtime auth token must be non-empty and contain no control characters");return C4($,$.daemonAuthToken,`${X}
492
- `,{mode:e4,dirMode:T4}),$.daemonAuthToken}function Go$($){return F6($,Zf)}function eJ$($,J){let X=Go$(J);if(X)return Yo$($,X);return Wo$($.daemonAuthToken,{force:!0}),null}function $8$($){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 Zf="secret://clawdi/auth-token";var Mf=j(()=>{C6();tJ();C0()});import{isAbsolute as zo$}from"node:path";function w8($,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&&zo$(W)?W:J.userHome}var _f=()=>{};function iB($){let J=If($),X=If(J?.authCert),Q=If(X?.PUBLIC_KEY),W=J?.capability,Y=X?.ISSUER,G=X?.SERIAL,z=Q?.data;if(!J||!Af(J,["authCert","capability","schemaVersion"])||J.schemaVersion!=="clawdi.managedWhatsAppSocket.v1"||typeof W!=="string"||!/^clawdi_[a-f0-9]{32}$/.test(W)||!X||!Af(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||!Af(Q,["data","type"])||Q.type!=="Buffer"||typeof z!=="string"||!Uo$(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 If($){return $&&typeof $==="object"&&!Array.isArray($)?$:null}function Af($,J){return Object.keys($).sort().join("\x00")===[...J].sort().join("\x00")}function Uo$($,J){let X=Buffer.from($,"base64");return X.length===J&&X.toString("base64")===$}var WG="x-clawdi-whatsapp-link-capability",oB="clawdi.managedWhatsAppSocket",bf="clawdi.managedWhatsAppSocket.v1";import{createHash as Ho$}from"node:crypto";function J8$($){if($.links.length===0)return[];let J=Bo$($.controlPlaneApiUrl),X=[...$.links].sort((Q,W)=>Q.linkId.localeCompare(W.linkId)).map((Q)=>({id:`native-whatsapp-baileys-${Vo$(Q.linkId)}`,enabled:!0,kind:"websocket",match:{scheme:"wss",host:"web.whatsapp.com",path:{type:"equals",value:"/ws/chat"},headers:{[WG]:{type:"secretRefEquals",secretRef:Q.capabilitySecretRef}},query:{}},rewrite:{upstreamBaseUrl:J,preservePath:!1,removeHeaders:[WG],setHeaders:{authorization:{type:"secretRef",secretRef:Q.agentTokenSecretRef,prefix:"Bearer "}}},logging:{redactHeaders:[WG,"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:{[WG]:{type:"exists"}},query:{}},logging:{redactHeaders:[WG],redactUrlPatterns:[]},priority:49,owner:"clawdi-native-whatsapp",description:"Fail closed when a managed WhatsApp capability is misplaced, stale, or invalid."}),X}function Bo$($){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 Vo$($){return Ho$("sha256").update($).digest("hex").slice(0,16)}var X8$=()=>{};import{createHash as wo$}from"node:crypto";import{join as G8$}from"node:path";function Pf($,J=O$({mode:"hosted"})){if(!$.channelBindings)return $;let X=$.secretValues??{},Q=$.channelBindings.map((G)=>Ko$(G,X)),W=Do$($.manifest,Q,J),Y=To$(Q.filter((G)=>G.account.provider==="whatsapp"),W.projection?.channelCredentials);return{...$,manifest:W,sourceManifest:$.sourceManifest??$.manifest,secretValues:{...X,...Y}}}function Ko$($,J){let X=F6(J,$.agentTokenSecretRef),Q=F6(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=So$($.accountKey,$.linkId),Y=Co$($.accountKey,$.linkId),G=Ef($.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"?No$($,J):void 0}}function No$($,J){let X=$.credential.credsSecretRef,Q=ko$($.accountKey,$.credential.id);if(X!==Q)throw Error("runtime bundle WhatsApp credential ref does not match its credential");let W=F6(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=V8$(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 Do$($,J,X){let Q=Ro$(J,$.controlPlane.apiUrl),W=w8($,X),Y=go$($),G=Fo$(J,W,Y),z={...$,projection:{...$.projection??{},channels:Oo$(J,W,Y),channelCredentials:G},egressProfiles:Po$($.egressProfiles,Q)};return Zo$(jo$(z,J),J)}function Oo$($,J,X){let Q={};for(let W of $){let Y=W.account.provider;if(Y==="telegram"){let G=Rf(Q,"telegram",W.accountKey);G.accounts[W.accountKey]={enabled:!0,botToken:Q8$(W),dmPolicy:"open",groupPolicy:"open",allowFrom:["*"],capabilities:{inlineButtons:"all"},groups:{"*":{requireMention:!1}}};continue}if(Y==="discord"){let G=Rf(Q,"discord",W.accountKey);G.accounts[W.accountKey]={enabled:!0,token:Q8$(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=Rf(Q,"whatsapp",W.accountKey),z=B8$(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 Fo$($,J,X){return $.map((Q)=>B8$(Q,J,X)).filter((Q)=>Q!==null).sort((Q,W)=>`${Q.provider}:${Q.accountKey}:${Q.credentialId}`.localeCompare(`${W.provider}:${W.accountKey}:${W.credentialId}`))}function jo$($,J){let X=$.runtimes.openclaw;if(!X?.enabled)return $;Mo$(J);let Q=X.run??{env:{},prependPath:[]},W=Io$(Q.secretEnv??{});for(let Y of J)W[H8$(Y)]=Y.placeholderSecretRef;if(!X.run&&Object.keys(W).length===0)return $;return{...$,runtimes:{...$.runtimes,openclaw:{...X,run:{...Q,secretEnv:W}}}}}function Zo$($,J){let X=$.runtimes.hermes;if(!X?.enabled)return $;let Q=rB(J,"telegram"),W=rB(J,"discord"),Y=rB(J,"whatsapp"),G=X.run??{env:{},prependPath:[]},z=Y8$(G.env??{},qo$),U=Y8$(G.secretEnv??{},Lo$);if(Q)z.TELEGRAM_ALLOW_ALL_USERS="true",z.HERMES_TELEGRAM_DISABLE_FALLBACK_IPS="true",U.TELEGRAM_BOT_TOKEN=Q.placeholderSecretRef;if(W)z.DISCORD_ALLOW_ALL_USERS="true",U.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:U}}}}}function rB($,J){let X=$.filter((Q)=>Q.account.provider===J);if(X.length>1)throw Error(_o$(J));return X[0]??null}function Mo$($){for(let J of["telegram","discord","whatsapp"])rB($,J)}function _o$($){return`This Agent has multiple active ${$==="telegram"?"Telegram":$==="discord"?"Discord":$} bots. Unlink the extras until only one remains.`}function Q8$($){return{source:"env",provider:"default",id:H8$($)}}function H8$($){return`${z8$}${W8$($.account.provider)}_${W8$($.accountKey)}${U8$}`}function W8$($){return $.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"CHANNEL"}function Io$($){return Object.fromEntries(Object.entries($).filter(([J])=>!Ao$(J)))}function Ao$($){return $.startsWith(z8$)&&$.endsWith(U8$)}function Y8$($,J){let X=new Set(J),Q={};for(let[W,Y]of Object.entries($))if(!X.has(W))Q[W]=Y;return Q}function Rf($,J,X){let Q=$[J];if(bo$(Q))return Q;let W={enabled:!0,defaultAccount:X,accounts:{}};return $[J]=W,W}function bo$($){return typeof $==="object"&&$!==null&&!Array.isArray($)&&typeof $.accounts==="object"&&$.accounts!==null&&!Array.isArray($.accounts)}function Ro$($,J){let X=yo$(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:`${ho$(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=rB($,"whatsapp");if(W&&!Tf(W))throw Error(`managed WhatsApp Link ${W.linkId} has no valid synthetic auth`);return Q.push(...J8$({controlPlaneApiUrl:J,links:W?[{linkId:W.linkId,agentTokenSecretRef:W.secretRef,capabilitySecretRef:W.placeholderSecretRef}]:[]})),Q}function Po$($,J){let X=[...$?.profiles??[]],Q=new Set(J.map((W)=>W.id));return{profiles:[...X.filter((W)=>!Q.has(W.id)&&!Eo$(W)),...J]}}function Eo$($){return $.owner==="clawdi-native-channels"||$.owner==="clawdi-native-whatsapp"||$.id==="direct-provider-passthrough"||$.id.startsWith("direct-provider-passthrough-")}function To$($,J){let X={},Q=new Set(S5(J).map((W)=>W.credsJsonSecretRef));for(let W of $){let Y=Tf(W);if(Y){let G=Y.credential.credsSecretRef;if(Q.has(G))X[G]=JSON.stringify(xo$(W,Y))}}return X}function So$($,J){return`secret://channels/whatsapp/${$}/links/${J}/agent-token`}function Co$($,J){return`secret://channels/whatsapp/${$}/links/${J}/egress-capability`}function ko$($,J){return`secret://channels/whatsapp/${$}/credentials/${J}/creds-json`}function Ef($,J){return`clawdi_${wo$("sha256").update(`whatsapp:${$}:${J}`).digest("hex").slice(0,32)}`}function B8$($,J,X){let Q=Tf($);if(!Q)return null;let W=fo$(J,$.accountKey),Y=vo$(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 Tf($){if($.account.provider!=="whatsapp")return null;let J=$.credential;if(!J)return null;let{material:X}=J,Q;try{Q=iB({schemaVersion:bf,capability:Ef($.accountKey,$.linkId),authCert:X.authCert})}catch{return null}return{credential:J,creds:X.creds,authCert:Q.authCert}}function xo$($,J){let X=J.creds.additionalData,Q=X===void 0?{}:V8$(X);if(!Q)throw Error("managed WhatsApp synthetic creds.additionalData must be an object");let W=iB({schemaVersion:bf,capability:Ef($.accountKey,$.linkId),authCert:J.authCert});return{...J.creds,additionalData:{...Q,[oB]:W}}}function fo$($,J){return G8$($,".openclaw","credentials","whatsapp",J)}function vo$($){return G8$($,".hermes","platforms","whatsapp","session")}function go$($){return{openclaw:$.runtimes.openclaw?.enabled===!0,hermes:$.runtimes.hermes?.enabled===!0}}function V8$($){if(!$||typeof $!=="object"||Array.isArray($))return null;return $}function yo$($){return $.replace(/\/+$/,"")}function ho$($){if($.startsWith("https://"))return`wss://${$.slice(8)}`;if($.startsWith("http://"))return`ws://${$.slice(7)}`;return $}var qo$,Lo$,z8$="CLAWDI_CHANNEL_",U8$="_AGENT_TOKEN";var w8$=j(()=>{k6();_f();tJ();X8$();qo$=["TELEGRAM_ALLOW_ALL_USERS","DISCORD_ALLOW_ALL_USERS","HERMES_TELEGRAM_DISABLE_FALLBACK_IPS","WHATSAPP_MODE","WHATSAPP_ALLOWED_USERS","WHATSAPP_ALLOW_ALL_USERS"],Lo$=["TELEGRAM_BOT_TOKEN","DISCORD_BOT_TOKEN"]});import{dirname as q8$,isAbsolute as L8$,relative as uo$,resolve as Sf}from"node:path";function lo$(){return process.env.CLAWDI_RUNTIME_MODE?.trim().toLowerCase()||"missing"}function xf($,J={}){let X=J.expectedIdentity??K8$,Q=lo$(),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,U=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 H=(J.resolveUserIdentity??pe)(G);if(U=`${G} (${H.uid}:${H.gid})`,H.uid===0||H.gid===0)z=`hosted runtime user ${G} resolved to root identity ${H.uid}:${H.gid}`;else if(H.uid!==X.uid||H.gid!==X.gid)z=`hosted runtime user ${G} must resolve to ${X.uid}:${X.gid}; resolved ${H.uid}:${H.gid}`;else for(let[B,V,w]of[["CLAWDI_RUNTIME_UID",process.env.CLAWDI_RUNTIME_UID?.trim(),H.uid],["CLAWDI_RUNTIME_GID",process.env.CLAWDI_RUNTIME_GID?.trim(),H.gid]])if(V&&V!==String(w)){z=`${B} must match the resolved hosted runtime identity ${w}; resolved ${V}`;break}}catch(H){z=H instanceof Error?H.message:String(H)}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:U,...z?{error:z}:{}}}}function aB($,J,X={}){let Q=xf($,X),W=[Q.mode,Q.home,Q.user].find((U)=>!U.ok)?.error;if(W)throw Error(W);let Y=Sf($.clawdiHome),G=Sf($.serviceStateRoot),z=uo$(Sf($.userHome),Y);if(z===""||!z.startsWith("..")&&!L8$(z))throw Error(`hosted CLAWDI_HOME must be outside the tenant home; resolved ${$.clawdiHome}`);if(!L8$($.clawdiHome)||Y===G||q8$(Y)!==q8$(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")$3($);return{identity:X.expectedIdentity??K8$,assertPlatformRoots:()=>$3($)}}var Cf="/home/clawdi",kf="clawdi",mo$=10001,co$=10001,K8$;var ZO=j(()=>{_0();C0();K8$={home:Cf,user:kf,uid:mo$,gid:co$}});import{spawnSync as vf}from"node:child_process";import{createHash as do$}from"node:crypto";import{accessSync as po$,constants as no$,existsSync as F8$,lstatSync as oo$,mkdirSync as io$,mkdtempSync as ro$,readdirSync as ao$,readFileSync as j8$,readlinkSync as Z8$,renameSync as so$,rmSync as tB,statSync as to$,symlinkSync as eo$}from"node:fs";import{tmpdir as $i$}from"node:os";import{dirname as XX,join as JX,resolve as K8}from"node:path";function M8$($){if($.mode!=="hosted"||$.userHome!==Cf||process.env.CLAWDI_RUNTIME_USER?.trim()!==kf||typeof process.geteuid==="function"&&process.geteuid()!==0)return;let J;try{J=oo$(sB)}catch(Q){if(Q.code==="ENOENT")return;throw Q}if(!J.isSymbolicLink())throw Error(`hosted tenant PATH contains an unmanaged clawdi entrypoint: ${sB}`);let X=K8(XX(sB),Z8$(sB));if(X!==Yi$)throw Error(`hosted tenant PATH contains an unmanaged clawdi symlink target: ${X}`);tB(sB)}function _8$($,J,X={}){let Q=PO(J,X);if(Q.selfReexec){let B=GG(J.cliBootstrapStatus);return YG("deferred",J,{packageSpec:$.clawdiCli?.packageSpec?.trim()||null,registry:B?.registry??null,npmPrefix:B?.npmPrefix??J.cliNpmPrefix,activeTarget:B?.activeTarget??null,version:B?.version??null,error:`CLI transaction recovery ${Q.status}; re-exec is required`},!0)}let W=$.clawdiCli?.packageSpec?.trim();if(!W)return YG("not_requested",J,{packageSpec:null,registry:null,activeTarget:null,version:null});Bi$(W);let Y=Hi$($),G=GG(J.cliBootstrapStatus);if(Vi$(G,J,W,Y))return YG("current",J,{packageSpec:W,registry:Y,npmPrefix:G.npmPrefix??eB(G.activeTarget),activeTarget:G.activeTarget??null,version:G.version??null});let z=Li$(J,W);if(z)return l5(J,{packageSpec:W,registry:Y,npmPrefix:z.npmPrefix,activeTarget:z.activeTarget,version:z.version},z.verification),YG("current",J,{packageSpec:W,registry:Y,npmPrefix:z.npmPrefix,activeTarget:z.activeTarget,version:z.version});if(X.deferInstall)return YG("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 U=qi$(J,G);if(U&&V1(J.cliManagedBin)===U.activeTarget&&(G?.status!=="installed"||G.source!=="npm"||G.packageSpec!==U.packageSpec||(G.registry??null)!==U.registry||G.npmPrefix!==U.npmPrefix||G.activePath!==J.cliManagedBin||G.activeTarget!==U.activeTarget||G.version!==U.version)){let B=L8(J,U);if(!B)throw Error("active clawdi CLI changed during verification");l5(J,U,B)}let H=Ki$(J,W,Y);return Di$(J,{newIdentity:{packageSpec:W,registry:Y,npmPrefix:H.npmPrefix,activeTarget:H.activeTarget,version:H.version},previousIdentity:U,rollbackEligible:X.rollbackEligible===!0&&U!==null}),b8$(J.cliManagedBin,H.activeTarget),l5(J,{packageSpec:W,registry:Y,npmPrefix:H.npmPrefix,activeTarget:H.activeTarget,version:H.version},H.verification),P8$(J),zG(J,[H.npmPrefix,U?.npmPrefix??null]),YG("installed",J,{packageSpec:W,registry:Y,npmPrefix:H.npmPrefix,activeTarget:H.activeTarget,version:H.version},!0)}function YG($,J,X,Q=!1){return{status:$,...X,npmPrefix:X.npmPrefix??J.cliNpmPrefix,npmCache:X.npmCache??J.cliNpmCache,activePath:J.cliManagedBin,selfReexec:Q}}function Hi$($){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 Bi$($){if(MH.safeParse($).success)return;throw Error(`clawdi CLI packageSpec must be clawdi@<exact-semver> or a managed bootstrap tarball: ${$}`)}function GG($){if(!F8$($))return null;try{let J=JSON.parse(j8$($,"utf-8"));if(typeof J!=="object"||J===null||Array.isArray(J))return null;return J}catch{return null}}function tW($){io$($,{recursive:!0})}function gf($,J){let X=K8($.cliNpmPrefix),Q=K8(J);return Q===X||Q.startsWith(`${X}/`)}function AO($,J){return gf($,J)&&J.endsWith("/bin/clawdi")}function Vi$($,J,X,Q){if(!$)return!1;if($.status!=="installed"||$.source!=="npm")return!1;if($.activePath!==J.cliManagedBin)return!1;if(!$.activeTarget)return!1;if(!AO(J,$.activeTarget))return!1;if(V1(J.cliManagedBin)!==$.activeTarget)return!1;if(!$.npmPrefix||K8($.npmPrefix)!==K8(eB($.activeTarget)))return!1;if(!d5($.activeTarget))return!1;if(!$.version)return!1;let W=UG(X);if(W&&$.version!==W)return!1;let Y=process.env.CLAWDI_RUNTIME_ALLOW_TEST_INSTALLERS==="1"&&$.packageSpec===LW&&W===$.version;if($.packageSpec!==X&&!Y)return!1;if(($.registry??null)!==Q)return!1;if(!d5(J.cliManagedBin))return!1;let G=eW($.activeTarget);if(G&&$.verification&&bO($.verification,G)&&A8$($.verification))return!0;if(!G)return!1;try{if(JV($.activeTarget)!==$.version)return!1;XV($.activeTarget);let z=$V($.activeTarget,G);return l5(J,{packageSpec:Y?LW:X,registry:Q,npmPrefix:$.npmPrefix,activeTarget:$.activeTarget,version:$.version},z),!0}catch{return!1}}function wi$($,J){let X=V1($.cliManagedBin);if(!X||!AO($,X))return null;let Q=eB(X);if(!gf($,Q))return null;if(!d5(X)||!d5($.cliManagedBin))return null;try{let W=eW(X);if(!W)return null;let Y=JV(X);XV(X),$V(X,W);let G=`clawdi@${Y}`;if(!BY.safeParse(G).success)return null;let z=J?.packageSpec,U=J?.registry??null,H=z?UG(z):null,B=J?.status==="installed"&&J.source==="npm"&&J.activePath===$.cliManagedBin&&J.activeTarget===X&&J.npmPrefix!==void 0&&K8(J.npmPrefix)===K8(Q)&&J.version===Y&&z!==void 0&&MH.safeParse(z).success&&(H===null||H===Y)&&(U===null||U==="https://registry.npmjs.org");return{packageSpec:B&&z?z:G,registry:B?U:null,npmPrefix:Q,activeTarget:X,version:Y}}catch{return null}}function qi$($,J){let X=wi$($,J);if(!X)return null;let Q=GJ($).transaction;if(Q?.phase!=="activated"||Q.rollback||!Q.rollbackEligible||!Q.previousIdentity||Q.newIdentity.activeTarget!==X.activeTarget)return X;return L8($,Q.previousIdentity)?Q.previousIdentity:X}function Li$($,J){let X=UG(J);if(!X)return null;let Q=I8$($,X),W=V1($.cliManagedBin);if(W!==JX(Q,"bin","clawdi"))return null;if(!AO($,W))return null;if(!d5(W)||!d5($.cliManagedBin))return null;let Y=eW(W);if(!Y)return null;let G=JV(W);if(G!==X)return null;XV(W);let z=$V(W,Y);return{npmPrefix:eB(W),activeTarget:W,version:G,verification:z}}function UG($){if(!BY.safeParse($).success)return null;return $.slice(7)}function Ki$($,J,X){let Q=Ni$($,J,X);if(ji$($,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;tW(XX(XX($.cliManagedBin))),tW(XX($.cliManagedBin)),tW($.cliNpmPrefix),tW(W),tW($.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=vf("npm",Y,{encoding:"utf8",timeout:Ji$,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}`:""}${_O(G.stdout,G.stderr)}`);let z=`${W}/bin/clawdi`;if(!d5(z))throw Error(`npm install completed but clawdi bin is missing: ${z}`);let U=eW(z);if(!U)throw Error(`installed clawdi bin disappeared before verification: ${z}`);let H=JV(z),B=UG(J);if(B&&H!==B)throw Error(`npm install ${Q.installPackageSpec} reported version ${H}, expected ${B}`);XV(z);let V=$V(z,U);return{npmPrefix:W,activeTarget:z,version:H,verification:V}}function Ni$($,J,X){let Q=UG(J);if(Q)return{installPackageSpec:`clawdi@${Q}`,npmPrefix:I8$($,Q),version:Q};let W=do$("sha256").update(JSON.stringify({packageSpec:J,registry:X})).digest("hex").slice(0,16);return{installPackageSpec:J,npmPrefix:JX($.cliNpmPrefix,"packages",`tarball-${W}`),version:`tarball-${W}`}}function I8$($,J){if(!/^[0-9A-Za-z._+-]+$/.test(J))throw Error(`resolved clawdi CLI version contains unsafe path characters: ${J}`);return JX($.cliNpmPrefix,"packages",J)}function eB($){return XX(XX($))}function eW($){try{let J=to$($);return{device:J.dev,inode:J.ino,size:J.size,modifiedAtMs:J.mtimeMs}}catch{return null}}function bO($,J){return $.device===J.device&&$.inode===J.inode&&$.size===J.size&&$.modifiedAtMs===J.modifiedAtMs}function A8$($){let J=Date.parse($.verifiedAt),X=Date.now()-J;return Number.isFinite(J)&&X>=0&&X<Wi$}function $V($,J){let X=eW($);if(!X||!bO(J,X))throw Error(`clawdi CLI target changed during verification: ${$}`);return{verifiedAt:new Date().toISOString(),...X}}function V1($){try{return K8(XX($),Z8$($))}catch{return null}}function zG($,J){let X=JX($.cliNpmPrefix,"packages"),Q=new Set(J.filter((W)=>Boolean(W)));try{for(let W of ao$(X,{withFileTypes:!0})){if(!W.isDirectory())continue;let Y=JX(X,W.name);if(!Q.has(Y))tB(Y,{recursive:!0,force:!0})}}catch{}}function _O($,J){let X=[$,J].filter(Boolean).join(`
492
+ `,{mode:e4,dirMode:T4}),$.daemonAuthToken}function Go$($){return F6($,Zf)}function eJ$($,J){let X=Go$(J);if(X)return Yo$($,X);return Wo$($.daemonAuthToken,{force:!0}),null}function $8$($){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 Zf="secret://clawdi/auth-token";var Mf=j(()=>{C6();tJ();C0()});import{isAbsolute as zo$}from"node:path";function w8($,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&&zo$(W)?W:J.userHome}var _f=()=>{};function iB($){let J=If($),X=If(J?.authCert),Q=If(X?.PUBLIC_KEY),W=J?.capability,Y=X?.ISSUER,G=X?.SERIAL,z=Q?.data;if(!J||!Af(J,["authCert","capability","schemaVersion"])||J.schemaVersion!=="clawdi.managedWhatsAppSocket.v1"||typeof W!=="string"||!/^clawdi_[a-f0-9]{32}$/.test(W)||!X||!Af(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||!Af(Q,["data","type"])||Q.type!=="Buffer"||typeof z!=="string"||!Uo$(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 If($){return $&&typeof $==="object"&&!Array.isArray($)?$:null}function Af($,J){return Object.keys($).sort().join("\x00")===[...J].sort().join("\x00")}function Uo$($,J){let X=Buffer.from($,"base64");return X.length===J&&X.toString("base64")===$}var WG="x-clawdi-whatsapp-link-capability",oB="clawdi.managedWhatsAppSocket",bf="clawdi.managedWhatsAppSocket.v1";import{createHash as Ho$}from"node:crypto";function J8$($){if($.links.length===0)return[];let J=Bo$($.controlPlaneApiUrl),X=[...$.links].sort((Q,W)=>Q.linkId.localeCompare(W.linkId)).map((Q)=>({id:`native-whatsapp-baileys-${Vo$(Q.linkId)}`,enabled:!0,kind:"websocket",match:{scheme:"wss",host:"web.whatsapp.com",path:{type:"equals",value:"/ws/chat"},headers:{[WG]:{type:"secretRefEquals",secretRef:Q.capabilitySecretRef}},query:{}},rewrite:{upstreamBaseUrl:J,preservePath:!1,removeHeaders:[WG],setHeaders:{authorization:{type:"secretRef",secretRef:Q.agentTokenSecretRef,prefix:"Bearer "}}},logging:{redactHeaders:[WG,"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:{[WG]:{type:"exists"}},query:{}},logging:{redactHeaders:[WG],redactUrlPatterns:[]},priority:49,owner:"clawdi-native-whatsapp",description:"Fail closed when a managed WhatsApp capability is misplaced, stale, or invalid."}),X}function Bo$($){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 Vo$($){return Ho$("sha256").update($).digest("hex").slice(0,16)}var X8$=()=>{};import{createHash as wo$}from"node:crypto";import{join as G8$}from"node:path";function Pf($,J=O$({mode:"hosted"})){if(!$.channelBindings)return $;let X=$.secretValues??{},Q=$.channelBindings.map((G)=>Ko$(G,X)),W=Do$($.manifest,Q,J),Y=To$(Q.filter((G)=>G.account.provider==="whatsapp"),W.projection?.channelCredentials);return{...$,manifest:W,sourceManifest:$.sourceManifest??$.manifest,secretValues:{...X,...Y}}}function Ko$($,J){let X=F6(J,$.agentTokenSecretRef),Q=F6(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=So$($.accountKey,$.linkId),Y=Co$($.accountKey,$.linkId),G=Ef($.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"?No$($,J):void 0}}function No$($,J){let X=$.credential.credsSecretRef,Q=ko$($.accountKey,$.credential.id);if(X!==Q)throw Error("runtime bundle WhatsApp credential ref does not match its credential");let W=F6(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=V8$(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 Do$($,J,X){let Q=Ro$(J,$.controlPlane.apiUrl),W=w8($,X),Y=go$($),G=Fo$(J,W,Y),z={...$,projection:{...$.projection??{},channels:Oo$(J,W,Y),channelCredentials:G},egressProfiles:Po$($.egressProfiles,Q)};return Zo$(jo$(z,J),J)}function Oo$($,J,X){let Q={};for(let W of $){let Y=W.account.provider;if(Y==="telegram"){let G=Rf(Q,"telegram",W.accountKey);G.accounts[W.accountKey]={enabled:!0,botToken:Q8$(W),dmPolicy:"open",groupPolicy:"open",allowFrom:["*"],capabilities:{inlineButtons:"all"},groups:{"*":{requireMention:!1}}};continue}if(Y==="discord"){let G=Rf(Q,"discord",W.accountKey);G.accounts[W.accountKey]={enabled:!0,token:Q8$(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=Rf(Q,"whatsapp",W.accountKey),z=B8$(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 Fo$($,J,X){return $.map((Q)=>B8$(Q,J,X)).filter((Q)=>Q!==null).sort((Q,W)=>`${Q.provider}:${Q.accountKey}:${Q.credentialId}`.localeCompare(`${W.provider}:${W.accountKey}:${W.credentialId}`))}function jo$($,J){let X=$.runtimes.openclaw;if(!X?.enabled)return $;Mo$(J);let Q=X.run??{env:{},prependPath:[]},W=Io$(Q.secretEnv??{});for(let Y of J)W[H8$(Y)]=Y.placeholderSecretRef;if(!X.run&&Object.keys(W).length===0)return $;return{...$,runtimes:{...$.runtimes,openclaw:{...X,run:{...Q,secretEnv:W}}}}}function Zo$($,J){let X=$.runtimes.hermes;if(!X?.enabled)return $;let Q=rB(J,"telegram"),W=rB(J,"discord"),Y=rB(J,"whatsapp"),G=X.run??{env:{},prependPath:[]},z=Y8$(G.env??{},qo$),U=Y8$(G.secretEnv??{},Lo$);if(Q)z.TELEGRAM_ALLOW_ALL_USERS="true",z.HERMES_TELEGRAM_DISABLE_FALLBACK_IPS="true",U.TELEGRAM_BOT_TOKEN=Q.placeholderSecretRef;if(W)z.DISCORD_ALLOW_ALL_USERS="true",U.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:U}}}}}function rB($,J){let X=$.filter((Q)=>Q.account.provider===J);if(X.length>1)throw Error(_o$(J));return X[0]??null}function Mo$($){for(let J of["telegram","discord","whatsapp"])rB($,J)}function _o$($){return`This Agent has multiple active ${$==="telegram"?"Telegram":$==="discord"?"Discord":$} bots. Unlink the extras until only one remains.`}function Q8$($){return{source:"env",provider:"default",id:H8$($)}}function H8$($){return`${z8$}${W8$($.account.provider)}_${W8$($.accountKey)}${U8$}`}function W8$($){return $.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"CHANNEL"}function Io$($){return Object.fromEntries(Object.entries($).filter(([J])=>!Ao$(J)))}function Ao$($){return $.startsWith(z8$)&&$.endsWith(U8$)}function Y8$($,J){let X=new Set(J),Q={};for(let[W,Y]of Object.entries($))if(!X.has(W))Q[W]=Y;return Q}function Rf($,J,X){let Q=$[J];if(bo$(Q))return Q;let W={enabled:!0,defaultAccount:X,accounts:{}};return $[J]=W,W}function bo$($){return typeof $==="object"&&$!==null&&!Array.isArray($)&&typeof $.accounts==="object"&&$.accounts!==null&&!Array.isArray($.accounts)}function Ro$($,J){let X=yo$(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:`${ho$(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=rB($,"whatsapp");if(W&&!Tf(W))throw Error(`managed WhatsApp Link ${W.linkId} has no valid synthetic auth`);return Q.push(...J8$({controlPlaneApiUrl:J,links:W?[{linkId:W.linkId,agentTokenSecretRef:W.secretRef,capabilitySecretRef:W.placeholderSecretRef}]:[]})),Q}function Po$($,J){let X=[...$?.profiles??[]],Q=new Set(J.map((W)=>W.id));return{profiles:[...X.filter((W)=>!Q.has(W.id)&&!Eo$(W)),...J]}}function Eo$($){return $.owner==="clawdi-native-channels"||$.owner==="clawdi-native-whatsapp"||$.id==="direct-provider-passthrough"||$.id.startsWith("direct-provider-passthrough-")}function To$($,J){let X={},Q=new Set(S5(J).map((W)=>W.credsJsonSecretRef));for(let W of $){let Y=Tf(W);if(Y){let G=Y.credential.credsSecretRef;if(Q.has(G))X[G]=JSON.stringify(xo$(W,Y))}}return X}function So$($,J){return`secret://channels/whatsapp/${$}/links/${J}/agent-token`}function Co$($,J){return`secret://channels/whatsapp/${$}/links/${J}/egress-capability`}function ko$($,J){return`secret://channels/whatsapp/${$}/credentials/${J}/creds-json`}function Ef($,J){return`clawdi_${wo$("sha256").update(`whatsapp:${$}:${J}`).digest("hex").slice(0,32)}`}function B8$($,J,X){let Q=Tf($);if(!Q)return null;let W=fo$(J,$.accountKey),Y=vo$(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 Tf($){if($.account.provider!=="whatsapp")return null;let J=$.credential;if(!J)return null;let{material:X}=J,Q;try{Q=iB({schemaVersion:bf,capability:Ef($.accountKey,$.linkId),authCert:X.authCert})}catch{return null}return{credential:J,creds:X.creds,authCert:Q.authCert}}function xo$($,J){let X=J.creds.additionalData,Q=X===void 0?{}:V8$(X);if(!Q)throw Error("managed WhatsApp synthetic creds.additionalData must be an object");let W=iB({schemaVersion:bf,capability:Ef($.accountKey,$.linkId),authCert:J.authCert});return{...J.creds,additionalData:{...Q,[oB]:W}}}function fo$($,J){return G8$($,".openclaw","credentials","whatsapp",J)}function vo$($){return G8$($,".hermes","platforms","whatsapp","session")}function go$($){return{openclaw:$.runtimes.openclaw?.enabled===!0,hermes:$.runtimes.hermes?.enabled===!0}}function V8$($){if(!$||typeof $!=="object"||Array.isArray($))return null;return $}function yo$($){return $.replace(/\/+$/,"")}function ho$($){if($.startsWith("https://"))return`wss://${$.slice(8)}`;if($.startsWith("http://"))return`ws://${$.slice(7)}`;return $}var qo$,Lo$,z8$="CLAWDI_CHANNEL_",U8$="_AGENT_TOKEN";var w8$=j(()=>{k6();_f();tJ();X8$();qo$=["TELEGRAM_ALLOW_ALL_USERS","DISCORD_ALLOW_ALL_USERS","HERMES_TELEGRAM_DISABLE_FALLBACK_IPS","WHATSAPP_ENABLED","WHATSAPP_MODE","WHATSAPP_ALLOWED_USERS","WHATSAPP_ALLOW_ALL_USERS"],Lo$=["TELEGRAM_BOT_TOKEN","DISCORD_BOT_TOKEN"]});import{dirname as q8$,isAbsolute as L8$,relative as uo$,resolve as Sf}from"node:path";function lo$(){return process.env.CLAWDI_RUNTIME_MODE?.trim().toLowerCase()||"missing"}function xf($,J={}){let X=J.expectedIdentity??K8$,Q=lo$(),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,U=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 H=(J.resolveUserIdentity??pe)(G);if(U=`${G} (${H.uid}:${H.gid})`,H.uid===0||H.gid===0)z=`hosted runtime user ${G} resolved to root identity ${H.uid}:${H.gid}`;else if(H.uid!==X.uid||H.gid!==X.gid)z=`hosted runtime user ${G} must resolve to ${X.uid}:${X.gid}; resolved ${H.uid}:${H.gid}`;else for(let[B,V,w]of[["CLAWDI_RUNTIME_UID",process.env.CLAWDI_RUNTIME_UID?.trim(),H.uid],["CLAWDI_RUNTIME_GID",process.env.CLAWDI_RUNTIME_GID?.trim(),H.gid]])if(V&&V!==String(w)){z=`${B} must match the resolved hosted runtime identity ${w}; resolved ${V}`;break}}catch(H){z=H instanceof Error?H.message:String(H)}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:U,...z?{error:z}:{}}}}function aB($,J,X={}){let Q=xf($,X),W=[Q.mode,Q.home,Q.user].find((U)=>!U.ok)?.error;if(W)throw Error(W);let Y=Sf($.clawdiHome),G=Sf($.serviceStateRoot),z=uo$(Sf($.userHome),Y);if(z===""||!z.startsWith("..")&&!L8$(z))throw Error(`hosted CLAWDI_HOME must be outside the tenant home; resolved ${$.clawdiHome}`);if(!L8$($.clawdiHome)||Y===G||q8$(Y)!==q8$(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")$3($);return{identity:X.expectedIdentity??K8$,assertPlatformRoots:()=>$3($)}}var Cf="/home/clawdi",kf="clawdi",mo$=10001,co$=10001,K8$;var ZO=j(()=>{_0();C0();K8$={home:Cf,user:kf,uid:mo$,gid:co$}});import{spawnSync as vf}from"node:child_process";import{createHash as do$}from"node:crypto";import{accessSync as po$,constants as no$,existsSync as F8$,lstatSync as oo$,mkdirSync as io$,mkdtempSync as ro$,readdirSync as ao$,readFileSync as j8$,readlinkSync as Z8$,renameSync as so$,rmSync as tB,statSync as to$,symlinkSync as eo$}from"node:fs";import{tmpdir as $i$}from"node:os";import{dirname as XX,join as JX,resolve as K8}from"node:path";function M8$($){if($.mode!=="hosted"||$.userHome!==Cf||process.env.CLAWDI_RUNTIME_USER?.trim()!==kf||typeof process.geteuid==="function"&&process.geteuid()!==0)return;let J;try{J=oo$(sB)}catch(Q){if(Q.code==="ENOENT")return;throw Q}if(!J.isSymbolicLink())throw Error(`hosted tenant PATH contains an unmanaged clawdi entrypoint: ${sB}`);let X=K8(XX(sB),Z8$(sB));if(X!==Yi$)throw Error(`hosted tenant PATH contains an unmanaged clawdi symlink target: ${X}`);tB(sB)}function _8$($,J,X={}){let Q=PO(J,X);if(Q.selfReexec){let B=GG(J.cliBootstrapStatus);return YG("deferred",J,{packageSpec:$.clawdiCli?.packageSpec?.trim()||null,registry:B?.registry??null,npmPrefix:B?.npmPrefix??J.cliNpmPrefix,activeTarget:B?.activeTarget??null,version:B?.version??null,error:`CLI transaction recovery ${Q.status}; re-exec is required`},!0)}let W=$.clawdiCli?.packageSpec?.trim();if(!W)return YG("not_requested",J,{packageSpec:null,registry:null,activeTarget:null,version:null});Bi$(W);let Y=Hi$($),G=GG(J.cliBootstrapStatus);if(Vi$(G,J,W,Y))return YG("current",J,{packageSpec:W,registry:Y,npmPrefix:G.npmPrefix??eB(G.activeTarget),activeTarget:G.activeTarget??null,version:G.version??null});let z=Li$(J,W);if(z)return l5(J,{packageSpec:W,registry:Y,npmPrefix:z.npmPrefix,activeTarget:z.activeTarget,version:z.version},z.verification),YG("current",J,{packageSpec:W,registry:Y,npmPrefix:z.npmPrefix,activeTarget:z.activeTarget,version:z.version});if(X.deferInstall)return YG("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 U=qi$(J,G);if(U&&V1(J.cliManagedBin)===U.activeTarget&&(G?.status!=="installed"||G.source!=="npm"||G.packageSpec!==U.packageSpec||(G.registry??null)!==U.registry||G.npmPrefix!==U.npmPrefix||G.activePath!==J.cliManagedBin||G.activeTarget!==U.activeTarget||G.version!==U.version)){let B=L8(J,U);if(!B)throw Error("active clawdi CLI changed during verification");l5(J,U,B)}let H=Ki$(J,W,Y);return Di$(J,{newIdentity:{packageSpec:W,registry:Y,npmPrefix:H.npmPrefix,activeTarget:H.activeTarget,version:H.version},previousIdentity:U,rollbackEligible:X.rollbackEligible===!0&&U!==null}),b8$(J.cliManagedBin,H.activeTarget),l5(J,{packageSpec:W,registry:Y,npmPrefix:H.npmPrefix,activeTarget:H.activeTarget,version:H.version},H.verification),P8$(J),zG(J,[H.npmPrefix,U?.npmPrefix??null]),YG("installed",J,{packageSpec:W,registry:Y,npmPrefix:H.npmPrefix,activeTarget:H.activeTarget,version:H.version},!0)}function YG($,J,X,Q=!1){return{status:$,...X,npmPrefix:X.npmPrefix??J.cliNpmPrefix,npmCache:X.npmCache??J.cliNpmCache,activePath:J.cliManagedBin,selfReexec:Q}}function Hi$($){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 Bi$($){if(MH.safeParse($).success)return;throw Error(`clawdi CLI packageSpec must be clawdi@<exact-semver> or a managed bootstrap tarball: ${$}`)}function GG($){if(!F8$($))return null;try{let J=JSON.parse(j8$($,"utf-8"));if(typeof J!=="object"||J===null||Array.isArray(J))return null;return J}catch{return null}}function tW($){io$($,{recursive:!0})}function gf($,J){let X=K8($.cliNpmPrefix),Q=K8(J);return Q===X||Q.startsWith(`${X}/`)}function AO($,J){return gf($,J)&&J.endsWith("/bin/clawdi")}function Vi$($,J,X,Q){if(!$)return!1;if($.status!=="installed"||$.source!=="npm")return!1;if($.activePath!==J.cliManagedBin)return!1;if(!$.activeTarget)return!1;if(!AO(J,$.activeTarget))return!1;if(V1(J.cliManagedBin)!==$.activeTarget)return!1;if(!$.npmPrefix||K8($.npmPrefix)!==K8(eB($.activeTarget)))return!1;if(!d5($.activeTarget))return!1;if(!$.version)return!1;let W=UG(X);if(W&&$.version!==W)return!1;let Y=process.env.CLAWDI_RUNTIME_ALLOW_TEST_INSTALLERS==="1"&&$.packageSpec===LW&&W===$.version;if($.packageSpec!==X&&!Y)return!1;if(($.registry??null)!==Q)return!1;if(!d5(J.cliManagedBin))return!1;let G=eW($.activeTarget);if(G&&$.verification&&bO($.verification,G)&&A8$($.verification))return!0;if(!G)return!1;try{if(JV($.activeTarget)!==$.version)return!1;XV($.activeTarget);let z=$V($.activeTarget,G);return l5(J,{packageSpec:Y?LW:X,registry:Q,npmPrefix:$.npmPrefix,activeTarget:$.activeTarget,version:$.version},z),!0}catch{return!1}}function wi$($,J){let X=V1($.cliManagedBin);if(!X||!AO($,X))return null;let Q=eB(X);if(!gf($,Q))return null;if(!d5(X)||!d5($.cliManagedBin))return null;try{let W=eW(X);if(!W)return null;let Y=JV(X);XV(X),$V(X,W);let G=`clawdi@${Y}`;if(!BY.safeParse(G).success)return null;let z=J?.packageSpec,U=J?.registry??null,H=z?UG(z):null,B=J?.status==="installed"&&J.source==="npm"&&J.activePath===$.cliManagedBin&&J.activeTarget===X&&J.npmPrefix!==void 0&&K8(J.npmPrefix)===K8(Q)&&J.version===Y&&z!==void 0&&MH.safeParse(z).success&&(H===null||H===Y)&&(U===null||U==="https://registry.npmjs.org");return{packageSpec:B&&z?z:G,registry:B?U:null,npmPrefix:Q,activeTarget:X,version:Y}}catch{return null}}function qi$($,J){let X=wi$($,J);if(!X)return null;let Q=GJ($).transaction;if(Q?.phase!=="activated"||Q.rollback||!Q.rollbackEligible||!Q.previousIdentity||Q.newIdentity.activeTarget!==X.activeTarget)return X;return L8($,Q.previousIdentity)?Q.previousIdentity:X}function Li$($,J){let X=UG(J);if(!X)return null;let Q=I8$($,X),W=V1($.cliManagedBin);if(W!==JX(Q,"bin","clawdi"))return null;if(!AO($,W))return null;if(!d5(W)||!d5($.cliManagedBin))return null;let Y=eW(W);if(!Y)return null;let G=JV(W);if(G!==X)return null;XV(W);let z=$V(W,Y);return{npmPrefix:eB(W),activeTarget:W,version:G,verification:z}}function UG($){if(!BY.safeParse($).success)return null;return $.slice(7)}function Ki$($,J,X){let Q=Ni$($,J,X);if(ji$($,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;tW(XX(XX($.cliManagedBin))),tW(XX($.cliManagedBin)),tW($.cliNpmPrefix),tW(W),tW($.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=vf("npm",Y,{encoding:"utf8",timeout:Ji$,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}`:""}${_O(G.stdout,G.stderr)}`);let z=`${W}/bin/clawdi`;if(!d5(z))throw Error(`npm install completed but clawdi bin is missing: ${z}`);let U=eW(z);if(!U)throw Error(`installed clawdi bin disappeared before verification: ${z}`);let H=JV(z),B=UG(J);if(B&&H!==B)throw Error(`npm install ${Q.installPackageSpec} reported version ${H}, expected ${B}`);XV(z);let V=$V(z,U);return{npmPrefix:W,activeTarget:z,version:H,verification:V}}function Ni$($,J,X){let Q=UG(J);if(Q)return{installPackageSpec:`clawdi@${Q}`,npmPrefix:I8$($,Q),version:Q};let W=do$("sha256").update(JSON.stringify({packageSpec:J,registry:X})).digest("hex").slice(0,16);return{installPackageSpec:J,npmPrefix:JX($.cliNpmPrefix,"packages",`tarball-${W}`),version:`tarball-${W}`}}function I8$($,J){if(!/^[0-9A-Za-z._+-]+$/.test(J))throw Error(`resolved clawdi CLI version contains unsafe path characters: ${J}`);return JX($.cliNpmPrefix,"packages",J)}function eB($){return XX(XX($))}function eW($){try{let J=to$($);return{device:J.dev,inode:J.ino,size:J.size,modifiedAtMs:J.mtimeMs}}catch{return null}}function bO($,J){return $.device===J.device&&$.inode===J.inode&&$.size===J.size&&$.modifiedAtMs===J.modifiedAtMs}function A8$($){let J=Date.parse($.verifiedAt),X=Date.now()-J;return Number.isFinite(J)&&X>=0&&X<Wi$}function $V($,J){let X=eW($);if(!X||!bO(J,X))throw Error(`clawdi CLI target changed during verification: ${$}`);return{verifiedAt:new Date().toISOString(),...X}}function V1($){try{return K8(XX($),Z8$($))}catch{return null}}function zG($,J){let X=JX($.cliNpmPrefix,"packages"),Q=new Set(J.filter((W)=>Boolean(W)));try{for(let W of ao$(X,{withFileTypes:!0})){if(!W.isDirectory())continue;let Y=JX(X,W.name);if(!Q.has(Y))tB(Y,{recursive:!0,force:!0})}}catch{}}function _O($,J){let X=[$,J].filter(Boolean).join(`
493
493
  `).trim();return X?`: ${X.slice(0,1000)}`:""}function JV($){let J=vf($,["--version"],{encoding:"utf8",timeout:Xi$,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}`:""}${_O(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 XV($){let J=ro$(JX($i$(),"clawdi-runtime-verify-")),X;try{X=vf($,["runtime","verify","--json"],{encoding:"utf8",timeout:Qi$,env:{...process.env,HOME:JX(J,"home"),CLAWDI_SERVICE_STATE_DIR:JX(J,"state"),CLAWDI_RUN_DIR:JX(J,"run"),CLAWDI_NO_AUTO_UPDATE:"1",CLAWDI_NO_UPDATE_CHECK:"1"}})}finally{tB(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}`:""}${_O(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)}${_O(X.stdout,X.stderr)}`)}}function b8$($,J){let X=XX($);tW(XX(X)),tW(X);let Q=`${X}/.clawdi.next.${process.pid}.${Date.now()}`;try{tB(Q,{force:!0}),eo$(J,Q),so$(Q,$)}catch(W){throw tB(Q,{force:!0}),W}}function l5($,J,X){let Q=eW(J.activeTarget);if(X&&(!Q||!bO(X,Q)))throw Error(`clawdi CLI target changed after verification: ${J.activeTarget}`);C4($,$.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)}
494
494
  `,{mode:384,dirMode:493})}function R8$($,J){let X=null;try{X=GJ($).transaction??null,PO($)}catch(W){return O8$(X,W)}let Q=GJ($);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(!L8($,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(V1($.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 QX($,{...Q,transaction:W}),IO($,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 O8$(X,W)}}function RO($,J){let X=PO($,{runningVersion:J});if(X.selfReexec)return X;let Q=GJ($),W=Q.transaction??null;if(W?.phase!=="activated"||W.rollback)return X;if(W.newIdentity.version!==J)return X;if(V1($.cliManagedBin)!==W.newIdentity.activeTarget)return X;if(!L8($,W.newIdentity))return X;let Y=hf(Q);return Y.transaction=null,QX($,Y),zG($,[W.newIdentity.npmPrefix]),X}function yf($,J){return PO($,{runningVersion:J})}function Di$($,J){let X=hf(GJ($));X.transaction={phase:"prepared",previousIdentity:J.previousIdentity,newIdentity:J.newIdentity,rollbackEligible:J.rollbackEligible,installedAt:new Date().toISOString(),rollback:null},QX($,X)}function P8$($){let J=GJ($),X=J.transaction;if(X?.phase!=="prepared")throw Error("prepared clawdi CLI upgrade transaction is missing");if(V1($.cliManagedBin)!==X.newIdentity.activeTarget)throw Error("prepared clawdi CLI target is not active");QX($,{...J,transaction:{...X,phase:"activated"}})}function PO($,J={}){let X=GJ($),Q=X.transaction??null;if(!Q)return{status:"unchanged",selfReexec:!1};if(Q.rollback)return IO($,Q),q8($,"rolled_back",J.runningVersion);let W=V1($.cliManagedBin),Y=Q.previousIdentity?.activeTarget??null;if(Q.phase==="prepared"){if(W===Q.newIdentity.activeTarget){let G=L8($,Q.newIdentity);if(!G)return MO($,Q),q8($,"rolled_back",J.runningVersion);return l5($,Q.newIdentity,G),P8$($),zG($,[Q.newIdentity.npmPrefix,Q.previousIdentity?.npmPrefix??null]),q8($,"activated",J.runningVersion)}if(W===Y){if(Q.previousIdentity){let G=L8($,Q.previousIdentity);if(!G)throw Error("prepared clawdi CLI transaction has an invalid previous identity");l5($,Q.previousIdentity,G)}return QX($,{...X,transaction:null}),zG($,[Q.previousIdentity?.npmPrefix??null]),q8($,"unchanged",J.runningVersion)}return MO($,Q),q8($,"rolled_back",J.runningVersion)}if(W===Q.newIdentity.activeTarget){if(!L8($,Q.newIdentity))return MO($,Q),q8($,"rolled_back",J.runningVersion);return q8($,"unchanged",J.runningVersion)}if(Q.previousIdentity&&W===Y){let G=E8$(Q);return QX($,{...X,transaction:G}),IO($,G),q8($,"rolled_back",J.runningVersion)}if(Oi$($,Q))return q8($,"activated",J.runningVersion);return MO($,Q),q8($,"rolled_back",J.runningVersion)}function Oi$($,J){let X=D8$($);if(!X)return!1;let Q=GJ($);if(!Fi$(Q.transaction??null,J))throw Error("clawdi CLI transaction changed during bootstrap ownership handoff");let W=D8$($);if(!W||!ff(W,X))throw Error("clawdi CLI bootstrap identity changed during ownership handoff");if(QX($,{...Q,transaction:{phase:"activated",previousIdentity:null,newIdentity:X,rollbackEligible:!1,installedAt:new Date().toISOString(),rollback:null}}),V1($.cliManagedBin)!==X.activeTarget)throw Error("clawdi CLI bootstrap identity changed after ownership handoff");return zG($,[X.npmPrefix]),!0}function Fi$($,J){if($===null||J===null)return $===J;return $.phase===J.phase&&ff($.previousIdentity,J.previousIdentity)&&ff($.newIdentity,J.newIdentity)&&$.rollbackEligible===J.rollbackEligible&&$.installedAt===J.installedAt&&$.rollback?.reason===J.rollback?.reason&&$.rollback?.markedAt===J.rollback?.markedAt}function ff($,J){if($===null||J===null)return $===J;return $.packageSpec===J.packageSpec&&$.registry===J.registry&&$.npmPrefix===J.npmPrefix&&$.activeTarget===J.activeTarget&&$.version===J.version}function D8$($){let J=GG($.cliBootstrapStatus),X=V1($.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(!L8($,Q))return null;let W=GG($.cliBootstrapStatus);return V1($.cliManagedBin)===Q.activeTarget&&T8$(W,$,Q)&&W?.schemaVersion==="clawdi.cliNpmBootstrapStatus.v1"&&W.error===null&&W.npmCache===$.cliNpmCache?Q:null}function q8($,J,X){let Q=GG($.cliBootstrapStatus),W=V1($.cliManagedBin),Y=Q?.activeTarget===W?Q.version:void 0;return{status:J,selfReexec:X!==void 0&&Y!==void 0&&Y!==X}}function MO($,J){if(!J.previousIdentity||!L8($,J.previousIdentity))throw Error("clawdi CLI transaction cannot restore a verified previous identity");let X=E8$(J),Q=GJ($);QX($,{...Q,transaction:X}),IO($,X)}function E8$($){return{...$,rollback:{reason:"recovered interrupted or inconsistent clawdi CLI transaction",markedAt:new Date().toISOString()}}}function IO($,J){let X=J.previousIdentity;if(!J.rollback||!X)throw Error("clawdi CLI rollback transaction is incomplete");let Q=L8($,X);if(!Q)throw Error("previous clawdi CLI identity failed rollback verification");if(V1($.cliManagedBin)!==X.activeTarget)b8$($.cliManagedBin,X.activeTarget);l5($,X,Q);let Y=GJ($);QX($,{...Y,transaction:null,badVersions:Mi$(Y.badVersions??[],{packageSpec:J.newIdentity.packageSpec,registry:J.newIdentity.registry,version:J.newIdentity.version,reason:J.rollback.reason,markedAt:J.rollback.markedAt})}),zG($,[X.npmPrefix])}function L8($,J){if(!MH.safeParse(J.packageSpec).success||J.registry!==null&&J.registry!=="https://registry.npmjs.org"||!AO($,J.activeTarget)||!gf($,J.npmPrefix)||K8(eB(J.activeTarget))!==K8(J.npmPrefix)||!d5(J.activeTarget))return null;let X=UG(J.packageSpec);if(X&&X!==J.version)return null;let Q=GG($.cliBootstrapStatus),W=eW(J.activeTarget);if(T8$(Q,$,J)&&W&&Q?.verification&&bO(Q.verification,W)&&A8$(Q.verification))return Q.verification;if(!W)return null;try{if(JV(J.activeTarget)!==J.version)return null;XV(J.activeTarget);let Y=$V(J.activeTarget,W);if(V1($.cliManagedBin)===J.activeTarget)l5($,J,Y);return Y}catch{return null}}function T8$($,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 O8$($,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 ji$($,J,X,Q){return(GJ($).badVersions??[]).some((Y)=>Y.packageSpec===J&&(Y.registry??null)===X&&Y.version===Q)}function GJ($){if(!F8$($.cliUpgradeState))return Zi$();let J;try{J=JSON.parse(j8$($.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=Ui$.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 QX($,J){C4($,$.cliUpgradeState,`${JSON.stringify(hf(J),null,2)}
495
495
  `,{mode:384,dirMode:493})}function hf($){return{schemaVersion:"clawdi.cliUpgradeState.v2",transaction:$.transaction??null,badVersions:$.badVersions??[]}}function Zi$(){return{schemaVersion:"clawdi.cliUpgradeState.v2",transaction:null,badVersions:[]}}function Mi$($,J){let X=$.filter((Q)=>Q.packageSpec!==J.packageSpec||(Q.registry??null)!==J.registry||Q.version!==J.version);return X.push(J),X}function d5($){try{return po$($,no$.X_OK),!0}catch{return!1}}var Ji$=180000,Xi$=20000,Qi$=20000,Wi$=300000,sB="/usr/local/bin/clawdi",Yi$="/usr/local/lib/node_modules/clawdi/bin/clawdi.mjs",N8$,Gi$,zi$,Ui$;var uf=j(()=>{w6();ZO();O5();C0();N8$=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(),Gi$=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(),zi$=L.object({phase:L.enum(["prepared","activated"]),previousIdentity:N8$.nullable(),newIdentity:N8$,rollbackEligible:L.boolean(),installedAt:L.string().min(1),rollback:L.object({reason:L.string(),markedAt:L.string().min(1)}).strict().nullable()}).strict(),Ui$=L.object({schemaVersion:L.literal("clawdi.cliUpgradeState.v2"),transaction:zi$.nullable(),badVersions:L.array(Gi$)}).strict()});import{createHash as _i$}from"node:crypto";import{existsSync as S8$,lstatSync as C8$,mkdtempSync as Ii$,readdirSync as k8$,readFileSync as mf,rmSync as Ai$}from"node:fs";import{tmpdir as bi$}from"node:os";import{join as HG}from"node:path";function EO($){return _i$("sha256").update($).digest("hex")}function QV($,J){return J.type==="github"?["github",$,J.url,J.path,J.commit].join("\x00"):["project",$,J.projectId,J.contentHash].join("\x00")}function f8$($,J,X){let Q=EO(QV(J,X)),W=HG($.hostedSkillArchiveRoot,Q);return{archive:HG(W,"skill.tar.gz"),receipt:HG(W,"receipt.json")}}function Ei$($,J,X){let Q=f8$($,J,X);if(!S8$(Q.archive)||!S8$(Q.receipt))return null;try{let W=C8$(Q.archive),Y=C8$(Q.receipt);if(!W.isFile()||W.isSymbolicLink()||W.size>Ri$||!Y.isFile()||Y.isSymbolicLink())return null;let G=JSON.parse(mf(Q.receipt,"utf8"));if(!Ti$(G))return null;if(G.skillId!==J||QV(G.skillId,G.source)!==QV(J,X))return null;let z=mf(Q.archive);if(EO(z)!==G.sha256)return null;return{archiveSha256:G.sha256,tarBytes:z}}catch{return null}}function Ti$($){if(typeof $!=="object"||$===null||Array.isArray($))return!1;let J=$;if(J.schemaVersion!==x8$||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 Si$($,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 Ci$($,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 d8(W,Pi$,{resourceLabel:"Project Skill archive",limitLabel:"25 MB"}),G=Ii$(HG(bi$(),"clawdi-project-skill-"));try{await C8(G,Y);let z=k8$(G);if(z.length!==1||z[0]!==$)throw Error(`Project Skill ${$} archive has an unexpected root layout`);let U=HG(G,$),H=await F0(U,G,$),B=k8$(U),V=B.length===1&&B[0]==="SKILL.md"&&EO(mf(HG(U,"SKILL.md")))===J.contentHash;if(H.hash!==J.contentHash&&!V)throw Error(`Project Skill ${$} archive does not match its content identity`);return H.archive}finally{Ai$(G,{recursive:!0,force:!0})}}function ki$($,J,X,Q){let W=EO(Q),Y=f8$($,J,X);return C4($,Y.archive,Q,{mode:384,dirMode:448}),C4($,Y.receipt,`${JSON.stringify({schemaVersion:x8$,skillId:J,source:X,sha256:W},null,2)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clawdi",
3
- "version": "0.13.82",
3
+ "version": "0.13.83",
4
4
  "description": "iCloud for AI Agents — cross-agent sessions, skills, memory, and vault.",
5
5
  "license": "MIT",
6
6
  "type": "module",