clawdi 0.14.25 → 0.14.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -261,7 +261,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
261
261
|
`)}var _i=_(()=>{qb();Xg();U$();C5()});var O5;var T5=_(()=>{sn();O5=y.object({type:y.literal("mitmproxy"),version:y.string().min(1),url:y.string().url(),sha256:y.string().regex(/^[a-fA-F0-9]{64}$/)})});function Yo(e){let t={};for(let[n,r]of Object.entries(e??{})){if(Ep(n)===null)throw Error(`runtime secret value key must be a canonical secret:// reference: ${n}`);if(!r)throw Error(`runtime secret value must be non-empty: ${n}`);t[n]=r}return t}function Ep(e){if(!e||!j5.test(e))return null;return e.slice(R0e.length)}function It(e,t){if(Ep(t)===null)return null;let n=e[t];return typeof n==="string"&&n.length>0?n:null}var R0e="secret://",j5,lr;var Yr=_(()=>{sn();j5=/^secret:\/\/\S+$/,lr=y.string().regex(j5,"must be a canonical non-empty secret:// reference")});function A0e(e){if(!e||e.length>253)return!1;for(let t of e){let n=t.charCodeAt(0);if(t==="@"||t==="?"||t==="#"||t==="/"||t==="\\"||t===" "||t==="%"||n<32||n===127)return!1}return!e.startsWith(".")&&!e.endsWith(".")}function x0e(e){try{let t=new URL(e);return["http:","https:","ws:","wss:"].includes(t.protocol)&&t.username===""&&t.password===""&&A0e(t.hostname.toLowerCase())}catch{return!1}}function Yk(e){let t=new Set;for(let n of e?.profiles??[]){if(!n.enabled)continue;for(let i of[n.match.path,...Object.values(n.match.headers??{}),...Object.values(n.match.query??{})])if(i&&"secretRef"in i)t.add(i.secretRef);let r=n.rewrite?.pathReplace;if(r)t.add(r.secretRef),t.add(r.replacementSecretRef);for(let i of Object.values(n.rewrite?.setHeaders??{}))if(typeof i!=="string")t.add(i.secretRef)}return[...t].sort()}function L5(e){return{schemaVersion:"clawdi.egressProfiles.v1",generatedAt:e.generatedAt,generation:e.generation,instanceId:e.instanceId,profiles:e.profiles?.profiles??[]}}function KM(e){return e.profiles.some((t)=>t.enabled)}var Ds,P0e,Jk,E0e,D5,$0e,C0e,I0e,O0e,T0e,j0e,N5,M5,Xgt;var Ap=_(()=>{sn();Yr();Ds=lr,P0e=y.string().min(1).regex(/^[a-z0-9][a-z0-9-_.]*$/),Jk=y.string().min(1).regex(/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/),E0e=y.string().min(1);D5=y.discriminatedUnion("type",[y.object({type:y.literal("exists")}),y.object({type:y.literal("equals"),value:y.string(),prefix:y.string().optional()}),y.object({type:y.literal("secretRefEquals"),secretRef:Ds,prefix:y.string().optional()}),y.object({type:y.literal("secretRefPrefix"),secretRef:Ds,prefix:y.string().default(""),suffix:y.string().default("")})]).describe("Header matchers must never inline secret values unless type=equals is intentionally public."),$0e=y.discriminatedUnion("type",[y.object({type:y.literal("equals"),value:y.string().min(1)}),y.object({type:y.literal("prefix"),value:y.string().min(1)}),y.object({type:y.literal("secretRefEquals"),secretRef:Ds,prefix:y.string().default(""),suffix:y.string().default("")}),y.object({type:y.literal("secretRefPrefix"),secretRef:Ds,prefix:y.string().default(""),suffix:y.string().default("")})]).describe("Path matchers allow URL-embedded tokens such as Telegram Bot API tokens."),C0e=y.union([y.string(),y.object({type:y.literal("secretRef"),secretRef:Ds,prefix:y.string().default("")})]).describe("Rewrite headers can be literal public values or secretRef-backed values resolved only by the sidecar."),I0e=y.object({type:y.literal("secretRefPrefix"),secretRef:Ds,replacementSecretRef:Ds,prefix:y.string().default(""),suffix:y.string().default("")}),O0e=y.object({scheme:y.enum(["http","https","ws","wss"]).optional(),host:y.string().min(1),notAfter:y.string().datetime({offset:!0}).optional(),pathPrefix:y.string().min(1).refine((e)=>e.startsWith("/"),"pathPrefix must start with /").optional(),path:$0e.optional(),headers:y.record(Jk,D5).default({}),query:y.record(E0e,D5).default({})}),T0e=y.object({upstreamBaseUrl:y.string().url().refine((e)=>["http:","https:","ws:","wss:"].includes(new URL(e).protocol),"upstreamBaseUrl must use http, https, ws, or wss").refine(x0e,"upstreamBaseUrl must not include credentials or an unsafe host").optional(),preservePath:y.boolean().default(!0),pathReplace:I0e.optional(),removeHeaders:y.array(Jk).optional(),setHeaders:y.record(Jk,C0e).default({})}),j0e=y.object({redactHeaders:y.array(Jk).default([]),redactUrlPatterns:y.array(y.string().min(1)).default([])}),N5=y.object({id:P0e,enabled:y.boolean().default(!0),kind:y.enum(["http","websocket","provider","passthrough","deny"]),match:O0e,rewrite:T0e.optional(),logging:j0e.default({redactHeaders:[],redactUrlPatterns:[]}),priority:y.number().int().default(100),owner:y.string().min(1).optional(),description:y.string().min(1).optional()}).superRefine((e,t)=>{if((e.kind==="http"||e.kind==="websocket")&&!e.rewrite?.upstreamBaseUrl)t.addIssue({code:"custom",path:["rewrite","upstreamBaseUrl"],message:`${e.kind} profiles require rewrite.upstreamBaseUrl`});if(e.kind==="deny"&&e.rewrite)t.addIssue({code:"custom",path:["rewrite"],message:"deny profiles must not include rewrite rules"});if(e.kind==="passthrough"&&e.rewrite)t.addIssue({code:"custom",path:["rewrite"],message:"passthrough profiles must not include rewrite rules"})}),M5=y.object({profiles:y.array(N5).default([])}),Xgt=y.object({schemaVersion:y.literal("clawdi.egressProfiles.v1"),generatedAt:y.string().min(1),generation:y.number().int().nonnegative(),instanceId:y.string().min(1),profiles:y.array(N5)})});import{createHash as D0e}from"node:crypto";function U5(e){let t=e.egressProfiles??{profiles:[]};return V0e(t,[...L0e(e),...N0e(e)])}function N0e(e){if(!e.mcp)return[];let t=[];for(let[n,r]of Object.entries(e.mcp.servers)){if(!("url"in r))continue;let i=Object.entries(r.headers).filter((a)=>typeof a[1]!=="string");if(i.length===0)continue;let o=new URL(r.url),s=o.port||(o.protocol==="https:"?"443":"80");t.push({id:`managed-mcp-${z5(n)}`,enabled:!0,kind:"provider",match:{scheme:o.protocol.slice(0,-1),host:`${o.hostname.toLowerCase()}:${s}`,path:{type:"equals",value:o.pathname||"/"},headers:Object.fromEntries(i.map(([a,l])=>[a,{type:"equals",value:Xk(n,a),prefix:l.prefix}])),query:{}},rewrite:{preservePath:!0,setHeaders:Object.fromEntries(i.map(([a,l])=>[a,{type:"secretRef",secretRef:l.secretRef,prefix:l.prefix}]))},logging:{redactHeaders:i.map(([a])=>a),redactUrlPatterns:[]},priority:70,owner:"mcp-projection",description:`Managed remote MCP credentials for ${n}.`})}return t}function Xk(e,t){let n=D0e("sha256").update(`${e}\x00${t.toLowerCase()}`).digest("hex").slice(0,16);return`${Xf}-mcp-${n}`}function M0e(e){return e==="openai_chat"||e==="openai_responses"}function L0e(e){let t=[],n=new Set;for(let[r,i]of U0e(e)){let o=z0e(r,i);if(!o)continue;let s=Qk(i.apiKeySecretRef),a=[o.match.scheme,o.match.host,o.match.pathPrefix??"",s??""].join(":");if(n.has(a))continue;n.add(a),t.push(o)}return t}function U0e(e){let t=Object.entries(e.providers??{}).sort(([r],[i])=>{if(r==="default")return-1;if(i==="default")return 1;return r.localeCompare(i)}),n=e.terminalTooling?.codex;if(n?.provider_id&&n.provider)t.push([n.provider_id,n.provider]);return t}function z0e(e,t){let n=B0e(t?.baseUrl),r=H0e(t?.apiMode),i=Qk(t?.apiKeySecretRef);if(!xp(t)||!n||!i||!M0e(r))return null;if(t.status&&t.status!=="ok")return null;let o=new URL(n),s=Rr(e)?zn:e;return{id:s==="default"?"managed-provider":`managed-provider-${z5(s)}`,enabled:!0,kind:"provider",match:{scheme:o.protocol.replace(/:$/,""),host:o.host.toLowerCase(),pathPrefix:F0e(o.pathname),headers:{authorization:{type:"equals",value:Xf,prefix:"Bearer "}},query:{}},rewrite:{preservePath:!0,setHeaders:{authorization:{type:"secretRef",secretRef:i,prefix:"Bearer "}}},logging:{redactHeaders:["authorization"],redactUrlPatterns:[]},priority:80,owner:"provider-projection"}}function F0e(e){if(e==="/")return e;return`${e.replace(/\/+$/,"")}/`}function Qk(e){let t=e?.trim();return t?.startsWith("secret://")&&t.length>9?t:null}function xp(e){return e.managed_by==="clawdi"}function H0e(e){return e?.trim()||null}function B0e(e){if(!e)return null;try{let t=new URL(e);if(!["http:","https:","ws:","wss:"].includes(t.protocol))return null;return t.toString().replace(/\/+$/,"")}catch{return null}}function V0e(e,t){let n=new Set(t.map((r)=>r.id));return{profiles:[...e.profiles.filter((r)=>!n.has(r.id)),...t]}}function z5(e){return e.toLowerCase().replace(/[^a-z0-9-_.]+/g,"-").replace(/^[^a-z0-9]+/,"").replace(/[^a-z0-9]+$/,"")||"provider"}var $p=_(()=>{_i();bs()});import{cpSync as q0e,existsSync as W0e,mkdtempSync as F5,readdirSync as G0e,rmSync as H5}from"node:fs";import{tmpdir as B5}from"node:os";import{basename as K0e,isAbsolute as Z0e,join as Zh,relative as J0e,resolve as Y0e}from"node:path";function ZM(e,t,n){return new URL(`https://codeload.github.com/${encodeURIComponent(e)}/${encodeURIComponent(t)}/tar.gz/${encodeURIComponent(n)}`)}function Lc(e){return Array.from(e).some((t)=>{let n=t.charCodeAt(0);return n<=31||n===127})}async function Ns(e,t,n={}){let r=n.resourceLabel??"GitHub archive",i=n.limitLabel??"100 MB";if(!Number.isSafeInteger(t)||t<=0)throw Error("Response byte limit must be a positive safe integer.");let o=e.headers.get("content-length");if(o!==null){let c=Number(o);if(!Number.isSafeInteger(c)||c<0)throw Error("Response has an invalid Content-Length.");if(c>t)throw await e.body?.cancel("response exceeds byte limit"),Error(`${r} exceeds the ${i} download limit.`)}if(!e.body)throw Error(`${r} response has no body.`);let s=e.body.getReader(),a=[],l=0;try{while(!0){let c=await s.read();if(c.done)break;if(l+=c.value.byteLength,l>t)throw await s.cancel("response exceeds byte limit"),Error(`${r} exceeds the ${i} download limit.`);a.push(c.value)}}finally{s.releaseLock()}return Buffer.concat(a,l)}function Q0e(e){let t=e.split("/");if(e!==e.trim()||t.length===0||t.some((n)=>!n||n==="."||n===".."||n.includes("\\")||Lc(n)))throw Error("GitHub Skill path is invalid.")}function eR(e){let t;try{t=new URL(e)}catch{throw Error("GitHub repository URL is invalid.")}let n=/^\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/.exec(t.pathname);if(t.protocol!=="https:"||t.hostname!=="github.com"||t.username||t.password||t.search||t.hash||!n||e!==`https://github.com${t.pathname}`)throw Error("GitHub repository URL must be canonical.");return{owner:n[1],repo:n[2]}}async function tR(e,t={}){if(e.path)Q0e(e.path);let n=ZM(e.owner,e.repo,e.ref??"HEAD"),r=await(t.fetcher??fetch)(n,{headers:{Accept:"application/vnd.github+json"},redirect:"follow"});if(!r.ok)throw Error(`GitHub archive download failed (${r.status}).`);let i=await Ns(r,X0e),o=F5(Zh(B5(),"clawdi-github-skill-"));try{await Vi(o,i);let s=G0e(o,{withFileTypes:!0}).filter((m)=>m.isDirectory()),a=s.length===1?s[0]:void 0;if(!a)throw Error("GitHub archive has an unexpected root layout.");let l=Zh(o,a.name),c=e.path?Y0e(l,e.path):l,u=J0e(l,c);if(u.startsWith("..")||Z0e(u)||!W0e(Zh(c,"SKILL.md")))throw Error("GitHub source does not contain a Skill at the requested path.");let d=Qu(t.skillKey??K0e(e.path??e.repo)),p=F5(Zh(B5(),"clawdi-github-skill-stage-"));try{let m=Zh(p,d);return q0e(c,m,{recursive:!0}),{skillKey:d,tarBytes:await q$(m,[l,p],d)}}finally{H5(p,{recursive:!0,force:!0})}}finally{H5(o,{recursive:!0,force:!0})}}var X0e=104857600;var Cp=_(()=>{Bi();yr()});function q5(e){return/^[A-Za-z_][A-Za-z0-9_]{0,127}$/.test(e)}function nR(e){let t=e.toLowerCase();return["authorization","cookie","proxy-authorization","x-api-key","x-auth-token"].includes(t)||V5.test(e.replaceAll("-","_"))}function W5(e){return e.toUpperCase()==="AUTH"||V5.test(e)}function rR(e){return/\$\{[^}]*\}/.test(e)}function JM(e){let t=e.trim().toLowerCase();return["bearer ","basic ","apikey ","api-key "].some((n)=>t.startsWith(n))||t.includes("-----begin private key-----")||/^[A-Za-z][A-Za-z0-9+.-]*:\/\/[^/\s:@]+:[^/\s@]+@/.test(e)||/(?:sk|pk|ghp|github_pat|xox[baprs])_[A-Za-z0-9_-]{12,}/.test(e)}var V5;var YM=_(()=>{V5=/(?:^|_)(?:ACCESS_?KEY|API_?KEY|AUTHORIZATION|AUTH_?TOKEN|BEARER_?TOKEN|CLIENT_?SECRET|CREDENTIALS?|PASS(?:WORD|WD)?|PAT|PRIVATE_?KEY|SECRET|TOKEN)(?:_|$)/i});function iOe(e){try{let t=new URL(e);return t.protocol==="https:"&&t.hostname==="github.com"&&!t.username&&!t.password&&!t.search&&!t.hash&&/^\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(t.pathname)}catch{return!1}}function oOe(e){if(e==="")return!0;let t=e.split("/");return e===e.trim()&&t.length>0&&t.every((n)=>n.length>0&&n!=="."&&n!==".."&&!n.includes("\\")&&!Lc(n))}function sOe(e){try{let t=new URL(e);return t.protocol==="https:"&&t.hostname==="github.com"&&!t.username&&!t.password&&!t.search&&!t.hash&&/^\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/releases\/download\/[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+\.tar\.gz$/.test(t.pathname)&&e===`https://github.com${t.pathname}`}catch{return!1}}var K5,Ip,eOe,XM="https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",tOe,nOe,iR,rOe,Z5,aOe,lOe,cOe,Jh,J5,G5,uOe,QM,dOe,pOe,mOe,Y5;var Op=_(()=>{sn();Cp();Ap();YM();K5=y.string().regex(/^[a-z0-9][a-z0-9._-]{0,63}$/),Ip=y.string().min(1).max(64).regex(/^(?!.*(?:--|\.\.))[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/),eOe=y.string().regex(/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/),tOe=y.object({secretRef:Ds,prefix:y.string().max(100).default("")}).strict(),nOe=y.object({url:y.string().url().refine((e)=>{let t=new URL(e);return(t.protocol==="http:"||t.protocol==="https:")&&!t.username&&!t.password&&!t.search&&!t.hash},"must be an HTTP(S) URL without credentials, query, or fragment"),transport:y.enum(["streamable-http","sse"]),headers:y.record(eOe,y.union([y.string(),tOe])).default({})}).strict().superRefine((e,t)=>{if(!Object.values(e.headers).some((r)=>typeof r!=="string"))t.addIssue({code:"custom",message:"at least one MCP header must use secretRef"});let n=new Set;for(let r of Object.keys(e.headers)){let i=r.toLowerCase();if(n.has(i))t.addIssue({code:"custom",message:`duplicate HTTP header ${r}`,path:["headers",r]});if(typeof e.headers[r]==="string"&&nR(r))t.addIssue({code:"custom",message:`credential-bearing HTTP header ${r} must use secretRef`,path:["headers",r]});n.add(i)}}),iR=y.object({servers:y.record(K5,nOe)}).strict(),rOe=y.string().regex(/^[a-f0-9]{40}$/);Z5=y.object({type:y.literal("github"),url:y.string().max(500).refine(iOe,"must be a canonical GitHub repository URL"),path:y.string().max(500).refine(oOe,"must be a safe repository-relative directory"),commit:rOe}).strict();aOe=y.object({type:y.literal("github-release"),url:y.string().max(1000).refine(sOe,"must be a canonical GitHub release asset URL"),archiveDigest:y.string().regex(/^sha256:[0-9a-f]{64}$/)}).strict(),lOe=y.discriminatedUnion("type",[Z5,aOe]),cOe=y.string().min(1).max(256).regex(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/),Jh=y.object({installationId:y.string().min(1).max(200).refine((e)=>e===e.trim()&&!Lc(e),"must be a canonical non-empty identifier"),version:cOe,agentPluginsSchema:y.literal(XM),source:lOe,contentDigest:y.string().regex(/^sha256-tree-v1:[0-9a-f]{64}$/)}).strict(),J5=y.object({schemaVersion:y.literal(1),installations:y.record(Ip,Jh).refine((e)=>Object.keys(e).length<=128,"must contain at most 128 entries")}).strict(),G5=y.string().url().max(2000).refine((e)=>{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:")&&!t.username&&!t.password&&!t.search&&!t.hash},"must be a clean HTTP(S) URL"),uOe=y.object({type:y.literal("project"),projectId:y.uuid(),contentHash:y.string().regex(/^[a-f0-9]{64}$/),archiveUrl:G5,installUrl:G5}).strict(),QM=y.discriminatedUnion("type",[Z5,uOe]),dOe=y.object({enabled:y.boolean(),version:y.number().int().positive().default(1)}).strict(),pOe=y.object({enabled:y.boolean(),source:QM}).strict(),mOe=y.union([dOe,pOe]),Y5=y.object({entries:y.record(K5,mOe)}).strict()});import{existsSync as e1,readFileSync as t1}from"node:fs";import{basename as fOe,dirname as X5,join as gOe}from"node:path";function Tp(e){return Q5.safeParse(e).success}function yOe(e){let t=fOe(e),n=Xo.safeParse(t);return n.success?n.data:null}function sR(e,t){return t?`${e}+${t}`:e}function n1(e,t=de(),n){return gOe(t.runConfigRoot,`${sR(e,n)}.json`)}function r1(e){let n=[...e.commandPath?[X5(e.commandPath)]:[],...e.settings?.prependPath??[]].filter((r,i,o)=>o.indexOf(r)===i);return{schemaVersion:"clawdi.runtimeRunConfig.v1",runtime:e.runtime,service:e.service??null,enabled:e.enabled,generatedAt:e.generatedAt,generation:e.generation,instanceId:e.instanceId,command:e.settings?.command??e.commandPath??e.runtime,defaultArgs:e.settings?.args??(e.service?[]:vOe(e.runtime)),env:e.settings?.env??{},secretEnv:e.secretEnv??{},secretFilePath:e.secretFilePath??null,prependPath:n,cwd:e.settings?.cwd??e.workspaceRoot,commandPath:e.commandPath,appRoot:e.appRoot,egressProfileBundlePath:e.egressProfileBundlePath??null}}function i1(e,t){let n=n1(e.runtime,t,e.service);return Ut(t,n,`${JSON.stringify(e,null,2)}
|
|
262
262
|
`,{mode:420,dirMode:493}),n}function tJ(e,t=de()){let n=yOe(e);if(!n)return{status:"not-runtime",runtime:null};let r=n1(n,t);if(!e1(r))return Tp(n)?{status:"missing",runtime:n,path:r}:{status:"not-runtime",runtime:null};try{let i=eJ.parse(JSON.parse(t1(r,"utf8")));if(!i.enabled)return{status:"disabled",runtime:n,path:r,config:i};return{status:"ok",runtime:n,path:r,config:i}}catch(i){return{status:"invalid",runtime:n,path:r,error:U(i)}}}function nJ(e,t,n=de()){let r=Xo.safeParse(e);if(!r.success)return{status:"not-runtime",runtime:null};let i=sl.safeParse(t);if(!i.success)return{status:"not-runtime",runtime:null};let o=n1(r.data,n,i.data);if(!e1(o))return{status:"missing",runtime:r.data,path:o};try{let s=eJ.parse(JSON.parse(t1(o,"utf8")));if(!s.enabled)return{status:"disabled",runtime:r.data,path:o,config:s};return{status:"ok",runtime:r.data,path:o,config:s}}catch(s){return{status:"invalid",runtime:r.data,path:o,error:U(s)}}}function aR(e,t,n,r=de()){let i=e.config.prependPath.join(":"),o=Yh(n.PATH??"",X5(r.cliManagedBin)),s={...n,...e.config.env,...wOe(e.config.secretFilePath,e.config.secretEnv),PATH:i?[i,o].filter(Boolean).join(":"):o};if(e.config.egressProfileBundlePath)Ea(s);let a=e.config.commandPath&&e1(e.config.commandPath)?e.config.commandPath:e.config.command;return{runtime:e.runtime,service:e.config.service,command:a,args:t.length>1?t.slice(1):e.config.defaultArgs,cwd:e.config.cwd,env:s}}function Yh(e,t){return e.split(":").filter((n)=>n&&n!==t).join(":")}function vOe(e){let t=Q5.safeParse(e);return t.success?hOe[t.data]:[]}function wOe(e,t){let n=Object.entries(t);if(n.length===0)return{};if(!e)throw Error("Runtime run config references secrets but has no secret file.");let r={};if(e){let o;try{o=JSON.parse(t1(e,"utf-8"))}catch(s){throw Error(`Runtime secret file is unavailable: ${U(s)}`)}if(!o||typeof o!=="object"||Array.isArray(o))throw Error("Runtime secret file must contain a JSON object.");r=y.record(y.string(),y.unknown()).parse(o)}let i={};for(let[o,s]of n){let a=It(r,s);if(!a)throw Error(`Runtime secret ${s} for ${o} is unavailable.`);i[o]=a}return i}var Xo,sl,Q5,oR,Rht,eJ,hOe;var al=_(()=>{sn();Zt();bs();Lt();Yr();Un();Xo=y.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/).refine((e)=>e!=="clawdi","Runtime name is reserved."),sl=y.string().regex(/^[a-z0-9][a-z0-9._-]{0,63}$/).refine((e)=>e!=="main","Runtime service name is reserved."),Q5=y.enum(["hermes","openclaw"]),oR=y.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),Rht=y.object({command:y.string().min(1).optional(),args:y.array(y.string()).optional(),env:y.record(oR,y.string()).default({}),secretEnv:y.record(oR,lr).optional(),cwd:y.string().min(1).optional(),prependPath:y.array(y.string().min(1)).default([])}),eJ=y.object({schemaVersion:y.literal("clawdi.runtimeRunConfig.v1"),runtime:Xo,service:sl.nullable().default(null),enabled:y.boolean(),generatedAt:y.string().min(1),generation:y.number().int().nonnegative(),instanceId:y.string().min(1),command:y.string().min(1),defaultArgs:y.array(y.string()).default([]),env:y.record(oR,y.string()).default({}),secretEnv:y.record(oR,lr).default({}),secretFilePath:y.string().min(1).nullable().default(null),prependPath:y.array(y.string().min(1)).default([]),cwd:y.string().min(1).optional(),commandPath:y.string().min(1).nullable(),appRoot:y.string().min(1).nullable(),egressProfileBundlePath:y.string().min(1).nullable().default(null)}).strict(),hOe={hermes:["gateway","run"],openclaw:["gateway","run"]}});import{isIP as _Oe}from"node:net";import{join as bOe}from"node:path";function o1(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>n===t[r])}function s1(e,t){return o1(t,ROe)||e==="openclaw"&&o1(t,POe)}function AOe(e){return o1(e,EOe)}function $Oe(e,t){let n=[...xOe[e]??[]];return e==="openclaw"?[...n,"--prefix",bOe(t,".local")]:n}function OOe(e){try{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password&&!t.search&&!t.hash?t:null}catch{return null}}function NOe(e){try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(),!0}catch{return!1}}function LOe(e){let t=/^clawdi@(.+)$/.exec(e)?.[1];return t!==void 0&&UOe(t)}function UOe(e){let t=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/.exec(e);if(!t)return!1;let n=t[4];if(!n)return!0;return n.split(".").every((r)=>!/^\d+$/.test(r)||/^(0|[1-9]\d*)$/.test(r))}function qOe(e,t,n){try{let r=new URL(e);return r.protocol==="https:"&&r.hostname==="github.com"&&r.port===""&&r.username===""&&r.password===""&&r.search===""&&r.hash===""&&r.pathname===`/gtsteffaniak/filebrowser/releases/download/${t}/linux-${n}-filebrowser`}catch{return!1}}function cJ(e,t){let n=e.status==="error",r=e.error!==void 0;if(n!==r)t.addIssue({code:"custom",message:"provider status:error and error must be supplied together",path:n?["error"]:["status"]});let i=n&&e.error?.code==="provider_not_found",o=e.type!==void 0&&e.baseUrl!==void 0;if(!i&&!o)t.addIssue({code:"custom",message:"provider must include type and baseUrl unless it is a provider_not_found error",path:[]})}function yTe(e,t){let n=(s,a)=>{t.addIssue({code:"custom",message:s,path:a})},r=(...s)=>["system",...s],i=(...s)=>["runtimes",e.runtime,...s],o=e.runtimes[e.runtime];if(!o)n(`runtimes.${e.runtime} must be present for selected runtime`,["runtimes",e.runtime]);for(let s of Object.keys(e.runtimes))if(s!==e.runtime)n("hosted runtime manifests must declare exactly one selected runtime",["runtimes",s]);if(o?.enabled!==!0)n("selected runtime must be enabled",["runtimes",e.runtime,"enabled"]);if(e.expiresAt){let s=Date.parse(e.expiresAt);if(!Number.isFinite(s))n("manifest expiresAt is not a valid timestamp",["expiresAt"]);else if(s<=Date.now())n(`manifest expired at ${e.expiresAt}`,["expiresAt"])}if(e.runtime==="openclaw"){let s=e.system.openclawGatewayAuth;if(!s)n("OpenClaw v2 native Control UI requires official gateway token authentication",r("openclawGatewayAuth"));else if(s.activation.enabled!==!0)n("OpenClaw native auth activation must be explicitly enabled",r("openclawGatewayAuth","activation","enabled"));if(!e.system.openclawControlUiAllowedOrigins?.length)n("OpenClaw v2 native Control UI requires an explicit public allowed origin",r("openclawControlUiAllowedOrigins"));let a=e.runtimes.openclaw?.run;if(!s1("openclaw",a?.args))n("OpenClaw v2 gateway must use the official gateway run command",i("run","args"));if(a?.secretEnv?.OPENCLAW_GATEWAY_TOKEN!==s?.tokenRef)n("OpenClaw v2 gateway token must use the declared environment secret reference",i("run","secretEnv","OPENCLAW_GATEWAY_TOKEN"));for(let[l,c]of Object.entries(e.providers))if(c.runtimeEnvName==="OPENCLAW_GATEWAY_TOKEN")n("OpenClaw v2 provider environment must not target native auth controls",["providers",l,"runtimeEnvName"])}else{if(!e.system.hermesDashboardAuth)n("hermes direct dashboard requires official password authentication",r("hermesDashboardAuth"));if(e.system.hermesDashboardAuth?.activation.enabled!==!0)n("hermes password authentication must be explicitly enabled",r("hermesDashboardAuth","activation","enabled"));if(e.system.openclawGatewayAuth)n("OpenClaw gateway auth is only valid for the OpenClaw runtime",r("openclawGatewayAuth"));if(e.system.openclawGatewayTrustedProxies)n("OpenClaw trusted proxies are only valid for the OpenClaw runtime",r("openclawGatewayTrustedProxies"));if(!s1("hermes",e.runtimes.hermes?.run.args))n("Hermes gateway must use the official gateway run command",i("run","args"));if(!AOe(e.runtimes.hermes?.services.dashboard?.args))n("hermes dashboard must bind directly to 0.0.0.0:9119",i("services","dashboard","args"))}if(o){let s=new Set(o.provider_ids);for(let a of s)if(!Object.hasOwn(e.providers,a))t.addIssue({code:"custom",message:"runtime provider must have a matching provider projection",path:["providers",a]});for(let a of Object.keys(e.providers))if(!s.has(a))t.addIssue({code:"custom",message:"provider projection must be selected by the runtime",path:["providers",a]})}if(e.runtime==="hermes"){let s=e.runtimes.hermes;if(s?.run.secretEnv)t.addIssue({code:"custom",message:"Hermes gateway must not declare OpenClaw gateway credentials",path:["runtimes","hermes","run","secretEnv"]});let a=Object.keys(s?.services??{});if(a.length!==1||a[0]!=="dashboard")t.addIssue({code:"custom",message:"Hermes must declare only its official dashboard command",path:["runtimes","hermes","services"]})}else if(e.system.hermesDashboardAuth)t.addIssue({code:"custom",message:"Hermes dashboard auth is only valid for the Hermes runtime",path:["system","hermesDashboardAuth"]});if(e.runtime==="openclaw"&&Object.keys(e.runtimes.openclaw?.services??{}).length>0)t.addIssue({code:"custom",message:"OpenClaw hosted runtime must not declare auxiliary services",path:["runtimes","openclaw","services"]})}function wTe(e){if(e.providerMode==="unmanaged")return{provider_ids:[]};return{provider_ids:e.provider_ids,primary_model:e.primary_model}}function _Te(e,t){let n=dJ(t);if(s1(e,t.args))n.args=["gateway","run"];return n}function dJ(e){return{args:[...e.args],env:{},prependPath:[],...e.secretEnv===void 0?{}:{secretEnv:{...e.secretEnv}}}}function pJ(e,t){let n=e.manifest.runtime;if(!n)return;if(e.manifest.runtimes[n]?.providerMode!=="unmanaged")return;let i=Ep(e.manifest.projection?.terminalTooling?.codex.provider.apiKeySecretRef);for(let o of Object.keys(e.secretValues)){let s=Ep(o);if(!s?.startsWith("provider.")||s===i)continue;t.addIssue({code:"custom",message:"unmanaged provider mode must not include provider secret values",path:["secretValues",o]})}}function fJ(e){return Object.keys(e.projection?.agentPlugins?.installations??{}).length>0}var SOe="clawdi.runtimeDesiredState.v1",oJ="clawdi.hosted-runtime.bundle.v2",kOe,ROe,POe,EOe,xOe,COe,IOe,TOe,jOe,DOe,MOe,Uc,zOe,FOe,HOe=9120,BOe,VOe,rJ,iJ="clawdi-files:",WOe,GOe,KOe,ZOe,JOe,YOe,XOe,QOe,eTe,sJ,tTe,aJ,nTe,rTe,iTe,oTe,sTe,aTe,lTe,lJ,cTe,uTe,dTe,pTe,mTe,fTe,gTe,hTe,vTe,uJ,mJ="Agent Plugin installations require a newer Clawdi runtime capability";var Xh=_(()=>{_i();sn();T5();Ap();$p();Op();Lt();al();Yr();kOe={openclaw:"https://openclaw.ai/install-cli.sh",hermes:"https://hermes-agent.nousresearch.com/install.sh"},ROe=["gateway","run"],POe=["gateway","run","--allow-unconfigured","--port","18789","--bind","lan","--force"],EOe=["dashboard","--host","0.0.0.0","--port","9119","--no-open"];xOe={openclaw:["--json","--no-onboard"],hermes:["--skip-setup","--skip-browser","--non-interactive"]};COe=y.enum(["openclaw","hermes"]),IOe=y.string().max(64).refine((e)=>_Oe(e)!==0,"must be an exact IPv4 or IPv6 address");TOe=y.object({mode:y.literal("password"),provider:y.literal("basic"),username:y.string().trim().min(1).max(128),passwordSecretRef:y.literal("secret://runtime/hermes/dashboard-password"),sessionSecretRef:y.literal("secret://runtime/hermes/dashboard-session-secret"),sessionTtlSeconds:y.number().int().min(60).max(604800).default(43200),publicUrl:y.string().url(),activation:y.object({enabled:y.literal(!0),capability:y.literal("hermes-basic-auth-v1")}).strict()}).strict().superRefine((e,t)=>{if(!OOe(e.publicUrl))t.addIssue({code:"custom",message:"must be an HTTPS URL without credentials, query, or fragment",path:["publicUrl"]})}),jOe=y.object({mode:y.literal("token"),tokenRef:y.literal("secret://runtime/openclaw/gateway-token"),deviceAuthRequired:y.literal(!1),activation:y.object({enabled:y.literal(!0),capability:y.literal("openclaw-native-auth-v1")}).strict()}).strict(),DOe=["en","zh-CN","zh-TW","ja","ko","es","fr","de","pt"];MOe=y.object({language:y.enum(DOe),timezone:y.string().min(1).refine(NOe,"must be a valid IANA timezone")}).strict();Uc=y.string().max(200).refine(LOe,"must be clawdi@<exact-semver>"),zOe=y.object({source:y.literal("npm:clawdi"),packageSpec:Uc,registry:y.literal("https://registry.npmjs.org")}).strict(),FOe=y.string().regex(/^[a-fA-F0-9]{64}$/),BOe=y.string().regex(/^v[0-9A-Za-z][0-9A-Za-z._-]{0,63}$/,"must be a canonical release tag"),VOe=y.string().regex(/^[a-f0-9]{40}$/),rJ=y.object({url:y.string().url(),sha256:FOe}).strict();WOe=y.object({method:y.literal("jwt"),algorithm:y.literal("HS256"),header:y.literal("X-JWT-Assertion"),userIdentifier:y.literal("sub"),groupsClaim:y.literal("groups"),secret:y.string().min(43).max(128).regex(/^[A-Za-z0-9_-]+$/),audience:y.string().min(1).max(256),subject:y.string().min(1).max(256),requiredGroup:y.string().min(1).max(256),accessRevision:y.string().regex(/^[a-f0-9]{64}$/)}).strict().superRefine((e,t)=>{let n=e.audience.startsWith(iJ)?e.audience.slice(iJ.length):"";if(!n||e.subject!==`deployment:${n}:owner`||e.requiredGroup!==`${e.audience}:${e.accessRevision}`)t.addIssue({code:"custom",message:"Files authentication fields must reference one deployment revision"})}),GOe=y.object({version:BOe,commit:VOe,listen:y.literal("0.0.0.0"),port:y.literal(HOe),baseURL:y.literal("/"),healthPath:y.literal("/health"),sourceRoot:y.literal("/home/clawdi"),assets:y.object({amd64:rJ,arm64:rJ}).strict(),auth:WOe}).strict().superRefine((e,t)=>{for(let n of["amd64","arm64"])if(!qOe(e.assets[n].url,e.version,n))t.addIssue({code:"custom",message:"Files asset URL must match its declared release and architecture",path:["assets",n,"url"]})}),KOe=y.object({filebrowser:GOe.optional()}).strict(),ZOe=y.object({agentType:Xo,environmentId:y.string().min(1)}),JOe=y.object({cloudApiUrl:y.string().url()}).strict(),YOe=y.object({args:y.array(y.string()),secretEnv:y.object({OPENCLAW_GATEWAY_TOKEN:y.literal("secret://runtime/openclaw/gateway-token")}).strict().optional()}).strict(),XOe=y.object({args:y.array(y.string())}).strict(),QOe=y.string().refine((e)=>{try{let t=new URL(e);return(t.protocol==="http:"||t.protocol==="https:")&&t.origin===e}catch{return!1}},"must be an HTTP(S) URL origin"),eTe=y.object({source:y.literal("official")}).strict(),sJ=y.object({provider_id:y.string().min(1),model:y.string().min(1)}).strict(),tTe=y.array(y.string().min(1)).min(1).max(1),aJ={enabled:y.boolean(),install:eTe,run:YOe,services:y.record(sl,XOe).default({})},nTe=y.object({...aJ,providerMode:y.literal("configured"),provider_ids:tTe,primary_model:sJ}).strict().superRefine((e,t)=>{if(e.primary_model&&!e.provider_ids.includes(e.primary_model.provider_id))t.addIssue({code:"custom",message:"primary model provider must be included in provider_ids",path:["primary_model","provider_id"]})}),rTe=y.object({...aJ,providerMode:y.literal("unmanaged"),provider_ids:y.array(y.string()).length(0)}).strict(),iTe=y.discriminatedUnion("providerMode",[nTe,rTe]),oTe=y.object({chat:y.boolean().optional(),responses:y.boolean().optional(),tools:y.boolean().optional(),vision:y.boolean().optional(),embeddings:y.boolean().optional(),image_generation:y.boolean().optional()}).strict(),sTe=y.object({input:y.number().nonnegative(),output:y.number().nonnegative(),cache_read:y.number().nonnegative().optional(),cache_write:y.number().nonnegative().optional()}).strict(),aTe=y.object({id:y.string().min(1),label:y.string().min(1).optional(),alias:y.string().min(1).optional(),api_mode:y.enum(zb).optional(),input_modalities:y.array(y.enum(["text","image","video","audio"])).optional(),supports_vision:y.boolean().optional(),supports_tools:y.boolean().optional(),supports_reasoning:y.boolean().optional(),compat:y.record(y.string(),y.unknown()).optional(),context_window:y.number().int().positive().optional(),max_input_tokens:y.number().int().positive().optional(),max_tokens:y.number().int().positive().optional(),cost:sTe.optional(),capabilities:oTe.optional()}).strict(),lTe=y.object({type:y.string().min(1),tool:y.string().min(1).optional(),profile:y.string().min(1).optional(),source:y.string().min(1).optional(),ref:y.string().min(1).optional(),credentialSecretRef:lr.optional(),credentialRevision:y.string().min(1).max(64).optional()}).strict().superRefine((e,t)=>{let n=e.credentialSecretRef!==void 0,r=e.credentialRevision!==void 0;if(n!==r)t.addIssue({code:"custom",message:"OAuth credential secret ref and revision must be supplied together",path:[n?"credentialRevision":"credentialSecretRef"]})}),lJ=y.object({kind:y.literal("openai-compatible"),type:y.enum(t0).optional(),baseUrl:y.string().url().optional(),models:y.array(aTe).optional(),apiMode:y.enum(zb).optional(),managed_by:y.enum(["user","clawdi"]).optional(),runtimeEnvName:y.string().min(1).optional(),apiKeySecretRef:lr.nullable().optional(),apiKeyRequired:y.boolean().optional(),status:y.literal("error").optional(),error:y.object({code:y.string().min(1),message:y.string().min(1)}).strict().optional(),auth:lTe.optional()}).strict();cTe=lJ.superRefine(cJ),uTe=cTe.superRefine((e,t)=>{if(e.managed_by==="clawdi"&&e.runtimeEnvName!==kr)t.addIssue({code:"custom",message:`Clawdi-managed runtime providers require ${kr}`,path:["runtimeEnvName"]})}),dTe=lJ.omit({models:!0}).superRefine(cJ),pTe=y.object({enabled:y.literal(!0),provider_id:y.string().min(1),primary_model:sJ,provider:dTe}).strict().superRefine((e,t)=>{if(e.primary_model.provider_id!==e.provider_id)t.addIssue({code:"custom",message:"Codex tool primary model provider must match provider_id",path:["primary_model","provider_id"]});if(e.provider.managed_by!=="clawdi"||e.provider.apiMode!=="openai_responses"||Ep(e.provider.apiKeySecretRef)!=="tool.codex.apiKey"||e.provider.runtimeEnvName!==kr||e.provider.status==="error")t.addIssue({code:"custom",message:"Codex tool requires a healthy Clawdi-managed provider secret reference",path:["provider"]})}),mTe=y.object({codex:pTe}).strict(),fTe=ZOe.extend({agentType:y.enum(["openclaw","hermes","codex"]),environmentId:y.string().min(1).max(200).refine((e)=>e===e.trim(),"must not contain surrounding whitespace")}).strict(),gTe=y.object({enabled:y.boolean(),agents:y.array(fTe)}).strict().superRefine((e,t)=>{let n=e.agents.map((i)=>`${i.agentType}\x00${i.environmentId}`);if(new Set(n).size!==n.length)t.addIssue({code:"custom",path:["agents"],message:"must not contain duplicate agent identities"});let r=e.agents.length>0;if(e.enabled!==r)t.addIssue({code:"custom",path:["enabled"],message:"must match whether agents are configured"})}),hTe=y.object({runtime:COe,deploymentId:y.string().min(1),environmentId:y.string().min(1),instanceId:y.string().min(1),generation:y.number().int().nonnegative(),issuedAt:y.string().min(1),expiresAt:y.string().min(1).optional(),locale:MOe,system:y.object({openclawControlUiAllowedOrigins:y.array(QOe).optional(),openclawGatewayTrustedProxies:y.array(IOe).min(1).max(16).refine((e)=>new Set(e).size===e.length,"must not contain duplicates").optional(),openclawControlUiBasePath:y.string().regex(/^\/(?:[^/?#]+(?:\/[^/?#]+)*)?$/).optional(),openclawGatewayAuth:jOe.optional(),hermesDashboardAuth:TOe.optional()}).strict(),controlPlane:JOe,egressEngine:O5.strict().optional(),companions:KOe.optional(),runtimes:y.record(Xo,iTe),providers:y.record(y.string().min(1),uTe),liveSync:gTe,egressProfiles:M5.strict().optional(),mcp:iR.optional(),skills:Y5.optional(),tools:y.unknown().optional(),terminalTooling:mTe,recovery:y.object({cacheManifest:y.boolean(),allowOfflineBoot:y.boolean()}).strict()}).strict();vTe=hTe.safeExtend({schemaVersion:y.literal("clawdi.hosted-runtime.manifest.v1"),clawdiCli:zOe,agentPlugins:J5.optional()}).strict().superRefine(yTe),uJ=vTe.transform((e)=>{let t=de({mode:"hosted"}),n=e.runtime,r=e.runtimes[n];if(!r)throw Error(`missing selected runtime ${n}`);return{schemaVersion:SOe,deploymentId:e.deploymentId,environmentId:e.environmentId,instanceId:e.instanceId,generation:e.generation,issuedAt:e.issuedAt,expiresAt:e.expiresAt,locale:e.locale,runtime:n,controlPlane:{apiUrl:e.controlPlane.cloudApiUrl},clawdiCli:{...e.clawdiCli},egressEngine:e.egressEngine,companions:e.companions,runtimes:{[n]:{enabled:r.enabled,providerMode:r.providerMode,install:{authority:"official",method:"official-installer",url:kOe[n],home:t.userHome,args:$Oe(n,t.userHome)},run:_Te(n,r.run),services:Object.fromEntries(Object.entries(r.services).map(([i,o])=>[i,dJ(o)])),...wTe(r)}},openclawGatewayAuth:e.system.openclawGatewayAuth,hermesDashboardAuth:e.system.hermesDashboardAuth,projection:{system:e.system,providers:e.providers,...e.mcp===void 0?{}:{mcp:e.mcp},...e.skills===void 0?{}:{skills:e.skills},...e.agentPlugins===void 0?{}:{agentPlugins:e.agentPlugins},...e.tools===void 0?{}:{tools:e.tools},...e.terminalTooling===void 0?{}:{terminalTooling:e.terminalTooling}},liveSync:e.liveSync,egressProfiles:U5(e),recovery:{...e.recovery}}})});import{readFileSync as bTe}from"node:fs";import{isAbsolute as STe}from"node:path";function Jt(e){return e.applyGeneration??e.generation}function Qo(e,t){if(e===null||t===null)return e===t;return e.generation===t.generation&&e.manifestETag===t.manifestETag&&e.applyReceiptId===t.applyReceiptId&&e.bootNonce===t.bootNonce}function es(e=xTe()){let t=$Te(e);return{kind:"context-file",backend:t.backend,identity:t.apply,manifestSource:t.manifestSource}}function xTe(){let e=process.env[a1];if(e===void 0)return kTe;if(process.env.CLAWDI_RUNTIME_ALLOW_TEST_INSTALLERS!=="1")throw Error(`${a1} is available only with CLAWDI_RUNTIME_ALLOW_TEST_INSTALLERS=1`);if(!e||e!==e.trim()||!STe(e))throw Error(`${a1} must be a canonical absolute path`);return e}function $Te(e){let t;try{t=JSON.parse(bTe(e,"utf-8"))}catch(r){throw Error(`could not read runtime context file ${e}: ${U(r)}`)}let n=ATe.safeParse(t);if(!n.success)throw Error(`invalid runtime context file ${e}: ${n.error.issues.map((r)=>`${r.path.join(".")}: ${r.message}`).join("; ")}`);return n.data}function l1(e,t){return y.string().min(e).max(t).refine((n)=>n===n.trim(),"must not contain surrounding whitespace")}var jp,kTe,a1="CLAWDI_RUNTIME_TEST_CONTEXT_FILE",RTe,gJ,PTe,ETe,ATe;var Ms=_(()=>{sn();Zt();Xh();Lt();jp=y.object({generation:y.number().int().positive().safe(),manifestETag:l1(1,128),applyReceiptId:l1(16,128),bootNonce:l1(16,128)}).strict();kTe=de({mode:"hosted"}).runtimeContextFile,RTe=y.string().min(1).refine((e)=>e===e.trim(),"must not have surrounding whitespace").refine((e)=>[...e].every((t)=>{let n=t.charCodeAt(0);return n>31&&n!==127}),"must not contain control characters"),gJ=y.object({type:y.literal("http"),url:y.url().refine((e)=>{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:")&&!t.username&&!t.password&&!t.hash&&t.pathname.endsWith("/v1/runtime/manifest")},"must be an HTTP(S) /v1/runtime/manifest URL without credentials or a fragment"),auth:y.object({type:y.literal("bearer"),token:RTe}).strict()}).strict(),PTe=y.object({schemaVersion:y.literal("clawdi.runtimeContext.v2"),backend:y.literal("incus"),apply:jp,cliPackageSpec:Uc,manifestSource:gJ}).strict(),ETe=y.object({schemaVersion:y.literal("clawdi.runtimeContext.v3"),backend:y.literal("incus"),apply:jp,manifestSource:gJ}).strict(),ATe=y.discriminatedUnion("schemaVersion",[PTe,ETe])});import{createHash as CTe}from"node:crypto";import{chmodSync as ITe,chownSync as OTe,readFileSync as TTe,statSync as jTe}from"node:fs";function Ls(e){if(e.manifestETag===void 0||e.applyReceiptId===void 0||e.bootNonce===void 0)return null;let t=jp.safeParse({generation:Jt(e),manifestETag:e.manifestETag,applyReceiptId:e.applyReceiptId,bootNonce:e.bootNonce});return t.success?t.data:null}function bi(e){return CTe("sha256").update(JSON.stringify(c1(e))).digest("hex")}function $n(e){let t;try{t=TTe(e.appliedState,"utf-8")}catch(n){if(n.code==="ENOENT")return null;throw n}try{return hJ.parse(JSON.parse(t))}catch(n){return C.warn("runtime.applied_state_invalid",{path:e.appliedState,error:U(n)}),null}}function yJ(e,t){let n=hJ.parse(e);return Ut(t,t.appliedState,`${JSON.stringify(n,null,2)}
|
|
263
263
|
`,{mode:384,dirMode:493}),zTe(t.appliedState),t.appliedState}function zTe(e){if(typeof process.getuid!=="function")return;let t=jTe(e);if((t.mode&511)!==384)ITe(e,384);if(process.getuid()===0&&(t.uid!==0||t.gid!==0))OTe(e,0,0)}function c1(e){if(Array.isArray(e))return e.map(c1);if(e&&typeof e==="object"){let t=e;return Object.fromEntries(Object.keys(t).sort().map((n)=>[n,c1(t[n])]))}return e}var DTe,NTe,MTe,LTe,UTe,hJ;var eo=_(()=>{sn();Zt();Ms();Un();DTe=y.object({sourcePath:y.string().min(1),sha256:y.string().regex(/^[a-f0-9]{64}$/)}).strict(),NTe=y.record(y.string().min(1),y.array(y.string().min(1)).refine((e)=>new Set(e).size===e.length,{message:"projected provider IDs must be unique"})),MTe=y.record(y.string().regex(/^[A-Za-z0-9_.@-]+\.service$/),y.string().regex(/^[a-f0-9]{64}$/)),LTe=y.record(y.string().regex(/^[A-Za-z0-9_.@-]+\.service$/),y.string().regex(/^[a-f0-9]{64}$/)),UTe=y.array(y.string().min(1)).refine((e)=>new Set(e).size===e.length,{message:"provider IDs must be unique"}),hJ=y.object({schemaVersion:y.literal("clawdi.runtimeAppliedState.v2"),appliedAt:y.string().datetime({offset:!0}),instanceId:y.string().min(1),etag:y.string().min(1),sourceRevision:y.string().regex(/^[a-f0-9]{64}$/),generation:y.number().int().nonnegative(),applyGeneration:y.number().int().positive().safe().optional(),manifestETag:y.string().min(1).max(128).optional(),applyReceiptId:y.string().min(16).max(128).optional(),bootNonce:y.string().min(16).max(128).optional(),contentIdentity:DTe,activated:LTe,officialServiceCommandRevisions:MTe.optional(),providerIds:UTe,projectedProviderIds:NTe}).strict().superRefine((e,t)=>{let n=[e.manifestETag,e.applyReceiptId,e.bootNonce],r=n.filter((i)=>i!==void 0).length;if(r!==0&&r!==n.length)t.addIssue({code:"custom",message:"manifestETag, applyReceiptId, and bootNonce must be present together",path:["manifestETag"]});if(r===n.length&&Jt(e)<1)t.addIssue({code:"custom",message:"apply identity generation must be at least 1",path:["generation"]})})});function ll(e,t,n,r={}){if(sc(e,t))Ut(e,t,n,r);else me(t,n,r)}function vJ(e,t,n){let r=`${JSON.stringify(t,null,2)}
|
|
264
|
-
`;if(n)ll(n,e,r);else me(e,r)}function W(e){if(!e||typeof e!=="object"||Array.isArray(e))return null;return e}function Qh(e,t){return Object.keys(e).sort().join("\x00")===[...t].sort().join("\x00")}function u1(e){let t=new URL(e);if(t.protocol==="https:")t.protocol="wss:";else if(t.protocol==="http:")t.protocol="ws:";else throw Error("URL must use HTTP or HTTPS");if(t.pathname==="/"&&!t.search&&!t.hash)return t.origin;return t.toString()}function dt(e){return typeof e==="string"?e:null}function Dp(e,t){return JSON.stringify(lR(e))===JSON.stringify(lR(t))}function lR(e){if(Array.isArray(e))return e.map(lR);if(!Ye(e))return e;return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,lR(n)]))}function Ye(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var Si=_(()=>{At();Un()});function cl(e,t){return t.userHome}import{resolve as wJ}from"node:path";function zc(e,t,n){return t==="hermes"?wJ(e,".hermes","platforms","whatsapp","session"):wJ(e,".openclaw","credentials","whatsapp",n)}function Mp(e){if(!Array.isArray(e))return[];return e.flatMap(FTe).sort((t,n)=>`${t.target}:${t.accountKey}:${t.credentialId}`.localeCompare(`${n.target}:${n.accountKey}:${n.credentialId}`))}function FTe(e){let t=W(e);if(!t)return[];if(t.provider!=="whatsapp"||t.kind!=="whatsapp_baileys_auth_state")return[];let n=Np(t.accountKey),r=Np(t.linkId),i=Np(t.credentialId),s=(Array.isArray(t.files)?t.files:[]).map(W).find((f)=>f?.path==="creds.json"&&typeof f.secretRef==="string"),a=s?Np(s.secretRef):null;if(!n||!i||!a)throw Error("WhatsApp auth credential projection is incomplete");let l=W(t.targets);if(!l)throw Error("WhatsApp auth credential projection is incomplete");let c=[],u=W(l.openclaw),d=Np(u?.authDir);if(d)c.push({accountKey:n,linkId:r,credentialId:i,authDir:d,credsJsonSecretRef:a,target:"openclaw"});let p=W(l.hermes),m=p?Np(p.authDir):null;if(m)c.push({accountKey:n,linkId:r,credentialId:i,authDir:m,credsJsonSecretRef:a,target:"hermes"});if(c.length===0)throw Error("WhatsApp auth credential projection is incomplete");return c}function Np(e){return typeof e==="string"&&e.trim()?e.trim():null}var ey=_(()=>{Si()});function Lp(e){let t=W(e),n=W(t?.authCert),r=W(n?.PUBLIC_KEY),i=n?.ISSUER,o=n?.SERIAL,s=r?.data;if(!t||!Qh(t,["authCert","schemaVersion"])||t.schemaVersion!==ty||!n||!Qh(n,["ISSUER","PUBLIC_KEY","SERIAL"])||typeof o!=="number"||!Number.isSafeInteger(o)||o<0||typeof i!=="string"||i.length===0||i.trim()!==i||i.length>256||!r||!Qh(r,["data","type"])||r.type!=="Buffer"||typeof s!=="string"||!HTe(s,32))throw Error("invalid Clawdi managed WhatsApp socket metadata");return{schemaVersion:ty,authCert:{SERIAL:o,ISSUER:i,PUBLIC_KEY:{type:"Buffer",data:s}}}}function d1(e){let t=W(e);if(!t||!Qh(t,["credentialId","schemaVersion"])||t.schemaVersion!==cR||typeof t.credentialId!=="string"||t.credentialId.length===0||t.credentialId.trim()!==t.credentialId)throw Error("invalid Clawdi managed WhatsApp credential metadata");return{schemaVersion:cR,credentialId:t.credentialId}}function HTe(e,t){let n=Buffer.from(e,"base64");return n.length===t&&n.toString("base64")===e}var Fc="clawdi.managedWhatsAppSocket",ty="clawdi.managedWhatsAppSocket.v1",Hc="clawdi.managedWhatsAppCredential",cR="clawdi.managedWhatsAppCredential.v1";var p1=_(()=>{Si()});function uR(e,t=de({mode:"hosted"})){if(!e.channelBindings)return e;let{channelBindings:n,...r}=e,i={...e.secretValues??{}};for(let l of n)if(l.provider==="whatsapp"&&l.placeholderTokenSecretRef)delete i[l.placeholderTokenSecretRef];let o=n.map((l)=>qTe(l,i)),s=GTe(e.manifest,o,t),a=sje(o.filter((l)=>l.account.provider==="whatsapp"),s.projection?.channelCredentials);return{...r,manifest:s,secretValues:{...i,...a}}}function qTe(e,t){if(!It(t,e.agentTokenSecretRef))throw Error(`runtime bundle is missing ${e.agentTokenSecretRef}`);if(e.provider!=="whatsapp"&&!It(t,e.placeholderTokenSecretRef))throw Error(`runtime bundle is missing ${e.placeholderTokenSecretRef}`);if(e.provider==="whatsapp"){let i=aje(e.accountKey,e.linkId);if(e.agentTokenSecretRef!==i)throw Error("runtime bundle WhatsApp agent token ref does not match its Link")}let r={account:{id:e.provider==="whatsapp"?e.accountId:e.accountKey,provider:e.provider},accountKey:e.accountKey,linkId:e.provider==="whatsapp"?e.linkId:e.accountKey,secretRef:e.agentTokenSecretRef,placeholderSecretRef:e.provider==="whatsapp"?null:e.placeholderTokenSecretRef,credential:e.provider==="whatsapp"?WTe(e,t):void 0,whatsappMaterial:null};return e.provider==="whatsapp"?{...r,whatsappMaterial:cje(r)}:r}function WTe(e,t){let n=e.credential.credsSecretRef,r=lje(e.accountKey,e.credential.id);if(n!==r)throw Error("runtime bundle WhatsApp credential ref does not match its credential");let i=It(t,n);if(!i)throw Error(`runtime bundle is missing ${n}`);let o;try{o=JSON.parse(i)}catch(a){throw Error(`runtime bundle WhatsApp credential is invalid: ${a instanceof Error?a.message:String(a)}`)}let s=W(o);if(!s)throw Error("runtime bundle WhatsApp credential must be a JSON object");return{id:e.credential.id,credsSecretRef:n,material:{schemaVersion:"clawdi.whatsappBaileysAuthState.v1",creds:s,authCert:e.credential.authCert}}}function GTe(e,t,n){let r=rje(t,e.controlPlane.apiUrl),i=cl(e,n),o=dje(e),s=ZTe(t,i,o),a={...e,projection:{...e.projection??{},channels:KTe(t,i,o),channelCredentials:s},egressProfiles:ije(e.egressProfiles,r)};return YTe(JTe(a,t),t)}function KTe(e,t,n){let r={};for(let i of e){let o=i.account.provider;if(o==="telegram"){let s=m1(r,"telegram",i.accountKey);s.accounts[i.accountKey]={enabled:!0,botToken:_J(i),dmPolicy:"open",groupPolicy:"open",allowFrom:["*"],capabilities:{inlineButtons:"all"},groups:{"*":{requireMention:!1}}};continue}if(o==="discord"){let s=m1(r,"discord",i.accountKey);s.accounts[i.accountKey]={enabled:!0,token:_J(i),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(o==="whatsapp"){let s=m1(r,"whatsapp",i.accountKey),a=EJ(i,t,n);s.accounts[i.accountKey]={enabled:!0,...a?.targets.openclaw?{authDir:a.targets.openclaw.authDir}:{},dmPolicy:"allowlist",allowFrom:["*"],groupPolicy:"open",groupAllowFrom:["*"],groups:{"*":{requireMention:!1}}}}}return r}function ZTe(e,t,n){return e.map((r)=>EJ(r,t,n)).filter((r)=>r!==null).sort((r,i)=>`${r.provider}:${r.accountKey}:${r.credentialId}`.localeCompare(`${i.provider}:${i.accountKey}:${i.credentialId}`))}function JTe(e,t){let n=e.runtimes.openclaw;if(!n?.enabled)return e;XTe(t);let r=n.run??{env:{},prependPath:[]},i=eje(r.secretEnv??{});for(let o of t){if(o.account.provider==="whatsapp")continue;i[PJ(o)]=ry(o)}if(!n.run&&Object.keys(i).length===0)return e;return{...e,runtimes:{...e.runtimes,openclaw:{...n,run:{...r,secretEnv:i}}}}}function YTe(e,t){let n=e.runtimes.hermes;if(!n?.enabled)return e;let r=ny(t,"telegram"),i=ny(t,"discord"),o=ny(t,"whatsapp"),s=n.run??{env:{},prependPath:[]},a=SJ(s.env??{},BTe),l=SJ(s.secretEnv??{},VTe);if(r)a.TELEGRAM_ALLOW_ALL_USERS="true",a.HERMES_TELEGRAM_DISABLE_FALLBACK_IPS="true",l.TELEGRAM_BOT_TOKEN=ry(r);if(i)a.DISCORD_ALLOW_ALL_USERS="true",l.DISCORD_BOT_TOKEN=ry(i);if(o)a.WHATSAPP_MODE="bot",a.WHATSAPP_ALLOWED_USERS="*",a.WHATSAPP_DM_POLICY="open",a.WHATSAPP_GROUP_POLICY="open";return{...e,runtimes:{...e.runtimes,hermes:{...n,run:{...s,env:a,secretEnv:l}}}}}function ny(e,t){let n=e.filter((r)=>r.account.provider===t);if(n.length>1)throw Error(QTe(t));return n[0]??null}function XTe(e){for(let t of["telegram","discord","whatsapp"])ny(e,t)}function QTe(e){return`This Agent has multiple active ${e==="telegram"?"Telegram":e==="discord"?"Discord":e} bots. Unlink the extras until only one remains.`}function _J(e){return{source:"env",provider:"default",id:PJ(e)}}function ry(e){if(!e.placeholderSecretRef)throw Error("managed channel placeholder secret ref is missing");return e.placeholderSecretRef}function PJ(e){return`${kJ}${bJ(e.account.provider)}_${bJ(e.accountKey)}${RJ}`}function bJ(e){return e.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"CHANNEL"}function eje(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!tje(t)))}function tje(e){return e.startsWith(kJ)&&e.endsWith(RJ)}function SJ(e,t){let n=new Set(t),r={};for(let[i,o]of Object.entries(e))if(!n.has(i))r[i]=o;return r}function m1(e,t,n){let r=e[t];if(nje(r))return r;let i={enabled:!0,defaultAccount:n,accounts:{}};return e[t]=i,i}function nje(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)&&typeof e.accounts==="object"&&e.accounts!==null&&!Array.isArray(e.accounts)}function rje(e,t){let n=pje(t),r=[];for(let o of e){let s=`${o.account.provider}-${o.accountKey}`;if(o.account.provider==="telegram")for(let a of[{id:`native-${s}-managed`,pathPrefix:"/bot"},{id:`native-${s}-file-managed`,pathPrefix:"/file/bot"}])r.push({id:a.id,enabled:!0,kind:"http",match:{scheme:"https",host:"api.telegram.org",pathPrefix:a.pathPrefix,path:{type:"secretRefPrefix",secretRef:ry(o),prefix:a.pathPrefix,suffix:"/"},headers:{},query:{}},rewrite:{upstreamBaseUrl:`${n}/v1/channels/telegram`,preservePath:!0,setHeaders:{authorization:{type:"secretRef",secretRef:o.secretRef,prefix:"Bearer "}}},logging:{redactHeaders:["authorization"],redactUrlPatterns:[]},priority:100,owner:"clawdi-native-channels"});if(o.account.provider==="discord")r.push({id:`native-${s}-rest-managed`,enabled:!0,kind:"http",match:{scheme:"https",host:"discord.com",pathPrefix:"/api/",headers:{authorization:{type:"secretRefEquals",secretRef:ry(o),prefix:"Bot "}},query:{}},rewrite:{upstreamBaseUrl:`${n}/v1/channels/discord`,preservePath:!0,setHeaders:{authorization:{type:"secretRef",secretRef:o.secretRef,prefix:"Bot "}}},logging:{redactHeaders:["authorization"],redactUrlPatterns:[]},priority:101,owner:"clawdi-native-channels"}),r.push({id:`native-${s}-gateway-managed`,enabled:!0,kind:"websocket",match:{scheme:"wss",host:"gateway.discord.gg",pathPrefix:"/",headers:{},query:{}},rewrite:{upstreamBaseUrl:`${u1(n)}/v1/channels/discord/gateway`,preservePath:!1,setHeaders:{authorization:{type:"secretRef",secretRef:o.secretRef,prefix:"Bearer "}}},logging:{redactHeaders:["authorization"],redactUrlPatterns:[]},priority:201,owner:"clawdi-native-channels"})}let i=ny(e,"whatsapp");if(i&&!i.whatsappMaterial)throw Error(`managed WhatsApp Link ${i.linkId} has no valid synthetic auth`);if(i)r.push({id:"native-whatsapp-baileys-managed",enabled:!0,kind:"websocket",match:{scheme:"wss",host:"web.whatsapp.com",path:{type:"equals",value:"/ws/chat"},headers:{},query:{}},rewrite:{upstreamBaseUrl:u1(new URL("/v1/channels/whatsapp/baileys",n).toString()),preservePath:!1,setHeaders:{authorization:{type:"secretRef",secretRef:i.secretRef,prefix:"Bearer "}}},logging:{redactHeaders:["authorization"],redactUrlPatterns:[]},priority:40,owner:"clawdi-native-channels"});return r}function ije(e,t){let n=[...e?.profiles??[]],r=new Set(t.map((i)=>i.id));return{profiles:[...n.filter((i)=>!r.has(i.id)&&!oje(i)),...t]}}function oje(e){return e.owner==="clawdi-native-channels"||e.owner==="clawdi-native-whatsapp"}function sje(e,t){let n={},r=new Set(Mp(t).map((i)=>i.credsJsonSecretRef));for(let i of e){let o=i.whatsappMaterial;if(o){let s=o.credential.credsSecretRef;if(r.has(s))n[s]=JSON.stringify(uje(o))}}return n}function aje(e,t){return`secret://channels/whatsapp/${e}/links/${t}/agent-token`}function lje(e,t){return`secret://channels/whatsapp/${e}/credentials/${t}/creds-json`}function EJ(e,t,n){let r=e.whatsappMaterial;if(!r)return null;let i={};if(n.openclaw)i.openclaw={authDir:zc(t,"openclaw",e.accountKey)};if(n.hermes)i.hermes={authDir:zc(t,"hermes",e.accountKey)};if(!i.openclaw&&!i.hermes)return null;return{provider:"whatsapp",kind:"whatsapp_baileys_auth_state",accountId:e.account.id,accountKey:e.accountKey,linkId:e.linkId,credentialId:r.credential.id,files:[{path:"creds.json",secretRef:r.credential.credsSecretRef}],targets:i}}function cje(e){if(e.account.provider!=="whatsapp")return null;let t=e.credential;if(!t)return null;let{material:n}=t,r;try{r=Lp({schemaVersion:ty,authCert:n.authCert})}catch{return null}return{credential:t,creds:n.creds,authCert:r.authCert}}function uje(e){let t=e.creds.additionalData,n=t===void 0?{}:W(t);if(!n)throw Error("managed WhatsApp synthetic creds.additionalData must be an object");let r=Lp({schemaVersion:ty,authCert:e.authCert});return{...e.creds,additionalData:{...n,[Fc]:r,[Hc]:{schemaVersion:cR,credentialId:e.credential.id}}}}function dje(e){return{openclaw:e.runtimes.openclaw?.enabled===!0,hermes:e.runtimes.hermes?.enabled===!0}}function pje(e){return e.replace(/\/+$/,"")}var BTe,VTe,kJ="CLAWDI_CHANNEL_",RJ="_AGENT_TOKEN";var f1=_(()=>{Si();Lt();Yr();ey();p1();BTe=["TELEGRAM_ALLOW_ALL_USERS","DISCORD_ALLOW_ALL_USERS","HERMES_TELEGRAM_DISABLE_FALLBACK_IPS","WHATSAPP_ENABLED","WHATSAPP_MODE","WHATSAPP_ALLOWED_USERS","WHATSAPP_DM_POLICY","WHATSAPP_GROUP_POLICY"],VTe=["TELEGRAM_BOT_TOKEN","DISCORD_BOT_TOKEN"]});import{existsSync as xJ,readFileSync as mje}from"node:fs";function $J(e){return JSON.parse(mje(e,"utf-8"))}function _je(e){return e.issues.map((t)=>`${t.path.length>0?`${t.path.join(".")}: `:""}${t.message}`)}function CJ(e,t){let n=Us.parse(e);return{manifest:n.manifest,sourceBundle:n.sourceBundle,source:"remote-datasource",sourcePath:t,offline:!1,secretValues:Yo(n.secretValues),channelBindings:n.channelBindings,sourceRevision:n.sourceRevision}}function bje(e){let t=Up(Up(e)?.manifest)?.generation;return typeof t==="number"&&Number.isInteger(t)?t:null}async function Sje(e,t={}){let n=e.manifestSource.url,r=e.manifestSource.auth.token,i=15000,o=new AbortController,s=setTimeout(()=>o.abort(),15000);try{let a=await fetch(n,{method:"GET",headers:{accept:g1,authorization:`Bearer ${r}`,[fje]:[gje,hje].join(", "),...t.ifNoneMatch?{"if-none-match":t.ifNoneMatch}:{}},signal:o.signal}),l=a.headers.get("etag")??void 0;if(a.status===304)return{url:n,notModified:!0,etag:l};if(!a.ok){let u=await a.text().catch(()=>"");if(a.status===401||a.status===403)throw new h1(a.status,u);throw Error(`runtime manifest request failed: HTTP ${a.status}${u?` ${u.slice(0,200)}`:""}`)}let c=a.headers.get("content-type")?.split(";",1)[0]?.trim();if(c!==g1)throw new dR(`runtime manifest response content-type must be ${g1}, received ${c??"missing"}`,l);if(!l)throw Error("runtime bundle response is missing its strong ETag");try{return{url:n,raw:await a.json(),etag:l}}catch(u){throw new dR(`runtime manifest response is not valid JSON: ${U(u)}`,l)}}finally{clearTimeout(s)}}async function pR(e,t={}){let n;try{n=t.applyContext??es()}catch(s){return IJ(s)}let r;try{r=await Sje(n,t)}catch(s){return{mode:"repair",stage:Rje(s),errors:[`could not fetch runtime manifest: ${U(s)}`],...s instanceof dR&&s.etag?{etag:s.etag}:{}}}if("notModified"in r)return{source:"remote-datasource",sourcePath:r.url,notModified:!0,etag:r.etag??t.ifNoneMatch,applyContext:n};let i;try{i=CJ(r.raw,r.url),y1(i.sourceRevision,r.etag),kje(i.manifest,n)}catch(s){return{mode:"manifest-rejected",stage:"network",errors:s instanceof y.ZodError?_je(s):[U(s)],etag:r.etag,rejectedGeneration:bje(r.raw),activeGeneration:OJ(e).generation??null}}let o=Aje(i,e);if(!("manifest"in o))return{...o,etag:r.etag};return{...o,etag:r.etag,applyContext:n}}function IJ(e){return{mode:"repair",stage:"local",errors:[U(e)]}}function kje(e,t){if(t.identity&&t.identity.generation!==Jt(e))throw Error(`runtime apply identity generation ${t.identity.generation} does not match resolved manifest apply generation ${Jt(e)}`)}function y1(e,t){if(!e)return;let n=`"sha256:${e}"`;if(t!==n)throw Error(`runtime bundle ETag ${t??"missing"} does not match its sourceRevision validator ${n}`)}function Rje(e){return e instanceof h1?"auth":"network"}function OJ(e){let t=$n(e);if(!t)return{};return{instanceId:t.instanceId,generation:t.generation}}async function v1(e,t={}){let n;try{n=t.applyContext??es()}catch(o){return IJ(o)}let r=await pR(e,{applyContext:n});if("errors"in r&&r.mode==="repair"&&(r.stage==="network"||r.stage==="auth")||"notModified"in r){let o=TJ(e,!0,n);if("manifest"in o)return o;return{mode:"repair",stage:"network",errors:[..."errors"in r?r.errors:["could not fetch runtime manifest: runtime manifest datasource returned 304 without If-None-Match"],...o.errors]}}return r}function TJ(e,t,n){if(!xJ(e.manifestLastGood))return{mode:"repair",stage:"local",errors:["last-good runtime manifest does not exist"]};try{let r=$J(e.manifestLastGood),i=Up(r);if(!i)throw Error("cached runtime bundle must be an object");let o=Pje(e);if("errors"in o)return o;let s=CJ({...i,secretValues:o.secretValues},e.manifestLastGood),a=$n(e),l=uR({...s,source:"last-good-cache",sourcePath:e.manifestLastGood,offline:!0,applyContext:n},e),c=l.manifest;if(t&&c.recovery.allowOfflineBoot!==!0)return{mode:"repair",stage:"local",errors:["cached manifest does not allow offline boot"]};let u=a?Ls(a):null;if(t&&!Qo(n.identity,u))return{mode:"repair",stage:"local",errors:["cached strict-v2 apply identity does not match the current runtime apply identity; refusing offline boot"],activeGeneration:a?.generation??null};if(mR(c).length>0){let p=Eje(c,o.secretValues);if(p.length>0)return{mode:"repair",stage:"local",errors:[`cached manifest references secretValues (${p.join(", ")}); refusing offline boot because cached secret values are missing`]}}if(!a)return{mode:"repair",stage:"local",errors:["cached manifest has no durable applied authority; refusing offline boot"]};if(a.generation!==c.generation||Jt(a)!==Jt(c)||a.instanceId!==c.instanceId||a.contentIdentity.sha256!==bi({manifest:r,secretValues:o.secretValues}))return{mode:"repair",stage:"local",errors:["cached manifest does not match the durable strict-v2 apply identity; refusing offline boot"],activeGeneration:a?.generation??null};return{...l,manifest:c}}catch(r){return{mode:"repair",stage:"local",errors:[`could not read last-good runtime manifest at ${e.manifestLastGood}: ${U(r)}`]}}}function w1(e,t){return TJ(e,!1,t)}function Pje(e){if(!xJ(e.managedSecretCacheFile))return{secretValues:{}};try{let t=$J(e.managedSecretCacheFile);if(!t||typeof t!=="object"||Array.isArray(t))throw Error("cached secret values must be a JSON object");let n={};for(let[r,i]of Object.entries(t)){if(typeof i!=="string")throw Error(`cached secret value for ${r} must be a string`);n[r]=i}return{secretValues:Yo(n)}}catch(t){return{mode:"repair",stage:"local",errors:[`could not read cached runtime secret values at ${e.managedSecretCacheFile}: ${U(t)}`]}}}function mR(e){let t=new Set,n=Up(e.projection?.providers),r=!1;for(let[i,o]of Object.entries(e.runtimes)){if(!o.enabled)continue;r=!0,AJ(o.run?.secretEnv,t);for(let s of Object.values(o.services??{}))AJ(s.secretEnv,t);if(i==="openclaw"&&e.openclawGatewayAuth)t.add(e.openclawGatewayAuth.tokenRef);if(i==="hermes"&&o.services?.dashboard&&e.hermesDashboardAuth)t.add(e.hermesDashboardAuth.passwordSecretRef),t.add(e.hermesDashboardAuth.sessionSecretRef);for(let s of o.provider_ids??[]){let a=Up(n?.[s]);if(!a||xp(a))continue;if(typeof a.apiKeySecretRef==="string")t.add(a.apiKeySecretRef);let l=Up(a.auth);if(typeof l?.credentialSecretRef==="string")t.add(l.credentialSecretRef)}}if(r){for(let i of Yk(e.egressProfiles))t.add(i);for(let i of Mp(e.projection?.channelCredentials))t.add(i.credsJsonSecretRef)}return[...t].sort()}function Eje(e,t){let n=Yo(t??{});return mR(e).filter((r)=>It(n,r)===null)}function AJ(e,t){for(let n of Object.values(e??{}))t.add(n)}function Up(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:null}function Aje(e,t){let n=OJ(t),r=e.manifest,i=[];if(n.instanceId&&n.instanceId!==r.instanceId)i.push(`manifest instanceId ${r.instanceId} does not match applied instanceId ${n.instanceId}`);if(n.instanceId===r.instanceId&&n.generation!==void 0&&r.generation<n.generation)i.push(`manifest generation ${r.generation} is older than applied generation ${n.generation}`);if(i.length>0)return{mode:"manifest-rejected",stage:e.source==="remote-datasource"?"network":"local",errors:i,rejectedGeneration:r.generation,activeGeneration:n.generation??null};return e}var g1="application/vnd.clawdi.runtime-bundle.v2+json",fje="x-clawdi-runtime-capabilities",gje="agent-plugins-manifest-v1",hje="agent-plugin-github-release-source-v1",yje,vje,wje,Us,h1,dR;var ul=_(()=>{sn();Zt();eo();Ms();f1();Ap();$p();Xh();Yr();ey();yje=y.object({provider:y.enum(["telegram","discord"]),accountKey:y.string().min(1),agentTokenSecretRef:lr,placeholderTokenSecretRef:lr}).strict(),vje=y.object({provider:y.literal("whatsapp"),accountId:y.string().uuid(),accountKey:y.string().min(1),linkId:y.string().uuid(),agentTokenSecretRef:lr,placeholderTokenSecretRef:lr.optional(),credential:y.object({id:y.string().uuid(),credsSecretRef:lr,authCert:y.object({SERIAL:y.number().int().nonnegative().safe(),ISSUER:y.string().trim().min(1).max(256),PUBLIC_KEY:y.object({type:y.literal("Buffer"),data:y.string().min(1)}).strict()}).strict()}).strict()}).strict(),wje=y.discriminatedUnion("provider",[yje,vje]),Us=y.object({schemaVersion:y.literal(oJ),sourceRevision:y.string().regex(/^[a-f0-9]{64}$/),manifest:y.unknown(),applyGeneration:y.number().int().positive().safe().optional(),channelBindings:y.array(wje),secretValues:y.record(lr,y.string())}).strict().transform((e,t)=>{let n=uJ.safeParse(e.manifest);if(!n.success){for(let r of n.error.issues)t.addIssue({...r,path:["manifest",...r.path]});return y.NEVER}return{...e,sourceBundle:{...e,secretValues:{}},manifest:{...n.data,...e.applyGeneration===void 0?{}:{applyGeneration:e.applyGeneration}}}}).superRefine(pJ);h1=class h1 extends Error{status;constructor(e,t){super(`runtime manifest authentication failed: HTTP ${e}${t?` ${t.slice(0,200)}`:""}`);this.status=e}};dR=class dR extends Error{etag;constructor(e,t){super(e);this.etag=t}}});import{dirname as jJ,isAbsolute as DJ,relative as xje,resolve as _1}from"node:path";function Ije(){return process.env.CLAWDI_RUNTIME_MODE?.trim().toLowerCase()||"missing"}function k1(e,t={}){let n=t.expectedIdentity??NJ,r=Ije(),i=r==="hosted"&&e.mode==="hosted"?void 0:`hosted convergence requires CLAWDI_RUNTIME_MODE=hosted explicitly; resolved runtime mode is ${e.mode} (environment: ${r})`,o=e.userHome===n.home?void 0:`hosted runtime HOME must resolve to ${n.home}; resolved ${e.userHome}`,s=process.env.CLAWDI_RUNTIME_USER?.trim()??"",a,l=s||"missing";if(s!==n.user)a=s?`hosted runtime user must be ${n.user}; resolved ${s}`:`hosted runtime user must be ${n.user}; CLAWDI_RUNTIME_USER is missing`;else try{let c=(t.resolveUserIdentity??OV)(s);if(l=`${s} (${c.uid}:${c.gid})`,c.uid===0||c.gid===0)a=`hosted runtime user ${s} resolved to root identity ${c.uid}:${c.gid}`;else if(c.uid!==n.uid||c.gid!==n.gid)a=`hosted runtime user ${s} must resolve to ${n.uid}:${n.gid}; resolved ${c.uid}:${c.gid}`;else for(let[u,d,p]of[["CLAWDI_RUNTIME_UID",process.env.CLAWDI_RUNTIME_UID?.trim(),c.uid],["CLAWDI_RUNTIME_GID",process.env.CLAWDI_RUNTIME_GID?.trim(),c.gid]])if(d&&d!==String(p)){a=`${u} must match the resolved hosted runtime identity ${p}; resolved ${d}`;break}}catch(c){a=c instanceof Error?c.message:String(c)}return{mode:{ok:i===void 0,detail:e.mode,...i?{error:i}:{}},home:{ok:o===void 0,detail:e.userHome,...o?{error:o}:{}},user:{ok:a===void 0,detail:l,...a?{error:a}:{}}}}function iy(e,t,n={}){let r=k1(e,n),i=[r.mode,r.home,r.user].find((l)=>!l.ok)?.error;if(i)throw Error(i);let o=_1(e.clawdiHome),s=_1(e.serviceStateRoot),a=xje(_1(e.userHome),o);if(a===""||!a.startsWith("..")&&!DJ(a))throw Error(`hosted CLAWDI_HOME must be outside the tenant home; resolved ${e.clawdiHome}`);if(!DJ(e.clawdiHome)||o===s||jJ(o)!==jJ(s))throw Error(`hosted CLAWDI_HOME must be an absolute sibling of ${e.serviceStateRoot}; resolved ${e.clawdiHome}`);if(t.backend!=="incus")throw Error(`hosted v2 convergence requires runtime context backend incus; resolved ${String(t.backend??"missing")}`);if(n.platformRoots!=="deferred")cg(e);return{identity:n.expectedIdentity??NJ}}var b1="/home/clawdi",S1="clawdi",$je=10001,Cje=10001,NJ;var oy=_(()=>{gt();Un();NJ={home:b1,user:S1,uid:$je,gid:Cje}});import{spawnSync as R1}from"node:child_process";import{accessSync as Oje,constants as Tje,existsSync as UJ,lstatSync as jje,mkdirSync as Dje,mkdtempSync as Nje,readdirSync as Mje,readFileSync as Lje,readlinkSync as zJ,renameSync as Uje,rmSync as zp,statSync as zje,symlinkSync as Fje}from"node:fs";import{tmpdir as Hje}from"node:os";import{dirname as zs,join as dl,resolve as hR}from"node:path";function FJ(e){if(e.mode!=="hosted"||e.userHome!==b1||process.env.CLAWDI_RUNTIME_USER?.trim()!==S1||typeof process.geteuid==="function"&&process.geteuid()!==0)return;let t;try{t=jje(sy)}catch(r){if(r.code==="ENOENT")return;throw r}if(!t.isSymbolicLink())throw Error(`hosted tenant PATH contains an unmanaged clawdi entrypoint: ${sy}`);let n=hR(zs(sy),zJ(sy));if(n!==Zje)throw Error(`hosted tenant PATH contains an unmanaged clawdi symlink target: ${n}`);zp(sy)}function HJ(e,t,n={}){let r=ly(t,n.runningVersion),i=e.clawdiCli?.packageSpec?.trim()||null;if(r.selfReexec)return MJ("deferred",t,Fp(t),i,"CLI recovery changed the active version; re-exec is required",!0);if(!i)return ay("not_requested",t,Qje());let o=bR(i);if(!o)throw Error(`clawdi CLI packageSpec must be clawdi@<exact-semver>: ${i}`);tDe(e.clawdiCli?.registry);let s=cy(t),a=A1(t,s),l=a?.bad??null;if(a?.version===o&&Hp(t.cliManagedBin)===a.activeTarget)return MJ("current",t,a,i);if(l?.version===o&&iDe(l))return ay("deferred",t,{packageSpec:i,registry:pl,npmPrefix:a?.npmPrefix??t.cliNpmPrefix,activeTarget:a?.activeTarget??null,version:a?.version??null,retryAt:l.retryAt,error:`clawdi CLI ${o} retry is deferred until ${l.retryAt}`});let c;try{c=nDe(t,i)}catch(d){let p=U(d),m=x1(l,o,p);if(a)Vc(t,yR(a),a.previous,m);return Bp(t,a?[a.npmPrefix,LJ(a.previous)]:[]),ay("error",t,{packageSpec:i,registry:pl,npmPrefix:a?.npmPrefix??t.cliNpmPrefix,activeTarget:a?.activeTarget??Hp(t.cliManagedBin),version:a?.version??null,retryAt:m.retryAt,error:p})}a=Fp(t);let u=a?.previous??(a?eDe(a):null);wR(t.cliManagedBin,c.activeTarget);try{Vc(t,c,u,a?.bad?.version===c.version?a.bad:null)}catch(d){if(a)wR(t.cliManagedBin,a.activeTarget);else zp(t.cliManagedBin,{force:!0});throw d}return Bp(t,[ml(c.activeTarget),LJ(u)]),ay("installed",t,{packageSpec:i,registry:pl,npmPrefix:ml(c.activeTarget),activeTarget:c.activeTarget,version:c.version},!0)}function BJ(e,t){let n=Fp(e);try{if(ly(e).status==="rolled_back"&&n?.previous)return fR(n,"rolled_back");let i=Fp(e);if(!i?.previous)return fR(i,"not_pending");return VJ(e,i,t),fR(i,"rolled_back")}catch(r){return fR(n,"error",U(r))}}function E1(e,t){let n=ly(e,t);if(n.selfReexec)return n;let r=Fp(e);if(r?.previous&&r.version===t&&Hp(e.cliManagedBin)===r.activeTarget)Vc(e,yR(r),null,r.bad?.version===r.version?null:r.bad),Bp(e,[r.npmPrefix]);return n}function ly(e,t){let n=cy(e),r=A1(e,n),i=Hp(e.cliManagedBin);if(!r){if(!i)return{status:"unchanged",selfReexec:!1};let s=vR(e,{activeTarget:i});return Vc(e,s,null,null),Bp(e,[ml(s.activeTarget)]),gR("unchanged",s.version,t)}if(i!==r.activeTarget){let s=r.previous??yR(r),a=vR(e,s);if(i!==a.activeTarget)wR(e.cliManagedBin,a.activeTarget);let l=r.previous?x1(r.bad,r.version,"recovered interrupted or inconsistent clawdi CLI activation"):r.bad;return Vc(e,a,null,l),Bp(e,[ml(a.activeTarget)]),gR("rolled_back",a.version,t)}let o=qJ(e,yR(r),r);if(!o){if(!r.previous)throw Error("active clawdi CLI is not verifiable and has no rollback target");return VJ(e,r,"active clawdi CLI failed recovery verification"),r=Fp(e),gR("rolled_back",r?.version,t)}if(!SR(r.verification,o.verification)||r.verification.verifiedAt!==o.verification.verifiedAt)Vc(e,o,r.previous,r.bad);return gR("unchanged",o.version,t,r.previous!==null)}function cy(e){if(!UJ(e.cliBootstrapStatus))return null;try{return P1.parse(JSON.parse(Lje(e.cliBootstrapStatus,"utf-8")))}catch(t){return C.warn("runtime.cli_bootstrap_status_invalid",{path:e.cliBootstrapStatus,error:U(t)}),null}}function ay(e,t,n,r=!1){return{status:e,...n,npmPrefix:n.npmPrefix??t.cliNpmPrefix,npmCache:n.npmCache??t.cliNpmCache,activePath:t.cliManagedBin,retryAt:n.retryAt??null,selfReexec:r}}function Qje(){return{packageSpec:null,registry:null,activeTarget:null,version:null}}function MJ(e,t,n,r,i,o=!1){return ay(e,t,{packageSpec:r,registry:r?pl:null,npmPrefix:n?.npmPrefix??t.cliNpmPrefix,activeTarget:n?.activeTarget??Hp(t.cliManagedBin),version:n?.version??null,retryAt:n?.bad?.version===bR(r??"")?n.bad.retryAt:null,error:i},o)}function A1(e,t){let n=P1.safeParse(t);if(!n.success)return null;let r=n.data;if(r.activePath!==e.cliManagedBin||r.npmCache!==e.cliNpmCache||r.npmPrefix!==ml(r.activeTarget)||!WJ(e,r.activeTarget)||bR(r.packageSpec)!==r.version||!rDe(r.bad))return C.warn("runtime.cli_state_invalid",{path:e.cliBootstrapStatus}),null;return r}function Fp(e){return A1(e,cy(e))}function Vc(e,t,n,r){let i=$1(t.activeTarget);if(!i||!SR(t.verification,i))throw Error(`clawdi CLI target changed after verification: ${t.activeTarget}`);let o=P1.parse({schemaVersion:"clawdi.cliNpmBootstrapStatus.v1",generatedAt:new Date().toISOString(),status:"installed",source:"npm",packageSpec:`clawdi@${t.version}`,registry:pl,npmPrefix:ml(t.activeTarget),npmCache:e.cliNpmCache,activePath:e.cliManagedBin,activeTarget:t.activeTarget,version:t.version,verification:t.verification,previous:n,bad:r,error:null});Ut(e,e.cliBootstrapStatus,`${JSON.stringify(o,null,2)}
|
|
264
|
+
`;if(n)ll(n,e,r);else me(e,r)}function W(e){if(!e||typeof e!=="object"||Array.isArray(e))return null;return e}function Qh(e,t){return Object.keys(e).sort().join("\x00")===[...t].sort().join("\x00")}function u1(e){let t=new URL(e);if(t.protocol==="https:")t.protocol="wss:";else if(t.protocol==="http:")t.protocol="ws:";else throw Error("URL must use HTTP or HTTPS");if(t.pathname==="/"&&!t.search&&!t.hash)return t.origin;return t.toString()}function dt(e){return typeof e==="string"?e:null}function Dp(e,t){return JSON.stringify(lR(e))===JSON.stringify(lR(t))}function lR(e){if(Array.isArray(e))return e.map(lR);if(!Ye(e))return e;return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,lR(n)]))}function Ye(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var Si=_(()=>{At();Un()});function cl(e,t){return t.userHome}import{resolve as wJ}from"node:path";function zc(e,t,n){return t==="hermes"?wJ(e,".hermes","platforms","whatsapp","session"):wJ(e,".openclaw","credentials","whatsapp",n)}function Mp(e){if(!Array.isArray(e))return[];return e.flatMap(FTe).sort((t,n)=>`${t.target}:${t.accountKey}:${t.credentialId}`.localeCompare(`${n.target}:${n.accountKey}:${n.credentialId}`))}function FTe(e){let t=W(e);if(!t)return[];if(t.provider!=="whatsapp"||t.kind!=="whatsapp_baileys_auth_state")return[];let n=Np(t.accountKey),r=Np(t.linkId),i=Np(t.credentialId),s=(Array.isArray(t.files)?t.files:[]).map(W).find((f)=>f?.path==="creds.json"&&typeof f.secretRef==="string"),a=s?Np(s.secretRef):null;if(!n||!i||!a)throw Error("WhatsApp auth credential projection is incomplete");let l=W(t.targets);if(!l)throw Error("WhatsApp auth credential projection is incomplete");let c=[],u=W(l.openclaw),d=Np(u?.authDir);if(d)c.push({accountKey:n,linkId:r,credentialId:i,authDir:d,credsJsonSecretRef:a,target:"openclaw"});let p=W(l.hermes),m=p?Np(p.authDir):null;if(m)c.push({accountKey:n,linkId:r,credentialId:i,authDir:m,credsJsonSecretRef:a,target:"hermes"});if(c.length===0)throw Error("WhatsApp auth credential projection is incomplete");return c}function Np(e){return typeof e==="string"&&e.trim()?e.trim():null}var ey=_(()=>{Si()});function Lp(e){let t=W(e),n=W(t?.authCert),r=W(n?.PUBLIC_KEY),i=n?.ISSUER,o=n?.SERIAL,s=r?.data;if(!t||!Qh(t,["authCert","schemaVersion"])||t.schemaVersion!==ty||!n||!Qh(n,["ISSUER","PUBLIC_KEY","SERIAL"])||typeof o!=="number"||!Number.isSafeInteger(o)||o<0||typeof i!=="string"||i.length===0||i.trim()!==i||i.length>256||!r||!Qh(r,["data","type"])||r.type!=="Buffer"||typeof s!=="string"||!HTe(s,32))throw Error("invalid Clawdi managed WhatsApp socket metadata");return{schemaVersion:ty,authCert:{SERIAL:o,ISSUER:i,PUBLIC_KEY:{type:"Buffer",data:s}}}}function d1(e){let t=W(e);if(!t||!Qh(t,["credentialId","schemaVersion"])||t.schemaVersion!==cR||typeof t.credentialId!=="string"||t.credentialId.length===0||t.credentialId.trim()!==t.credentialId)throw Error("invalid Clawdi managed WhatsApp credential metadata");return{schemaVersion:cR,credentialId:t.credentialId}}function HTe(e,t){let n=Buffer.from(e,"base64");return n.length===t&&n.toString("base64")===e}var Fc="clawdi.managedWhatsAppSocket",ty="clawdi.managedWhatsAppSocket.v1",Hc="clawdi.managedWhatsAppCredential",cR="clawdi.managedWhatsAppCredential.v1";var p1=_(()=>{Si()});function uR(e,t=de({mode:"hosted"})){if(!e.channelBindings)return e;let{channelBindings:n,...r}=e,i={...e.secretValues??{}};for(let l of n)if(l.provider==="whatsapp"&&l.placeholderTokenSecretRef)delete i[l.placeholderTokenSecretRef];let o=n.map((l)=>qTe(l,i)),s=GTe(e.manifest,o,t),a=sje(o.filter((l)=>l.account.provider==="whatsapp"),s.projection?.channelCredentials);return{...r,manifest:s,secretValues:{...i,...a}}}function qTe(e,t){if(!It(t,e.agentTokenSecretRef))throw Error(`runtime bundle is missing ${e.agentTokenSecretRef}`);if(e.provider!=="whatsapp"&&!It(t,e.placeholderTokenSecretRef))throw Error(`runtime bundle is missing ${e.placeholderTokenSecretRef}`);if(e.provider==="whatsapp"){let i=aje(e.accountKey,e.linkId);if(e.agentTokenSecretRef!==i)throw Error("runtime bundle WhatsApp agent token ref does not match its Link")}let r={account:{id:e.provider==="whatsapp"?e.accountId:e.accountKey,provider:e.provider},accountKey:e.accountKey,linkId:e.provider==="whatsapp"?e.linkId:e.accountKey,secretRef:e.agentTokenSecretRef,placeholderSecretRef:e.provider==="whatsapp"?null:e.placeholderTokenSecretRef,credential:e.provider==="whatsapp"?WTe(e,t):void 0,whatsappMaterial:null};return e.provider==="whatsapp"?{...r,whatsappMaterial:cje(r)}:r}function WTe(e,t){let n=e.credential.credsSecretRef,r=lje(e.accountKey,e.credential.id);if(n!==r)throw Error("runtime bundle WhatsApp credential ref does not match its credential");let i=It(t,n);if(!i)throw Error(`runtime bundle is missing ${n}`);let o;try{o=JSON.parse(i)}catch(a){throw Error(`runtime bundle WhatsApp credential is invalid: ${a instanceof Error?a.message:String(a)}`)}let s=W(o);if(!s)throw Error("runtime bundle WhatsApp credential must be a JSON object");return{id:e.credential.id,credsSecretRef:n,material:{schemaVersion:"clawdi.whatsappBaileysAuthState.v1",creds:s,authCert:e.credential.authCert}}}function GTe(e,t,n){let r=rje(t,e.controlPlane.apiUrl),i=cl(e,n),o=dje(e),s=ZTe(t,i,o),a={...e,projection:{...e.projection??{},channels:KTe(t,i,o),channelCredentials:s},egressProfiles:ije(e.egressProfiles,r)};return YTe(JTe(a,t),t)}function KTe(e,t,n){let r={};for(let i of e){let o=i.account.provider;if(o==="telegram"){let s=m1(r,"telegram",i.accountKey);s.accounts[i.accountKey]={enabled:!0,botToken:_J(i),dmPolicy:"open",groupPolicy:"open",allowFrom:["*"],capabilities:{inlineButtons:"all"},groups:{"*":{requireMention:!1}}};continue}if(o==="discord"){let s=m1(r,"discord",i.accountKey);s.accounts[i.accountKey]={enabled:!0,token:_J(i),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(o==="whatsapp"){let s=m1(r,"whatsapp",i.accountKey),a=EJ(i,t,n);s.accounts[i.accountKey]={enabled:!0,...a?.targets.openclaw?{authDir:a.targets.openclaw.authDir}:{},dmPolicy:"allowlist",allowFrom:["*"],groupPolicy:"open",groupAllowFrom:["*"],groups:{"*":{requireMention:!1}}}}}return r}function ZTe(e,t,n){return e.map((r)=>EJ(r,t,n)).filter((r)=>r!==null).sort((r,i)=>`${r.provider}:${r.accountKey}:${r.credentialId}`.localeCompare(`${i.provider}:${i.accountKey}:${i.credentialId}`))}function JTe(e,t){let n=e.runtimes.openclaw;if(!n?.enabled)return e;XTe(t);let r=n.run??{env:{},prependPath:[]},i=eje(r.secretEnv??{});for(let o of t){if(o.account.provider==="whatsapp")continue;i[PJ(o)]=ry(o)}if(!n.run&&Object.keys(i).length===0)return e;return{...e,runtimes:{...e.runtimes,openclaw:{...n,run:{...r,secretEnv:i}}}}}function YTe(e,t){let n=e.runtimes.hermes;if(!n?.enabled)return e;let r=ny(t,"telegram"),i=ny(t,"discord"),o=ny(t,"whatsapp"),s=n.run??{env:{},prependPath:[]},a=SJ(s.env??{},BTe),l=SJ(s.secretEnv??{},VTe);if(r)a.TELEGRAM_ALLOW_ALL_USERS="true",a.HERMES_TELEGRAM_DISABLE_FALLBACK_IPS="true",l.TELEGRAM_BOT_TOKEN=ry(r);if(i)a.DISCORD_ALLOW_ALL_USERS="true",l.DISCORD_BOT_TOKEN=ry(i);if(o)a.WHATSAPP_MODE="bot",a.WHATSAPP_ALLOWED_USERS="*",a.WHATSAPP_ALLOW_ALL_USERS="true",a.WHATSAPP_DM_POLICY="open",a.WHATSAPP_GROUP_POLICY="open";return{...e,runtimes:{...e.runtimes,hermes:{...n,run:{...s,env:a,secretEnv:l}}}}}function ny(e,t){let n=e.filter((r)=>r.account.provider===t);if(n.length>1)throw Error(QTe(t));return n[0]??null}function XTe(e){for(let t of["telegram","discord","whatsapp"])ny(e,t)}function QTe(e){return`This Agent has multiple active ${e==="telegram"?"Telegram":e==="discord"?"Discord":e} bots. Unlink the extras until only one remains.`}function _J(e){return{source:"env",provider:"default",id:PJ(e)}}function ry(e){if(!e.placeholderSecretRef)throw Error("managed channel placeholder secret ref is missing");return e.placeholderSecretRef}function PJ(e){return`${kJ}${bJ(e.account.provider)}_${bJ(e.accountKey)}${RJ}`}function bJ(e){return e.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"CHANNEL"}function eje(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!tje(t)))}function tje(e){return e.startsWith(kJ)&&e.endsWith(RJ)}function SJ(e,t){let n=new Set(t),r={};for(let[i,o]of Object.entries(e))if(!n.has(i))r[i]=o;return r}function m1(e,t,n){let r=e[t];if(nje(r))return r;let i={enabled:!0,defaultAccount:n,accounts:{}};return e[t]=i,i}function nje(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)&&typeof e.accounts==="object"&&e.accounts!==null&&!Array.isArray(e.accounts)}function rje(e,t){let n=pje(t),r=[];for(let o of e){let s=`${o.account.provider}-${o.accountKey}`;if(o.account.provider==="telegram")for(let a of[{id:`native-${s}-managed`,pathPrefix:"/bot"},{id:`native-${s}-file-managed`,pathPrefix:"/file/bot"}])r.push({id:a.id,enabled:!0,kind:"http",match:{scheme:"https",host:"api.telegram.org",pathPrefix:a.pathPrefix,path:{type:"secretRefPrefix",secretRef:ry(o),prefix:a.pathPrefix,suffix:"/"},headers:{},query:{}},rewrite:{upstreamBaseUrl:`${n}/v1/channels/telegram`,preservePath:!0,setHeaders:{authorization:{type:"secretRef",secretRef:o.secretRef,prefix:"Bearer "}}},logging:{redactHeaders:["authorization"],redactUrlPatterns:[]},priority:100,owner:"clawdi-native-channels"});if(o.account.provider==="discord")r.push({id:`native-${s}-rest-managed`,enabled:!0,kind:"http",match:{scheme:"https",host:"discord.com",pathPrefix:"/api/",headers:{authorization:{type:"secretRefEquals",secretRef:ry(o),prefix:"Bot "}},query:{}},rewrite:{upstreamBaseUrl:`${n}/v1/channels/discord`,preservePath:!0,setHeaders:{authorization:{type:"secretRef",secretRef:o.secretRef,prefix:"Bot "}}},logging:{redactHeaders:["authorization"],redactUrlPatterns:[]},priority:101,owner:"clawdi-native-channels"}),r.push({id:`native-${s}-gateway-managed`,enabled:!0,kind:"websocket",match:{scheme:"wss",host:"gateway.discord.gg",pathPrefix:"/",headers:{},query:{}},rewrite:{upstreamBaseUrl:`${u1(n)}/v1/channels/discord/gateway`,preservePath:!1,setHeaders:{authorization:{type:"secretRef",secretRef:o.secretRef,prefix:"Bearer "}}},logging:{redactHeaders:["authorization"],redactUrlPatterns:[]},priority:201,owner:"clawdi-native-channels"})}let i=ny(e,"whatsapp");if(i&&!i.whatsappMaterial)throw Error(`managed WhatsApp Link ${i.linkId} has no valid synthetic auth`);if(i)r.push({id:"native-whatsapp-baileys-managed",enabled:!0,kind:"websocket",match:{scheme:"wss",host:"web.whatsapp.com",path:{type:"equals",value:"/ws/chat"},headers:{},query:{}},rewrite:{upstreamBaseUrl:u1(new URL("/v1/channels/whatsapp/baileys",n).toString()),preservePath:!1,setHeaders:{authorization:{type:"secretRef",secretRef:i.secretRef,prefix:"Bearer "}}},logging:{redactHeaders:["authorization"],redactUrlPatterns:[]},priority:40,owner:"clawdi-native-channels"});return r}function ije(e,t){let n=[...e?.profiles??[]],r=new Set(t.map((i)=>i.id));return{profiles:[...n.filter((i)=>!r.has(i.id)&&!oje(i)),...t]}}function oje(e){return e.owner==="clawdi-native-channels"||e.owner==="clawdi-native-whatsapp"}function sje(e,t){let n={},r=new Set(Mp(t).map((i)=>i.credsJsonSecretRef));for(let i of e){let o=i.whatsappMaterial;if(o){let s=o.credential.credsSecretRef;if(r.has(s))n[s]=JSON.stringify(uje(o))}}return n}function aje(e,t){return`secret://channels/whatsapp/${e}/links/${t}/agent-token`}function lje(e,t){return`secret://channels/whatsapp/${e}/credentials/${t}/creds-json`}function EJ(e,t,n){let r=e.whatsappMaterial;if(!r)return null;let i={};if(n.openclaw)i.openclaw={authDir:zc(t,"openclaw",e.accountKey)};if(n.hermes)i.hermes={authDir:zc(t,"hermes",e.accountKey)};if(!i.openclaw&&!i.hermes)return null;return{provider:"whatsapp",kind:"whatsapp_baileys_auth_state",accountId:e.account.id,accountKey:e.accountKey,linkId:e.linkId,credentialId:r.credential.id,files:[{path:"creds.json",secretRef:r.credential.credsSecretRef}],targets:i}}function cje(e){if(e.account.provider!=="whatsapp")return null;let t=e.credential;if(!t)return null;let{material:n}=t,r;try{r=Lp({schemaVersion:ty,authCert:n.authCert})}catch{return null}return{credential:t,creds:n.creds,authCert:r.authCert}}function uje(e){let t=e.creds.additionalData,n=t===void 0?{}:W(t);if(!n)throw Error("managed WhatsApp synthetic creds.additionalData must be an object");let r=Lp({schemaVersion:ty,authCert:e.authCert});return{...e.creds,additionalData:{...n,[Fc]:r,[Hc]:{schemaVersion:cR,credentialId:e.credential.id}}}}function dje(e){return{openclaw:e.runtimes.openclaw?.enabled===!0,hermes:e.runtimes.hermes?.enabled===!0}}function pje(e){return e.replace(/\/+$/,"")}var BTe,VTe,kJ="CLAWDI_CHANNEL_",RJ="_AGENT_TOKEN";var f1=_(()=>{Si();Lt();Yr();ey();p1();BTe=["TELEGRAM_ALLOW_ALL_USERS","DISCORD_ALLOW_ALL_USERS","HERMES_TELEGRAM_DISABLE_FALLBACK_IPS","WHATSAPP_ENABLED","WHATSAPP_MODE","WHATSAPP_ALLOWED_USERS","WHATSAPP_ALLOW_ALL_USERS","WHATSAPP_DM_POLICY","WHATSAPP_GROUP_POLICY"],VTe=["TELEGRAM_BOT_TOKEN","DISCORD_BOT_TOKEN"]});import{existsSync as xJ,readFileSync as mje}from"node:fs";function $J(e){return JSON.parse(mje(e,"utf-8"))}function _je(e){return e.issues.map((t)=>`${t.path.length>0?`${t.path.join(".")}: `:""}${t.message}`)}function CJ(e,t){let n=Us.parse(e);return{manifest:n.manifest,sourceBundle:n.sourceBundle,source:"remote-datasource",sourcePath:t,offline:!1,secretValues:Yo(n.secretValues),channelBindings:n.channelBindings,sourceRevision:n.sourceRevision}}function bje(e){let t=Up(Up(e)?.manifest)?.generation;return typeof t==="number"&&Number.isInteger(t)?t:null}async function Sje(e,t={}){let n=e.manifestSource.url,r=e.manifestSource.auth.token,i=15000,o=new AbortController,s=setTimeout(()=>o.abort(),15000);try{let a=await fetch(n,{method:"GET",headers:{accept:g1,authorization:`Bearer ${r}`,[fje]:[gje,hje].join(", "),...t.ifNoneMatch?{"if-none-match":t.ifNoneMatch}:{}},signal:o.signal}),l=a.headers.get("etag")??void 0;if(a.status===304)return{url:n,notModified:!0,etag:l};if(!a.ok){let u=await a.text().catch(()=>"");if(a.status===401||a.status===403)throw new h1(a.status,u);throw Error(`runtime manifest request failed: HTTP ${a.status}${u?` ${u.slice(0,200)}`:""}`)}let c=a.headers.get("content-type")?.split(";",1)[0]?.trim();if(c!==g1)throw new dR(`runtime manifest response content-type must be ${g1}, received ${c??"missing"}`,l);if(!l)throw Error("runtime bundle response is missing its strong ETag");try{return{url:n,raw:await a.json(),etag:l}}catch(u){throw new dR(`runtime manifest response is not valid JSON: ${U(u)}`,l)}}finally{clearTimeout(s)}}async function pR(e,t={}){let n;try{n=t.applyContext??es()}catch(s){return IJ(s)}let r;try{r=await Sje(n,t)}catch(s){return{mode:"repair",stage:Rje(s),errors:[`could not fetch runtime manifest: ${U(s)}`],...s instanceof dR&&s.etag?{etag:s.etag}:{}}}if("notModified"in r)return{source:"remote-datasource",sourcePath:r.url,notModified:!0,etag:r.etag??t.ifNoneMatch,applyContext:n};let i;try{i=CJ(r.raw,r.url),y1(i.sourceRevision,r.etag),kje(i.manifest,n)}catch(s){return{mode:"manifest-rejected",stage:"network",errors:s instanceof y.ZodError?_je(s):[U(s)],etag:r.etag,rejectedGeneration:bje(r.raw),activeGeneration:OJ(e).generation??null}}let o=Aje(i,e);if(!("manifest"in o))return{...o,etag:r.etag};return{...o,etag:r.etag,applyContext:n}}function IJ(e){return{mode:"repair",stage:"local",errors:[U(e)]}}function kje(e,t){if(t.identity&&t.identity.generation!==Jt(e))throw Error(`runtime apply identity generation ${t.identity.generation} does not match resolved manifest apply generation ${Jt(e)}`)}function y1(e,t){if(!e)return;let n=`"sha256:${e}"`;if(t!==n)throw Error(`runtime bundle ETag ${t??"missing"} does not match its sourceRevision validator ${n}`)}function Rje(e){return e instanceof h1?"auth":"network"}function OJ(e){let t=$n(e);if(!t)return{};return{instanceId:t.instanceId,generation:t.generation}}async function v1(e,t={}){let n;try{n=t.applyContext??es()}catch(o){return IJ(o)}let r=await pR(e,{applyContext:n});if("errors"in r&&r.mode==="repair"&&(r.stage==="network"||r.stage==="auth")||"notModified"in r){let o=TJ(e,!0,n);if("manifest"in o)return o;return{mode:"repair",stage:"network",errors:[..."errors"in r?r.errors:["could not fetch runtime manifest: runtime manifest datasource returned 304 without If-None-Match"],...o.errors]}}return r}function TJ(e,t,n){if(!xJ(e.manifestLastGood))return{mode:"repair",stage:"local",errors:["last-good runtime manifest does not exist"]};try{let r=$J(e.manifestLastGood),i=Up(r);if(!i)throw Error("cached runtime bundle must be an object");let o=Pje(e);if("errors"in o)return o;let s=CJ({...i,secretValues:o.secretValues},e.manifestLastGood),a=$n(e),l=uR({...s,source:"last-good-cache",sourcePath:e.manifestLastGood,offline:!0,applyContext:n},e),c=l.manifest;if(t&&c.recovery.allowOfflineBoot!==!0)return{mode:"repair",stage:"local",errors:["cached manifest does not allow offline boot"]};let u=a?Ls(a):null;if(t&&!Qo(n.identity,u))return{mode:"repair",stage:"local",errors:["cached strict-v2 apply identity does not match the current runtime apply identity; refusing offline boot"],activeGeneration:a?.generation??null};if(mR(c).length>0){let p=Eje(c,o.secretValues);if(p.length>0)return{mode:"repair",stage:"local",errors:[`cached manifest references secretValues (${p.join(", ")}); refusing offline boot because cached secret values are missing`]}}if(!a)return{mode:"repair",stage:"local",errors:["cached manifest has no durable applied authority; refusing offline boot"]};if(a.generation!==c.generation||Jt(a)!==Jt(c)||a.instanceId!==c.instanceId||a.contentIdentity.sha256!==bi({manifest:r,secretValues:o.secretValues}))return{mode:"repair",stage:"local",errors:["cached manifest does not match the durable strict-v2 apply identity; refusing offline boot"],activeGeneration:a?.generation??null};return{...l,manifest:c}}catch(r){return{mode:"repair",stage:"local",errors:[`could not read last-good runtime manifest at ${e.manifestLastGood}: ${U(r)}`]}}}function w1(e,t){return TJ(e,!1,t)}function Pje(e){if(!xJ(e.managedSecretCacheFile))return{secretValues:{}};try{let t=$J(e.managedSecretCacheFile);if(!t||typeof t!=="object"||Array.isArray(t))throw Error("cached secret values must be a JSON object");let n={};for(let[r,i]of Object.entries(t)){if(typeof i!=="string")throw Error(`cached secret value for ${r} must be a string`);n[r]=i}return{secretValues:Yo(n)}}catch(t){return{mode:"repair",stage:"local",errors:[`could not read cached runtime secret values at ${e.managedSecretCacheFile}: ${U(t)}`]}}}function mR(e){let t=new Set,n=Up(e.projection?.providers),r=!1;for(let[i,o]of Object.entries(e.runtimes)){if(!o.enabled)continue;r=!0,AJ(o.run?.secretEnv,t);for(let s of Object.values(o.services??{}))AJ(s.secretEnv,t);if(i==="openclaw"&&e.openclawGatewayAuth)t.add(e.openclawGatewayAuth.tokenRef);if(i==="hermes"&&o.services?.dashboard&&e.hermesDashboardAuth)t.add(e.hermesDashboardAuth.passwordSecretRef),t.add(e.hermesDashboardAuth.sessionSecretRef);for(let s of o.provider_ids??[]){let a=Up(n?.[s]);if(!a||xp(a))continue;if(typeof a.apiKeySecretRef==="string")t.add(a.apiKeySecretRef);let l=Up(a.auth);if(typeof l?.credentialSecretRef==="string")t.add(l.credentialSecretRef)}}if(r){for(let i of Yk(e.egressProfiles))t.add(i);for(let i of Mp(e.projection?.channelCredentials))t.add(i.credsJsonSecretRef)}return[...t].sort()}function Eje(e,t){let n=Yo(t??{});return mR(e).filter((r)=>It(n,r)===null)}function AJ(e,t){for(let n of Object.values(e??{}))t.add(n)}function Up(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:null}function Aje(e,t){let n=OJ(t),r=e.manifest,i=[];if(n.instanceId&&n.instanceId!==r.instanceId)i.push(`manifest instanceId ${r.instanceId} does not match applied instanceId ${n.instanceId}`);if(n.instanceId===r.instanceId&&n.generation!==void 0&&r.generation<n.generation)i.push(`manifest generation ${r.generation} is older than applied generation ${n.generation}`);if(i.length>0)return{mode:"manifest-rejected",stage:e.source==="remote-datasource"?"network":"local",errors:i,rejectedGeneration:r.generation,activeGeneration:n.generation??null};return e}var g1="application/vnd.clawdi.runtime-bundle.v2+json",fje="x-clawdi-runtime-capabilities",gje="agent-plugins-manifest-v1",hje="agent-plugin-github-release-source-v1",yje,vje,wje,Us,h1,dR;var ul=_(()=>{sn();Zt();eo();Ms();f1();Ap();$p();Xh();Yr();ey();yje=y.object({provider:y.enum(["telegram","discord"]),accountKey:y.string().min(1),agentTokenSecretRef:lr,placeholderTokenSecretRef:lr}).strict(),vje=y.object({provider:y.literal("whatsapp"),accountId:y.string().uuid(),accountKey:y.string().min(1),linkId:y.string().uuid(),agentTokenSecretRef:lr,placeholderTokenSecretRef:lr.optional(),credential:y.object({id:y.string().uuid(),credsSecretRef:lr,authCert:y.object({SERIAL:y.number().int().nonnegative().safe(),ISSUER:y.string().trim().min(1).max(256),PUBLIC_KEY:y.object({type:y.literal("Buffer"),data:y.string().min(1)}).strict()}).strict()}).strict()}).strict(),wje=y.discriminatedUnion("provider",[yje,vje]),Us=y.object({schemaVersion:y.literal(oJ),sourceRevision:y.string().regex(/^[a-f0-9]{64}$/),manifest:y.unknown(),applyGeneration:y.number().int().positive().safe().optional(),channelBindings:y.array(wje),secretValues:y.record(lr,y.string())}).strict().transform((e,t)=>{let n=uJ.safeParse(e.manifest);if(!n.success){for(let r of n.error.issues)t.addIssue({...r,path:["manifest",...r.path]});return y.NEVER}return{...e,sourceBundle:{...e,secretValues:{}},manifest:{...n.data,...e.applyGeneration===void 0?{}:{applyGeneration:e.applyGeneration}}}}).superRefine(pJ);h1=class h1 extends Error{status;constructor(e,t){super(`runtime manifest authentication failed: HTTP ${e}${t?` ${t.slice(0,200)}`:""}`);this.status=e}};dR=class dR extends Error{etag;constructor(e,t){super(e);this.etag=t}}});import{dirname as jJ,isAbsolute as DJ,relative as xje,resolve as _1}from"node:path";function Ije(){return process.env.CLAWDI_RUNTIME_MODE?.trim().toLowerCase()||"missing"}function k1(e,t={}){let n=t.expectedIdentity??NJ,r=Ije(),i=r==="hosted"&&e.mode==="hosted"?void 0:`hosted convergence requires CLAWDI_RUNTIME_MODE=hosted explicitly; resolved runtime mode is ${e.mode} (environment: ${r})`,o=e.userHome===n.home?void 0:`hosted runtime HOME must resolve to ${n.home}; resolved ${e.userHome}`,s=process.env.CLAWDI_RUNTIME_USER?.trim()??"",a,l=s||"missing";if(s!==n.user)a=s?`hosted runtime user must be ${n.user}; resolved ${s}`:`hosted runtime user must be ${n.user}; CLAWDI_RUNTIME_USER is missing`;else try{let c=(t.resolveUserIdentity??OV)(s);if(l=`${s} (${c.uid}:${c.gid})`,c.uid===0||c.gid===0)a=`hosted runtime user ${s} resolved to root identity ${c.uid}:${c.gid}`;else if(c.uid!==n.uid||c.gid!==n.gid)a=`hosted runtime user ${s} must resolve to ${n.uid}:${n.gid}; resolved ${c.uid}:${c.gid}`;else for(let[u,d,p]of[["CLAWDI_RUNTIME_UID",process.env.CLAWDI_RUNTIME_UID?.trim(),c.uid],["CLAWDI_RUNTIME_GID",process.env.CLAWDI_RUNTIME_GID?.trim(),c.gid]])if(d&&d!==String(p)){a=`${u} must match the resolved hosted runtime identity ${p}; resolved ${d}`;break}}catch(c){a=c instanceof Error?c.message:String(c)}return{mode:{ok:i===void 0,detail:e.mode,...i?{error:i}:{}},home:{ok:o===void 0,detail:e.userHome,...o?{error:o}:{}},user:{ok:a===void 0,detail:l,...a?{error:a}:{}}}}function iy(e,t,n={}){let r=k1(e,n),i=[r.mode,r.home,r.user].find((l)=>!l.ok)?.error;if(i)throw Error(i);let o=_1(e.clawdiHome),s=_1(e.serviceStateRoot),a=xje(_1(e.userHome),o);if(a===""||!a.startsWith("..")&&!DJ(a))throw Error(`hosted CLAWDI_HOME must be outside the tenant home; resolved ${e.clawdiHome}`);if(!DJ(e.clawdiHome)||o===s||jJ(o)!==jJ(s))throw Error(`hosted CLAWDI_HOME must be an absolute sibling of ${e.serviceStateRoot}; resolved ${e.clawdiHome}`);if(t.backend!=="incus")throw Error(`hosted v2 convergence requires runtime context backend incus; resolved ${String(t.backend??"missing")}`);if(n.platformRoots!=="deferred")cg(e);return{identity:n.expectedIdentity??NJ}}var b1="/home/clawdi",S1="clawdi",$je=10001,Cje=10001,NJ;var oy=_(()=>{gt();Un();NJ={home:b1,user:S1,uid:$je,gid:Cje}});import{spawnSync as R1}from"node:child_process";import{accessSync as Oje,constants as Tje,existsSync as UJ,lstatSync as jje,mkdirSync as Dje,mkdtempSync as Nje,readdirSync as Mje,readFileSync as Lje,readlinkSync as zJ,renameSync as Uje,rmSync as zp,statSync as zje,symlinkSync as Fje}from"node:fs";import{tmpdir as Hje}from"node:os";import{dirname as zs,join as dl,resolve as hR}from"node:path";function FJ(e){if(e.mode!=="hosted"||e.userHome!==b1||process.env.CLAWDI_RUNTIME_USER?.trim()!==S1||typeof process.geteuid==="function"&&process.geteuid()!==0)return;let t;try{t=jje(sy)}catch(r){if(r.code==="ENOENT")return;throw r}if(!t.isSymbolicLink())throw Error(`hosted tenant PATH contains an unmanaged clawdi entrypoint: ${sy}`);let n=hR(zs(sy),zJ(sy));if(n!==Zje)throw Error(`hosted tenant PATH contains an unmanaged clawdi symlink target: ${n}`);zp(sy)}function HJ(e,t,n={}){let r=ly(t,n.runningVersion),i=e.clawdiCli?.packageSpec?.trim()||null;if(r.selfReexec)return MJ("deferred",t,Fp(t),i,"CLI recovery changed the active version; re-exec is required",!0);if(!i)return ay("not_requested",t,Qje());let o=bR(i);if(!o)throw Error(`clawdi CLI packageSpec must be clawdi@<exact-semver>: ${i}`);tDe(e.clawdiCli?.registry);let s=cy(t),a=A1(t,s),l=a?.bad??null;if(a?.version===o&&Hp(t.cliManagedBin)===a.activeTarget)return MJ("current",t,a,i);if(l?.version===o&&iDe(l))return ay("deferred",t,{packageSpec:i,registry:pl,npmPrefix:a?.npmPrefix??t.cliNpmPrefix,activeTarget:a?.activeTarget??null,version:a?.version??null,retryAt:l.retryAt,error:`clawdi CLI ${o} retry is deferred until ${l.retryAt}`});let c;try{c=nDe(t,i)}catch(d){let p=U(d),m=x1(l,o,p);if(a)Vc(t,yR(a),a.previous,m);return Bp(t,a?[a.npmPrefix,LJ(a.previous)]:[]),ay("error",t,{packageSpec:i,registry:pl,npmPrefix:a?.npmPrefix??t.cliNpmPrefix,activeTarget:a?.activeTarget??Hp(t.cliManagedBin),version:a?.version??null,retryAt:m.retryAt,error:p})}a=Fp(t);let u=a?.previous??(a?eDe(a):null);wR(t.cliManagedBin,c.activeTarget);try{Vc(t,c,u,a?.bad?.version===c.version?a.bad:null)}catch(d){if(a)wR(t.cliManagedBin,a.activeTarget);else zp(t.cliManagedBin,{force:!0});throw d}return Bp(t,[ml(c.activeTarget),LJ(u)]),ay("installed",t,{packageSpec:i,registry:pl,npmPrefix:ml(c.activeTarget),activeTarget:c.activeTarget,version:c.version},!0)}function BJ(e,t){let n=Fp(e);try{if(ly(e).status==="rolled_back"&&n?.previous)return fR(n,"rolled_back");let i=Fp(e);if(!i?.previous)return fR(i,"not_pending");return VJ(e,i,t),fR(i,"rolled_back")}catch(r){return fR(n,"error",U(r))}}function E1(e,t){let n=ly(e,t);if(n.selfReexec)return n;let r=Fp(e);if(r?.previous&&r.version===t&&Hp(e.cliManagedBin)===r.activeTarget)Vc(e,yR(r),null,r.bad?.version===r.version?null:r.bad),Bp(e,[r.npmPrefix]);return n}function ly(e,t){let n=cy(e),r=A1(e,n),i=Hp(e.cliManagedBin);if(!r){if(!i)return{status:"unchanged",selfReexec:!1};let s=vR(e,{activeTarget:i});return Vc(e,s,null,null),Bp(e,[ml(s.activeTarget)]),gR("unchanged",s.version,t)}if(i!==r.activeTarget){let s=r.previous??yR(r),a=vR(e,s);if(i!==a.activeTarget)wR(e.cliManagedBin,a.activeTarget);let l=r.previous?x1(r.bad,r.version,"recovered interrupted or inconsistent clawdi CLI activation"):r.bad;return Vc(e,a,null,l),Bp(e,[ml(a.activeTarget)]),gR("rolled_back",a.version,t)}let o=qJ(e,yR(r),r);if(!o){if(!r.previous)throw Error("active clawdi CLI is not verifiable and has no rollback target");return VJ(e,r,"active clawdi CLI failed recovery verification"),r=Fp(e),gR("rolled_back",r?.version,t)}if(!SR(r.verification,o.verification)||r.verification.verifiedAt!==o.verification.verifiedAt)Vc(e,o,r.previous,r.bad);return gR("unchanged",o.version,t,r.previous!==null)}function cy(e){if(!UJ(e.cliBootstrapStatus))return null;try{return P1.parse(JSON.parse(Lje(e.cliBootstrapStatus,"utf-8")))}catch(t){return C.warn("runtime.cli_bootstrap_status_invalid",{path:e.cliBootstrapStatus,error:U(t)}),null}}function ay(e,t,n,r=!1){return{status:e,...n,npmPrefix:n.npmPrefix??t.cliNpmPrefix,npmCache:n.npmCache??t.cliNpmCache,activePath:t.cliManagedBin,retryAt:n.retryAt??null,selfReexec:r}}function Qje(){return{packageSpec:null,registry:null,activeTarget:null,version:null}}function MJ(e,t,n,r,i,o=!1){return ay(e,t,{packageSpec:r,registry:r?pl:null,npmPrefix:n?.npmPrefix??t.cliNpmPrefix,activeTarget:n?.activeTarget??Hp(t.cliManagedBin),version:n?.version??null,retryAt:n?.bad?.version===bR(r??"")?n.bad.retryAt:null,error:i},o)}function A1(e,t){let n=P1.safeParse(t);if(!n.success)return null;let r=n.data;if(r.activePath!==e.cliManagedBin||r.npmCache!==e.cliNpmCache||r.npmPrefix!==ml(r.activeTarget)||!WJ(e,r.activeTarget)||bR(r.packageSpec)!==r.version||!rDe(r.bad))return C.warn("runtime.cli_state_invalid",{path:e.cliBootstrapStatus}),null;return r}function Fp(e){return A1(e,cy(e))}function Vc(e,t,n,r){let i=$1(t.activeTarget);if(!i||!SR(t.verification,i))throw Error(`clawdi CLI target changed after verification: ${t.activeTarget}`);let o=P1.parse({schemaVersion:"clawdi.cliNpmBootstrapStatus.v1",generatedAt:new Date().toISOString(),status:"installed",source:"npm",packageSpec:`clawdi@${t.version}`,registry:pl,npmPrefix:ml(t.activeTarget),npmCache:e.cliNpmCache,activePath:e.cliManagedBin,activeTarget:t.activeTarget,version:t.version,verification:t.verification,previous:n,bad:r,error:null});Ut(e,e.cliBootstrapStatus,`${JSON.stringify(o,null,2)}
|
|
265
265
|
`,{mode:384,dirMode:493})}function yR(e){return{activeTarget:e.activeTarget,version:e.version,verification:e.verification}}function eDe(e){return{activeTarget:e.activeTarget,version:e.version}}function VJ(e,t,n){if(!t.previous)throw Error("pending clawdi CLI upgrade has no rollback target");let r=vR(e,t.previous);if(Hp(e.cliManagedBin)!==r.activeTarget)wR(e.cliManagedBin,r.activeTarget);Vc(e,r,null,x1(t.bad,t.version,n)),Bp(e,[ml(r.activeTarget)])}function fR(e,t,n){return{status:t,version:e?.version??null,previousVersion:e?.previous?.version??null,activeTarget:e?.activeTarget??null,previousActiveTarget:e?.previous?.activeTarget??null,...n?{error:n}:{}}}function gR(e,t,n,r=e==="rolled_back"){return{status:e,selfReexec:r&&n!==void 0&&t!==void 0&&t!==n}}function tDe(e){if(e===void 0||e.trim()==="")return;let t;try{let n=new URL(e.trim());n.pathname=n.pathname.replace(/\/+$/,""),n.search="",n.hash="",t=n.toString().replace(/\/$/,"")}catch{throw Error(`unsupported clawdi CLI registry: ${e}`)}if(t!==pl)throw Error(`unsupported clawdi CLI registry: ${e}`)}function bR(e){if(!Uc.safeParse(e).success)return null;return e.slice(7)}function nDe(e,t){let n=bR(t);if(!n)throw Error(`clawdi CLI packageSpec must be exact: ${t}`);let r=oDe(e,n);Bc(zs(zs(e.cliManagedBin))),Bc(zs(e.cliManagedBin)),Bc(e.cliNpmPrefix),Bc(r),Bc(e.cliNpmCache);let i=["install","-g","--prefix",r,"--cache",e.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","--registry",pl,t],o=R1("npm",i,{encoding:"utf8",timeout:Bje,env:{...process.env,NO_UPDATE_NOTIFIER:"1",NPM_CONFIG_UPDATE_NOTIFIER:"false"}});if(o.status!==0)throw Error(`npm install ${t} failed${o.status===null?"":` (${o.status})`}${o.error?`: ${o.error.message}`:""}${_R(o.stdout,o.stderr)}`);let s=dl(r,"bin","clawdi"),a=vR(e,{activeTarget:s});if(a.version!==n)throw Error(`npm install ${t} reported version ${a.version}, expected ${n}`);return a}function vR(e,t){let n=qJ(e,t);if(!n)throw Error(`clawdi CLI target is missing, inconsistent, or not executable: ${t.activeTarget}`);return n}function qJ(e,t,n){if(!WJ(e,t.activeTarget)||!dDe(t.activeTarget))return null;let r=$1(t.activeTarget);if(!r)return null;if(n?.activeTarget===t.activeTarget&&n.version===t.version&&SR(n.verification,r)&&aDe(n.verification))return{activeTarget:t.activeTarget,version:n.version,verification:n.verification};try{let i=cDe(t.activeTarget);if(t.version!==void 0&&i!==t.version)return null;if(!Uc.safeParse(`clawdi@${i}`).success)return null;return uDe(t.activeTarget),{activeTarget:t.activeTarget,version:i,verification:lDe(t.activeTarget,r)}}catch(i){return C.warn("runtime.cli_target_verification_failed",{active_target:t.activeTarget,error:U(i)}),null}}function x1(e,t,n){let r=e?.version===t?e.attempts+1:1,i=new Date,o=Math.min(Gje*2**(r-1),Kje);return{version:t,reason:n,attempts:r,failedAt:i.toISOString(),retryAt:new Date(i.getTime()+o).toISOString()}}function rDe(e){if(!e)return!0;return Number.isFinite(Date.parse(e.failedAt))&&Number.isFinite(Date.parse(e.retryAt))}function iDe(e){let t=Date.parse(e.retryAt);return Number.isFinite(t)&&Date.now()<t}function oDe(e,t){if(!/^[0-9A-Za-z._+-]+$/.test(t))throw Error(`resolved clawdi CLI version contains unsafe path characters: ${t}`);return dl(e.cliNpmPrefix,"packages",t)}function ml(e){return zs(zs(e))}function LJ(e){return e?ml(e.activeTarget):null}function sDe(e,t){let n=hR(e.cliNpmPrefix),r=hR(t);return r===n||r.startsWith(`${n}/`)}function WJ(e,t){return sDe(e,t)&&t.endsWith("/bin/clawdi")}function Bc(e){Dje(e,{recursive:!0})}function Hp(e){try{return hR(zs(e),zJ(e))}catch{return null}}function wR(e,t){let n=zs(e);Bc(zs(n)),Bc(n);let r=`${n}/.clawdi.next.${process.pid}.${Date.now()}`;try{zp(r,{force:!0}),Fje(t,r),Uje(r,e)}catch(i){throw zp(r,{force:!0}),i}}function Bp(e,t){let n=dl(e.cliNpmPrefix,"packages");if(!UJ(n))return;let r=new Set(t.filter((i)=>Boolean(i)));try{for(let i of Mje(n,{withFileTypes:!0})){if(!i.isDirectory())continue;let o=dl(n,i.name);if(!r.has(o))zp(o,{recursive:!0,force:!0})}}catch(i){C.warn("runtime.cli_package_prune_failed",{package_root:n,error:U(i)})}}function $1(e){try{let t=zje(e);return{device:t.dev,inode:t.ino,size:t.size,modifiedAtMs:t.mtimeMs}}catch{return null}}function SR(e,t){return e.device===t.device&&e.inode===t.inode&&e.size===t.size&&e.modifiedAtMs===t.modifiedAtMs}function aDe(e){let t=Date.parse(e.verifiedAt),n=Date.now()-t;return Number.isFinite(t)&&n>=0&&n<Wje}function lDe(e,t){let n=$1(e);if(!n||!SR(t,n))throw Error(`clawdi CLI target changed during verification: ${e}`);return{verifiedAt:new Date().toISOString(),...n}}function _R(e,t){let n=[e,t].filter(Boolean).join(`
|
|
266
266
|
`).trim();return n?`: ${n.slice(0,1000)}`:""}function cDe(e){let t=R1(e,["--version"],{encoding:"utf8",timeout:Vje,env:{...process.env,CLAWDI_NO_AUTO_UPDATE:"1",CLAWDI_NO_UPDATE_CHECK:"1"}});if(t.status!==0)throw Error(`installed clawdi did not pass --version smoke check${t.status===null?"":` (${t.status})`}${t.error?`: ${t.error.message}`:""}${_R(t.stdout,t.stderr)}`);let n=t.stdout.trim().split(/\r?\n/,1)[0]?.trim();if(!n)throw Error("installed clawdi --version returned empty output");return n}function uDe(e){let t=Nje(dl(Hje(),"clawdi-runtime-verify-")),n;try{n=R1(e,["runtime","verify","--json"],{encoding:"utf8",timeout:qje,env:{...process.env,HOME:dl(t,"home"),CLAWDI_SERVICE_STATE_DIR:dl(t,"state"),CLAWDI_RUN_DIR:dl(t,"run"),CLAWDI_NO_AUTO_UPDATE:"1",CLAWDI_NO_UPDATE_CHECK:"1"}})}finally{zp(t,{recursive:!0,force:!0})}if(n.status!==0)throw Error(`installed clawdi did not pass runtime verify self-check${n.status===null?"":` (${n.status})`}${n.error?`: ${n.error.message}`:""}${_R(n.stdout,n.stderr)}`);let r=n.stdout.trim();if(!r)throw Error("installed clawdi runtime verify self-check returned empty output");try{y.object({status:y.literal("ok")}).loose().parse(JSON.parse(r))}catch(i){throw Error(`installed clawdi runtime verify self-check returned invalid JSON: ${U(i)}${_R(n.stdout,n.stderr)}`)}}function dDe(e){try{return Oje(e,Tje.X_OK),!0}catch{return!1}}var pl="https://registry.npmjs.org",Bje=180000,Vje=20000,qje=20000,Wje=300000,Gje=60000,Kje=3600000,sy="/usr/local/bin/clawdi",Zje="/usr/local/lib/node_modules/clawdi/bin/clawdi.mjs",Jje,Yje,Xje,P1;var kR=_(()=>{sn();Zt();oy();Xh();Un();Jje=y.object({verifiedAt:y.string().min(1),device:y.number().int().nonnegative(),inode:y.number().int().nonnegative(),size:y.number().int().nonnegative(),modifiedAtMs:y.number().nonnegative()}).strict(),Yje=y.object({activeTarget:y.string().min(1),version:y.string().min(1)}).strict(),Xje=y.object({version:y.string().min(1),reason:y.string().min(1),attempts:y.number().int().positive(),failedAt:y.string().min(1),retryAt:y.string().min(1)}).strict(),P1=y.object({schemaVersion:y.literal("clawdi.cliNpmBootstrapStatus.v1"),generatedAt:y.string().min(1),status:y.literal("installed"),source:y.literal("npm"),packageSpec:Uc,registry:y.literal(pl),npmPrefix:y.string().min(1),npmCache:y.string().min(1),activePath:y.string().min(1),activeTarget:y.string().min(1),version:y.string().min(1),verification:Jje,previous:Yje.nullable(),bad:Xje.nullable(),error:y.string().nullable()}).strict()});import{createHash as pDe}from"node:crypto";import{lstatSync as qc,readdirSync as ZJ,readFileSync as GJ,rmSync as mDe}from"node:fs";import{dirname as fDe,join as RR}from"node:path";function KJ(e){return pDe("sha256").update(e).digest("hex")}function uy(e,t,n,r,i,o){if(!JJ.test(n))throw Error("archive cache key is invalid");let s=RR(t,n);if(fDe(s)!==t)throw Error("archive cache key escapes its root");let a=RR(s,r),l=RR(s,"receipt.json"),c=()=>{try{return qc(s),!0}catch(p){if(p instanceof Error&&"code"in p&&p.code==="ENOENT")return!1;throw p}},u=()=>{try{let p=qc(a),m=qc(l);if(!p.isFile()||p.isSymbolicLink()||p.size>o||(p.mode&511)!==384||!m.isFile()||m.isSymbolicLink()||m.size>gDe||(m.mode&511)!==384||typeof process.getuid==="function"&&(p.uid!==process.getuid()||m.uid!==process.getuid()))return null;let f=i.parse(JSON.parse(GJ(l,"utf8"))),h=GJ(a);return f.key===n&&KJ(h)===f.archiveSha256?h:null}catch{return null}},d=(p={})=>{try{let m=qc(t),f=qc(s);if(!m.isDirectory()||m.isSymbolicLink()||!f.isDirectory()||f.isSymbolicLink()||p.allowIncomplete!==!0&&u()===null)return!1;for(let h of ZJ(s)){if(h!==r&&h!=="receipt.json")return!1;let v=qc(RR(s,h));if(!v.isFile()||v.isSymbolicLink())return!1}return mDe(s,{recursive:!0}),!0}catch(m){if(m instanceof Error&&"code"in m&&m.code==="ENOENT")return!1;throw m}};return{exists:c,read:u,write:(p,m)=>{if(p.length>o)throw Error("archive exceeds its cache limit");let f=KJ(p),h=m(f),v=i.parse(h);if(v.key!==n||v.archiveSha256!==f)throw Error("archive cache receipt does not match its entry");try{Ut(e,a,p,{mode:384,dirMode:448}),Ut(e,l,`${JSON.stringify(h,null,2)}
|
|
267
267
|
`,{mode:384,dirMode:448})}catch(w){throw d({allowIncomplete:!0}),w}},remove:d}}function PR(e,t,n,r,i,o){let s;try{let a=qc(t);if(!a.isDirectory()||a.isSymbolicLink())return;s=ZJ(t)}catch(a){if(a instanceof Error&&"code"in a&&a.code==="ENOENT")return;throw a}for(let a of s)if(JJ.test(a)&&!n.has(a))uy(e,t,a,r,i,o).remove()}var JJ,gDe=4096;var C1=_(()=>{Un();JJ=/^[a-f0-9]{64}$/});import{createHash as hDe}from"node:crypto";import{chmodSync as yDe,existsSync as vDe,lstatSync as QJ,mkdirSync as YJ,mkdtempSync as e3,readFileSync as t3,rmSync as O1,writeFileSync as wDe}from"node:fs";import{validateHeaderName as _De,validateHeaderValue as bDe}from"node:http";import{isIP as SDe}from"node:net";import{tmpdir as n3}from"node:os";import{dirname as kDe,join as Wc}from"node:path";function DDe(e){return k_(e)}function VDe(e){let[t,n=""]=e.split(":");return[Number.parseInt(t??"",16),n.split(",").map((r)=>String.fromCodePoint(Number.parseInt(r,16))).join("")]}function d3(e){let t="";for(let n of e){let r=n.codePointAt(0);if(r===void 0)continue;let i=qDe.get(r);if(i!==void 0)t+=i;else if(r>=5024&&r<=5109||r>=5112&&r<=5117||r>=43888&&r<=43967)t+=n.toUpperCase();else t+=n.toLowerCase()}return t}function p3(e){return hDe("sha256").update(e).digest("hex")}function m3(e,t){let n=t.source.type==="github"?[t.source.type,t.source.url,t.source.path,t.source.commit]:[t.source.type,t.source.url,t.source.archiveDigest];return p3(JSON.stringify([t.installationId,e,t.version,t.agentPluginsSchema,...n,t.contentDigest]))}function WDe(e,t){return j1.parse({...t,ownershipIdentity:m3(e,t)})}function f3(e){return Wc(e.statusRoot,"runtime-agent-plugin-receipts.json")}function Gc(e){let t=f3(e),n;try{n=QJ(t)}catch(r){if(r instanceof Error&&"code"in r&&r.code==="ENOENT")return null;throw Error("Agent Plugin receipts could not be inspected")}if(!n.isFile()||n.isSymbolicLink()||n.size>IDe)throw Error("Agent Plugin receipts are not a trusted regular file");if((n.mode&511)!==384)throw Error("Agent Plugin receipts do not have private file permissions");if(typeof process.getuid==="function"&&n.uid!==process.getuid())throw Error("Agent Plugin receipts do not have the expected file owner");try{let r=JSON.parse(t3(t,"utf8"));return c3.parse(r)}catch{throw Error("Agent Plugin receipts do not match the expected schema")}}function g3(e,t){let n=f3(t);if(!e||Object.keys(e.installations).length===0){O1(n,{force:!0});return}let r=c3.parse(e),i=Gc(t),o=`${JSON.stringify(r,null,2)}
|